1. Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.
    Dismiss Notice

Yet another PWM newbie

Discussion in 'Microcontrollers' started by erospawn, Apr 16, 2010.

  1. erospawn

    erospawn New Member

    Joined:
    Apr 12, 2010
    Messages:
    12
    Likes:
    0
    Hi,

    I've been tryin to understand from a coding standpoint how to write a software pwm. I understand what Pwm is and how it works, I think.. So, what I am trying to do understand the the external clock vs internal clock and the Timers etc.. So, if I have a 4mhz clock, my internal frequency would be 1Mhz ? If I set the prescaler, would that apply to just the timer?
    If I set the prescaler to say 1:16 @ 1mhz clock, then my frequency would be 244hz?
    Im just trying to figure out the frequency so I can base the duty cyle on the amount of time in each per step.. 1% 5% 10% and so on.. and essentially create a lookup table..

    In other words, a main loop that uses the TMR0 with interupt overflow to slow the speed of each transition so it doesn't get bright super fast. I was going to use a lookup table to supply values based on the clock cycle to reach a certain level in the duty cycle. The ultimate goal being to flip a switch and it slowly fade in or slowly fade out.

    I know Hardware pwm is much easier, but like I said, I want to try it in software first.
     
  2. Wond3rboy

    Wond3rboy Member

    Joined:
    Jun 25, 2008
    Messages:
    762
    Likes:
    7
    Location:
    Sindh,Pakistan
    Hi,

    If you set the prescaler to 1:16 with a 1MHz clock source then,1MHz/16 = 62.5KHz will be the freq of the timer, the timer will increment every 16us. You can use a lookup table to set the values for the timer register(TMRx). Set the pin high, then load the values from the look up table, when the timer overflows then turn the pin low and there you go, you got PWM with duty cycle of, TMR value set/max TMR value possible.

    Bear in mind you will need to add some instructions to compensate for the additional clock cycles, use the MPAB SIM Logic Analyzer to find that out.
     
  3. erospawn

    erospawn New Member

    Joined:
    Apr 12, 2010
    Messages:
    12
    Likes:
    0
    Awesome! Thanks.
     

Share This Page