PWM呼吸燈
阿新 • • 發佈:2018-12-09
##單個定時器
#include <reg52.h> #include <intrins.h> unsigned char PWM_COUNT; //計數 unsigned int HUXI_COUNT; //佔空比更新時間 unsigned char PWM_VLAUE; //佔空比比對值 bit direc_flag; //佔空比更新方向 void Enable_138(unsigned char ch) { P2 = (P2 & 0x1f ) | (ch << 5); _nop_(); _nop_(); P2 &= 0x1f; } void timer0_init() { TMOD=0x02; //模式設定,定時器0,工作於模式2(M1=1,M0=0) TH0=0x47; //定時器溢位值設定,每隔200us發起一次中斷。 TL0=0X47; TR0=1; //定時器0開始計時 ET0=1; //開定時器0中斷 EA=1; //開總中斷 PWM_COUNT =0; } void time0() interrupt 1 { PWM_COUNT++; HUXI_COUNT++; if(PWM_COUNT == PWM_VLAUE) //判斷是否到了點亮LED的時候 { P0 = 0xef; Enable_138(4); } //點亮LED if(PWM_COUNT == 10) //當前週期結束 { P0 = 0xff; Enable_138(4); //熄滅LED PWM_COUNT = 0; //重新計時 } if((HUXI_COUNT == 600) && (direc_flag == 0)) { //佔空比增加10% HUXI_COUNT = 0; PWM_VLAUE++; if(PWM_VLAUE == 9) //佔空比更改方向 direc_flag = 1; } if((HUXI_COUNT == 600) && (direc_flag == 1)) { //佔空比減少10% HUXI_COUNT = 0; PWM_VLAUE--; if(PWM_VLAUE == 1) //佔空比更改方向 direc_flag = 0; } } void main() { P0 = 0x00; Enable_138(5); P0 = 0x00; Enable_138(6); HUXI_COUNT = 0; PWM_COUNT = 0; PWM_VLAUE = 5; direc_flag = 0; P0 = 0xff; Enable_138(4); timer0_init(); //定時器0初始化 while(1); }