//51單片機(jī)PWM占空比調(diào)整演示程序//(通過(guò)測(cè)試,注意:AT89S51單片機(jī),有的單片機(jī)P3_7需要改為P3^7)/***************************************************************************** * 程序名稱:PWM占空比調(diào)整演示程序 * *程序思路說(shuō)明: * * 只需要4個(gè)按鍵。 * *關(guān)于頻率和占空比的確定,對(duì)于12M晶振,輸出頻率為1KHZ,這樣定時(shí)中斷次數(shù)設(shè)定為 **10,即0.01MS中斷一次,則TH0=FF,TL0=F6;由于設(shè)定中斷時(shí)間為0.01ms,這樣可以設(shè) **定占空比可從1-99%變化。即0.01ms*100=1ms * ******************************************************************************/#include#define uchar unsigned char #define uint unsigned intuchar timer0_tick,ZKB=1;//timer0_tick計(jì)數(shù),ZKB占空比uchar i=0,n=0,temp=0;code seven_seg[10]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};//1,2,3, 4, 5, 6, 7, 8, 9code scan[2]={0xfd,0xfe};uchar counter[2]={0,0};sbit AN1=P3^2;//調(diào)整個(gè)位sbit AN2=P3^3;//調(diào)整十位sbit AN3=P3^4;//啟動(dòng)按鍵sbit AN4=P3^5;//確認(rèn)按鍵void delay(uint z)//軟件延時(shí)函數(shù){uint x,y;for(x=z;x>0;x--)for(y=110;y>0;y--);}static void timer0_isr(void) interrupt 1 using 0 //中斷函數(shù){TR0=0;TL0=0xf6;TH0=0xff;TR0=1;if (ZKB>99) ZKB=1; if (ZKB<1) ZKB=99;counter[0]=ZKB%10;counter[1]=ZKB/10;n++;if(n==100){n=0;i++;if(i==2) i=0;P0=seven_seg[counter[i]];P2=scan[i];}timer0_tick++;if(timer0_tick++==100){timer0_tick=0;}if(AN2==0){ delay(100);if(AN2==0){temp=1;counter[0]++;if(counter[0]==10){counter[0]=0;}}}if(AN1==0){delay(100);if(AN1==0){temp=1;counter[1]++;if(counter[1]==10){counter[1]=0;}}}ZKB=counter[0]+counter[1]*10;if(AN4==0){delay(5);if(AN4==0)temp=0;}if(temp==1)P3_7=0;// P3_7為脈沖輸出引腳else {if (timer0_tick<=ZKB) /*當(dāng)小于占空比值時(shí)輸出低電平,高于時(shí)是高電平,從而實(shí)現(xiàn)占空比的調(diào)整*/ {P3_7=1;} else {P3_7=0;}}} static void timer0_initialize(void)//中斷初始化{EA=0;timer0_tick=0;TR0=0;TMOD=0x01;TL0=0xf6;TH0=0xff;PT0=0;ET0=1;TR0=1;EA=1;}void main(void){STAR: delay(100); if(AN3!=0) goto STAR;//按鍵3啟動(dòng)脈沖timer0_initialize();while(1);}//按按鍵3啟動(dòng)脈沖器,初始設(shè)置占空比為1%,按鍵1調(diào)整十位,//按鍵2調(diào)整個(gè)位,一旦調(diào)整,輸出為0,必須按確認(rèn)鍵確認(rèn),//輸出正確脈沖.可以占空比1-99%任意調(diào)節(jié)。
評(píng)論