Arduino PWM Tutorial #1 - How To Change PWM Frequency

Поділитися
Вставка
  • Опубліковано 13 вер 2024
  • The Arduino has a fixed PWM frequency of 490Hz - or does it? On digital pins 3, 9, 10 and 11 it's 490Hz, but on pins 5 and 6 it's 976Hz. Confused?
    And it is possible to change the PWM frequency to a higher (or lower) frequency by altering the timer prescalers. Here's how it's done.

КОМЕНТАРІ • 89

  • @JulianIlett
    @JulianIlett  11 років тому +6

    Thanks Shaun. I found a very nice PWM library (shown in my part2) which sets up all the registers and has a 'safe' mode to protect millis() and delay() by not changing anything related to Timer0

  • @JulianIlett
    @JulianIlett  11 років тому +5

    Yes, delay() and millis() are affected by changing the prescaler for timer0. If you want to avoid that, you should change timer1 and/or timer2 instead. Not sure what side effects would result from doing that though - anyone know?

  • @webslinger2011
    @webslinger2011 5 років тому

    Was fumbling around for 3 days looking for this. This will help on my arduino audio school project. Thanks!!!

  • @craiglarson6793
    @craiglarson6793 7 років тому +1

    Great stuff. You highlight one of the many abstractions that Arduino programming language/IDE manages for users in the background. I'm guessing that it may be easier to go straight to C programming for the PWM and Timer peripherals where the full power of all the options are available. But then it wouldn't be an Arduino topic. Thanks for your videos and clear instructions!

  • @T1iCanon
    @T1iCanon 9 років тому +1

    Thank you Julian , I fixed that ugly humming noise of a dc motor by changing the frequeny , now it is even more controlable and really quiet.

    • @mjosbesh
      @mjosbesh 6 років тому +1

      What frequency did you use? I'm using 976 HZ (pins 5&6) currently and the dc motor sound is annoying at low PWM.

  • @cowsongs
    @cowsongs Рік тому

    THANK YOU. This is huge for driving any non-trivial load off an Arduino pin. For an LED, it's fine. But if you want to drive some other entire circuit module, maybe some transistor circuit, etc, and you need to approximate smooth DC, a PWM at high frequency can very efficiently and simply be filtered to reasonably smooth DC with a small cap and resistor, much more easily (and with quicker response) than low freq 490 Hz PWM.

  • @chbonnici
    @chbonnici 5 років тому +2

    I tried this and works perfectly as you said. Very helpful. A thousand thanks

  • @ECOENERGI1
    @ECOENERGI1 6 років тому

    Hi Julian, I used this info on one of my projects to eliminate audible noise that I was getting at the lower 976hz. Thanks for sharing, regards Roger

  • @elninorosario
    @elninorosario 7 років тому +3

    just a suggestion! ..
    well u might think that a pencil is harmless when u use it to point adruino pins.
    But unfortunately graphite(pencil lead) is a conductor of electricity.. so be careful👍

  • @h3ctor1991
    @h3ctor1991 5 років тому +1

    Thank you so much Julian, it's a excellent tutorial.
    Regards from Colombia!

  • @icarossavvides2641
    @icarossavvides2641 3 роки тому

    I think you'll find that the discrepancy between the expected and measured nominal 31Khz frequency at the end of the video is down to being on too slow a 'scope range, if you set to 1us/div you'll likely be closer to target.

  • @ArcanePath360
    @ArcanePath360 8 років тому

    setting pins as output is usually a good idea if you've had another sketch previously on it, setting it as an input. This is how pins are destroyed. It's not necessary just good practice.

  • @kbssaprodussoes
    @kbssaprodussoes 8 років тому +8

    void setup() {
    TCCR2B = (TCCR2B & 0xF8) | value;
    }
    For the lazy, just change "value" for 1 to 7 according to this:
    31372.5 Hz -> 1
    3921.57 Hz -> 2
    980.392 Hz -> 3
    490.196 Hz -> 4 (default)
    245.098 Hz -> 5
    122.549 Hz -> 6
    30.6373 Hz -> 7

    • @Felipe-dg6kp
      @Felipe-dg6kp 6 років тому

      hello. Thank you i dont speak enghlish i have a question if i want set frecuency to 62.5 khz ¿ i can with arduino nano but not in the timer 0 (for the millis and delay)?

  • @atleastsomethinghapp
    @atleastsomethinghapp 9 років тому

    Thank you for this very clear and useful lesson!

  • @paulmeynell8866
    @paulmeynell8866 4 роки тому

    Excellent as usual

  • @Fleurlean4
    @Fleurlean4 8 років тому +2

    Very helpful man you are, thank you.

  • @TheGiselaSchumacher
    @TheGiselaSchumacher 9 років тому

    I'm designing a voltage controlled phase controller for AC lamp dimming that I intend to drive via an Arduino Uno. I'm attaining an analog voltage by passing the PWM outputs through a simple R/C network to generate a constant voltage proportional to the duty cycle of the PWM signal. To get a voltage output that changes fast but still has no noticeable ripple, I need a high frequency PWM signal. I've had this prescaler change work on both timers 0 and 1 of my Arduino Uno, giving me adequately high frequencies for my project. The only problem is, serial communications rely on timer 0, and the Arduino needs to be controlled via serial. This being said, most people would think that using timer 2 would be the obvious answer. So did I. However, when I set the prescaler of timer 2 to 1, PWM on pins 3 and 11 stopped working all together. an analog value from 0 to 254 yielded a logic 0, and 255 yielded a logic 1. Can anyone tell me why changing the prescaler on timer 2 of the Arduino Uno doesn't work? Am I doing something wrong, or is it just not possible to do? Thank you for any help!

    • @TheGiselaSchumacher
      @TheGiselaSchumacher 9 років тому

      Nevermind the issue stated in the last comment. I made a silly mistake. Well, in essence, so did the sources for how to change PWM speeds. They all say to use a code like this:TCCRnB = TCCRnB & 0b11111000 | mode;with mode being the prescaler setting. That works great for timers 0 and 1, because their mode is 3, or 011 in binary. since we're increasing the speed, setting one of those two LSBs to 0 will change their state as seen by a truth:011 & 010 = 010011 & 001 = 001011 & 000 = 000 (noting that this shuts off the PWM all together)However, timer 3 has an initial prescaler of 4, or 100 in binary, so a speed increase will yield these truths:100 & 011 = 000100 & 010 = 000100 & 001 = 000100 & 000 = 000As you can see here, using the commonly given code for prescaler alteration, an attempt to increase the speed will simply disable the PWM for 3 and 11 all together, hence my problem. A simple solution is to change the line of code to this:TCCR2B = TCCR2B + (4 - mode);with mode still being the same prescaler values.Setting mode to 1 will subtract three from the original value of TCCR2B without affecting anything beyond the prescaler values, so, knowing that 100 in binary is 4 in decimal, we can calculate the new prescaler:TCCR2B + (4 - mode)4 + (4 - 1) = 4 + -3 = 4 - 3 = 1I have tested this new code, and it does in fact work for the Arduino Uno PWM pins 3 and 11. The code can also be altered for TCCR0B and TCCR1B as such:TCCRnB = TCCRnB + (3 - 1);NOTE: once the timer speed has been altered using this code, altering it again with the same code will yield errors. This could be remedied with a code like this:int oldPrescaler = x; //set x to 3 for TCCR0B/TCCR0B, and 4 for TCCR2B
      void setPWMSpeed(newPrescaler){ TCCRnB = TCCRnB + (oldPrescaler - newPrescaler); oldPrescaler = newPrescaler;}This code will automatically compensate for a previously set prescaler if you should ever wish to change it again during a program.Noting how this hasn't been covered anywhere on the internet that I can find, I hope this helps anyone else stuck on the same issue!

    • @TheGiselaSchumacher
      @TheGiselaSchumacher 9 років тому

      I apologize if the code is confusing in line with the text, I forgot that UA-cam does that in comments. If you need any piece of the code in proper format, I can email you a text file of it. Happy coding!

  • @alingeorge8160
    @alingeorge8160 7 років тому +1

    Sir very informative...

  • @mendebil
    @mendebil 5 років тому

    This is awesome. thanks for sharing

  • @aitorsierra
    @aitorsierra 11 років тому

    changing timer prescaler affects to some functions such as delay() or servo library ?., Thanks

  • @sirius8ly
    @sirius8ly 8 років тому

    Thanks Jullian.

  • @Dahaksha
    @Dahaksha 8 років тому

    @3.05 you say that the pin D13 is missing, it's actually located on the down-left side of the arduino, just look for it. Great video nonetheless.

    • @Inertia888
      @Inertia888 4 роки тому

      I think he meant that he was wishing that D13 was a PWM channel, since it already has an onboard LED. Would be handy for experimenting.

  • @alf3071
    @alf3071 Рік тому

    i don't get why it is so hard to change the frequency, I still don't get how it works and have to copy pre made code

  • @YousefAboAnNour
    @YousefAboAnNour Місяць тому

    video: 11 minutes
    info: 10 seconds
    useful stuff starts at 9:00

  • @josemalibran4174
    @josemalibran4174 6 років тому

    Hey man
    I have a question, is it possible to work PWM at low frequencies? on the order of 4 to 10 Hz? Greetings man

  • @seancarney1647
    @seancarney1647 6 років тому

    Does the nano have the capability to read a frequency and control a device based on that frequency as it changes?

  • @superrodder2002
    @superrodder2002 9 років тому

    if you used a different frequency crystal to control the clock speed of the chip, wouldn't that change the frequency for the pwm output?

  • @maxxiang8746
    @maxxiang8746 4 роки тому

    Very helpful

  • @MkmeOrg
    @MkmeOrg 11 років тому

    Nice!

  • @mustafaglnr8780
    @mustafaglnr8780 5 років тому

    with the last included codes, will produce 50kHz frequency from arduıno as a PWM pulse.?

  • @MrBobWareham
    @MrBobWareham 10 років тому

    Padding resistors should always be used at each end of a pot to stop short outs say 1k0 or lower but love your Arduino Videos
    Bob

  • @CrazyHHO19
    @CrazyHHO19 6 років тому

    hello i was wondering if you would be able to help me.i have puls generator.how can i program it to run 10% duty cycle at 0.64 v input and gradually increacing voltage to 3.86v with duty cycle 90%.its for my project where voltage coming from throttle position sensor potenciometer control my pulse/duty cycle generator which then directly control fuel injector.any advice most appreciated cheers joe

  • @sunilshailon6656
    @sunilshailon6656 6 років тому

    can pwm frequency be changed in an arduino uno similarly??

  • @ctbully
    @ctbully 7 років тому

    A link to the tables would be nice :-)

  • @alingeorge8160
    @alingeorge8160 7 років тому

    Thank u so much

  • @boubalex5846
    @boubalex5846 7 років тому

    Can I take from arduino, PWM with duty cycle 20% and frequency 10Khz or 20 khz???

  • @TYGAMatt
    @TYGAMatt 4 роки тому

    This is many moons old, but would like to ask how you got the PWM library to install. I've had no luck!
    Tried installing from manage libraries but it doesn't show up and tried the include library/zip file from the sketch. Just says the PWM.h file doesn't exist. Most frustrating.

    • @TYGAMatt
      @TYGAMatt 4 роки тому

      Ignore my message. I did that thing that you should never do, and that's actually take notice of what the error says. All sorted and will compile now. Ooops

  • @sirius8ly
    @sirius8ly 8 років тому

    Just a quick question. Is the analogWrite duty cycle pre-established. I am going for a 50 percent duty and I am generating the 31khz from D9 like you showed in your video. Thank you.

    • @backcountry52
      @backcountry52 8 років тому

      analogWrite(pin,duty) is the syntax for the function. Duty is a scaled input from 0-255. 0 commands a 0% duty cycle, 255 commands 100%. For 50 percent enter 127.

    • @sirius8ly
      @sirius8ly 8 років тому

      +backcountry52 Thanks for the info. I really appreciate it. Cheers!

  • @wiraramadhan2227
    @wiraramadhan2227 5 років тому

    how can you change the arduino prescaller to 8 of a timer ? hmmm

  • @DrOdayAAhmed
    @DrOdayAAhmed 8 років тому

    thanks a lot

  • @lalortech5286
    @lalortech5286 6 років тому

    Hello, does anyone knows where I can download a copy of the header.h file, as Julians website has been down now for some time? I need a copy to be able to compile and upload to Arduino Nano.

  • @keltoumaiaiouss3869
    @keltoumaiaiouss3869 6 років тому

    How can I set the output to 20 kHz in arduino mega please I need your help

  • @usmanyaqoob6765
    @usmanyaqoob6765 4 роки тому

    Hello
    can i reduce frequency to 10hz

  • @bobc5151
    @bobc5151 10 років тому

    if you need two output frequencies can you program the second to have a 90 deg phase shift?

    • @JulianIlett
      @JulianIlett  10 років тому

      Yes, I think so. I'm going to produce a video on that quite soon. It's for a charge pump circuit where I want two PWM signals 180° out of phase, but 90° would be just as easy to implement.

  • @vladimirsch.3015
    @vladimirsch.3015 6 років тому

    Hudge thx to you.

  • @ztitan69
    @ztitan69 9 років тому +3

    How can you change the exact frequency to 10khz?

    • @JulianIlett
      @JulianIlett  9 років тому +3

      I did that in the follow up video

    • @SuperLefty2000
      @SuperLefty2000 9 років тому

      Julian Ilett Hey Julian, my friend created a non-overlapping pwm signal by using PIC18 without any extra hardware. Have you tried it with PIC? I mean how is it non possible with an Arduino?

    • @NaeemAwan36
      @NaeemAwan36 8 років тому +1

      will u give me the link of follow up video for 10 khz cuz i didnt find it in ur channel i wana generate 20 khz pwm

    • @chbonnici
      @chbonnici 5 років тому

      enjoy
      ua-cam.com/video/9JXGIeM3BSI/v-deo.html

    • @chbonnici
      @chbonnici 5 років тому

      when I load ver5 pwm iI could not get it to work keep getting message "Error compiling for board Arduino /Genuino Uno"

  • @beymeephanlom1246
    @beymeephanlom1246 9 років тому +4

    /*
    Prorotype Code for 1-4MHz PWM 50% Duty Cycle
    ICR1as TOP = crystal / (2*Prescale*Fpwm) in MODE 9

    at 16000000MHz 64 Prescale PWM Fmax = 62.5KHz
    at 16000000MHz 8 Prescale PWM Fmax = 500KHz
    at 16000000MHz 1 Prescale PWM Fmax = 4MHz
    */
    void setup(){
    pinMode(9, OUTPUT); // OCR1A Output
    pinMode(10, OUTPUT); // TEST Pin 10 as General purpose that can use after Enabling only OCR1A
    digitalWrite(10, LOW);
    delay(1000);
    digitalWrite(10, HIGH);
    //phase/frequency correct mode. SELECT THIS FOR INVERTED OUTPUTS.
    TCCR1A = _BV(COM1A1); // Enable OCR1A none inverting mode
    //TCCR1A = _BV(COM1A1) | _BV(COM1B1) ; // Enable OCR1A and OCAR1B and none inverting mode
    // TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(COM1A0) | _BV(COM1B0);
    //TCCR1B = _BV(WGM13) | _BV(CS11); // Set Prescale Clock 8 and Mode 9
    TCCR1B = _BV(WGM13) | _BV(CS10); // Set Prescale Clock 1 and Mode 9
    }
    void loop(){
    //ICR minimum 2 F = 16000000MHz No Change if using 14745600MHz
    //make this variable as table
    //ICR1 = 10,000; // 100Hz w/16MHz Prescale 8
    //ICR1 = 5,000; // 200Hz w/16MHz Prescale 8
    //ICR1 = 2; // 500KHz w/16MHz Prescale 8
    ICR1 = 2; // 4MHz w/ 1600000MHz Prescale 1
    OCR1A = ICR1 / 2; // 50 Duty of ICR1
    }

  • @IngenieurEdis
    @IngenieurEdis 8 років тому

    Hello. Is it possible to switch multiple frequencies with switches ? For exampe i want to drive a DC Motor with 500HZ, 1000Hz and 2000HZ , but i dont wont to change the code every time, but to change it with a switch mechanical. Is there a possibility to program a code witch recognizes witch switch i turned on, so the PWM works with the frequency. Sorry for my bad english.

    • @EngineeringNibbles
      @EngineeringNibbles 8 років тому +1

      You simply change the pwm %
      pwm frequency has no impact on the speed of your motors

  • @engrmhhassan7699
    @engrmhhassan7699 7 років тому

    how to change frequency upto 50hz?

  • @stevec5000
    @stevec5000 6 років тому

    How can I set the output to 130 Hz? I tried running the sketch in Tutorial #2 but it won't compile, it's worthless!

    • @Inertia888
      @Inertia888 4 роки тому

      I see that your question is from a few years ago, and I am honestly just beginning to understand how to manipulate these frequencies. But I wonder if changing the clock speed would allow us to have more control over a wider range of frequencies? Hopefully I don't sound too illiterate to you. Mostly I hope you have since solved this issue but as a beginner, trying to think this through seems to be helping me to grasp the concepts at a deeper level. Maybe I'm even close. Would love to hear what your solution was to this problem. Cheers!

  • @horacewonghy
    @horacewonghy 6 років тому

    great! i would use 62k for a class d projet

  • @sribalaji4289
    @sribalaji4289 2 роки тому

    Its varying the duty cycle 🥲

  • @baadikarim
    @baadikarim 4 роки тому

    Plz code 3-phase

  • @troydry1402
    @troydry1402 7 років тому

    I'm trying to run an rgb led off pins 3 5 and 6 but thinks pins 5 and 6 are the same why is this happening

    • @JulianIlett
      @JulianIlett  7 років тому +1

      +Troy Dry pins 5 and 6 use the same internal timer

  • @mhalw12
    @mhalw12 10 років тому

    hi Julian, i have been watching your video but i got questions. it is really possible to change the frequency of pwm up to 500kHz or it is limited up to 64kH on pin 5 and 6?
    thank you.

    • @JulianIlett
      @JulianIlett  10 років тому +1

      I think you can go to quite high frequencies, but you will lose resolution. So at 500kHz you may only get 3 or 4 different pulse width values.

  • @tejeshwvardhan1165
    @tejeshwvardhan1165 8 років тому

    can all 6 pwm run on same frequency of about 10khz?

    • @Inertia888
      @Inertia888 4 роки тому

      I have a related question that I am currently in the process of attempting to understand. I would like to know if each PWM channel, can output a different frequency simultaneously. For example, have Pin5 send a lower frequency to one motor, Pin9 send a somewhat faster frequency to a 2nd motor, and also have Pin11 send a higher frequency to a third motor?

  • @mihajlopetkovic2003
    @mihajlopetkovic2003 7 років тому +3

    When you change frequency and after that upload different sketch, does it set PWM frequency to default?

    • @thepvporg
      @thepvporg 6 років тому

      I think its changed to that speed when the sketch runs, thats how I understand the underclocking process.

  • @pooraramjakhar3224
    @pooraramjakhar3224 4 роки тому

    Can you run HDD ~18000RPM
    With controlled speed
    By this arduino
    I will pay for this
    It's part of my huge project..

  • @Dontlikeyellow
    @Dontlikeyellow 6 місяців тому

    Chat to find code 6:25

  • @MTB.J
    @MTB.J 9 років тому

    how to have code

    • @MTB.J
      @MTB.J 9 років тому

      Adrien Feudjio Temgoua yep je know mais sa dependra exactement du type de projet

  • @g0n4ds3
    @g0n4ds3 11 років тому

    very

  • @thepvporg
    @thepvporg 6 років тому

    LOL, you cooked the track I bet.