|
发表于 2010-9-28 07:29:40
|
显示全部楼层
the beauty of the code shown above is that all the work is done in the interrupt so no reliance on the main() loop to generate the signal. if you don't change PWM_DC, the mcu will just continue to generate the output.
the pwm period in the above code is presumed to be 256 x PWM_STEPPING (because pwm_dc is an unsigned char type). I have been asked to allow a user-define pwm period, and to show an example of variable pwm output. so here it is the 2nd revision to the code above.
============code========
#include <regx51.h>
#include "gpio.h"
//hardware configuration
#define PWM_PORT P2
#define PWM_DDR P2
#define PWM_OUT (1<<0) //pwm output on p2.0
//end hardware configuration
#define PWM_ON(bits) IO_CLR(PWM_PORT, bits) //turn on bits
#define PWM_OFF(bits) IO_SET(PWM_PORT, bits) //turn off bits
#define PWM_STEPPING 150 //pwm stepping, in us - should leave enough time to fully execute the isr, 0x00 - 0xff
#define PWM_PERIOD 100 //pwm period, 0x00 - 0xff
unsigned char PWM_DC = 4; //desired pwm duty cycle, from 0x00 - PWM_PERIOD
///////////////////???0????PWM////////////////////
void timer0(void) interrupt 1 using 2 {
static unsigned char pwm_index=0; //t?????????????????
pwm_index++; //?15????1
if (pwm_index==PWM_PERIOD) { //1.5???????
pwm_index=0; //reset pwm_index
PWM_ON(PWM_OUT); //turn on pwm_out
}
if (pwm_index==PWM_DC) //???????????????
PWM_OFF(PWM_OUT); //turn off pwm
}
void mcu_init(void) {
PWM_ON(PWM_OUT); //drive pwm_out off
IO_OUT(PWM_DDR, PWM_OUT); //pwm_out as output
}
void tmr0_init(void) {
TMOD = (TMOD & 0xf0) | 0x02; //???0,????2,8?????
TH0=-PWM_STEPPING; //??????241????0,?15??????(11.0592MHz)
TL0=TH0; //?????
TR0=1; //?????
ET0=1; //?????0??
EA=1; //?????
}
//////////////////?????//////////////////////
void main(void) {
volatile unsigned short i;
mcu_init(); //reset the mcu
tmr0_init(); //set up tmr0
while(1) {
for (i=0; i<0x02ff; i++)
continue; //waste some time
PWM_DC++; //update pwm duty cycle
if (PWM_DC==PWM_PERIOD) PWM_DC=0;
//(PWM_DC == PWM_PERIOD)? PWM_DC=0: PWM_DC++;
}
}
============end code============ |
|