??? 06/25/05 22:34 Read: times Msg Score: +1 +1 Good Question |
#95918 - General Pulse Width Modulation on 8051 |
Hello all,
I am trying to learn how to do PWM with timers on 8051 architecture. My goal is this: Generate a pulse with a width of 1.4 ms with frequency of 55 Hz on pin P1.0. So after reading a number of tutorials, my logic went like this: For my chip and crystal 1 machine cycle is 0.001085 ms. I want the frequency to be 55 times/second so the period is: 1 / 55 = 0.018181818 or 18.181818182 ms. The peak or high state should be 1.4 ms long. So the low state should be: 18.181818182 - 1.4 = 16.781818182 ms So in terms of machine cycles, for 1.4 ms. I need: 1.4 / .001085 =~ 1290 cycles and for 16.781818182 ms I need: 16.781818182 / .001085 =~ 15467 cycles So my assumption is that the timer in Mode 1 (16-bit) will always overflow at 65535. So for a 1.4 ms time I need to start the timer at: 65535 - 1290 = 64245 = FAF5 hex And for the 16.781818182 ms time I need to start the timer at: 65535 - 15467 = 50068 = C394 hex So I think the flow should be like this: 1. Reset everything. 2. Enable interrupts on Timer 0. 3. Set TH0 = 0xC3 and TL0 = 0x94 to initiate a low period. 4. Set a flag to 0. 5. Start the Timer. When the timer overflows and interrupts do the following: 1. Set the Flag to 1. 2. Set TH0 = 0xFA and TL0 = 0xF5 to initiate a high period. 3. Clear the overflow flag. 4. Turn on P1.0. 5. Return. When it overflows again then: 1. Set the Flag to 0. 2. Set TH0 = 0xC3 and TL0 = 0x94 to initiate a low period. 3. Clear the overflow flag. 4. Turn off P1.0. 5. Return. So each time the timer overflows, the interrupt code checks the flag value and decides to initiate a high period or a low period. To my mind this should generate the goal I am trying to achieve, but I am having no luck. Is my logic flawed? Am I making some bad assumptions? If anyone is willing to read all of this and check my logic I would be most appreciative. I also have the SDCC code that I am trying to use if it would help. |