Yes i messed up the math's! Let me have one last try to get it right.
OKEY DOKEY
STEP 1. Decide PWM frequency, the lower the frequency the slower the clock can be. But you dont have as much resolution (number of slots in that period), also slower the frequency, the more chance of unwanted type flicker (flashing). So frequency is a trade off of speed V Resolution (smoothness).
I would start at around 100Hz, this should be fast enough for good smoothness, but not so fast the micro cant do other stuff, like update variables. Also 100Hz makes the math's easier (well was meant to
).
SO STEP 1 = 100Hz
STEP 2. Workout how much time is in 100Hz, so frequency is divided by time.
1 SECOND / 100Hz (they are reciprocal, which i think means you can ignore the S and the Hz) so we get
1/100 =0.01 as we want a time measurement, the
0.01 is in seconds. SO
0.01s =10ms (10 mili seconds)
Now we know the following for timer, Interrupt based smooth PWM we need a
PERIOD of
10ms
Or to phrase it another way, if you set a timer to something every 10ms then its frequency is
100Hz
This is magic!! as normally we like to have the
DUTY CYCLE Between
1 AND 100 (well 99 as 100 is just fully on or straight DC)
STEP 3.
We know we need to set the timer so it triggers
100 TIMES every
10ms. So now we work out what
10ms is Divided by
100
10ms/100= 0.0001s OR
100us (100 micro seconds)
Quick recap, if we want a PWM frequency of 100Hz and a Duty Cycle between 1 and 100, we set the timer to interrupt our micro every 100 micro seconds. BUT THEN WHAT??
WE ARE NOW INSIDE THE ISR. NOT! THE MAIN CODE
STEP 4. INSIDE the
ISR (
Interrupt
Service
Routine) We (actually you!) place a variable, lets call it
duty_cycle.
STEP 5. EVERY time the timer fire's the interrupt (
Once every 100 us) we check that
duty_cycle = < (Less than) 100.
Because, if we want a maximum DUTY CYCLE of 100 (on fully on) then
duty_cycle must be less than 100
IF duty_cycle<(Less than) 100 We (you)
ADD 1 To
duty_cycle
WE ARE NOW OUTSIDE ISR IN MAIN PROGRAM
In your main code you have an array, Lets call it DUTY_CYCLE (i lack imagination this time of night) actually keep these names, it makes the code make more sense to read, now you know that duty_cycle is the Variable inside the ISR, that keeps a count of how many times the 100 us (micro seconds) has passed.
And you also know that DUTY_CYCLE is a array outside the ISR , that in a bit we will put values in .
I have named one array to make it simple to follow, I dont know if you know how to set a multi dimensional array?
ACTUALLY before i go on i do need to know that, If you know how to do an array with more than 1 element in swordfish then i will go one way with this, If you dont then we can go another way.
so please answer that QUESTION and i will continue with a step by step break down of what you need to do, I promise at the end of this you will know 2 things, 1 how to do software pwm on ANY chip with timer and 2 make a kick arse NON REDNECK candle