|
|
本帖最后由 51黑電子會(huì)員 于 2020-4-18 15:25 編輯
- #include<reg51.h>
- #include<intrins.h>
- #define uchar unsigned char//宏定義,用uchar表示unsigned char,叫無(wú)符號(hào)字符型數(shù)據(jù)類型,取值范圍為:0到255。
- #define uint unsigned int//宏定義,用uint表示unsigned int,叫無(wú)符號(hào)整數(shù)型數(shù)據(jù)類型,取值范圍為:0到65535。
- sbit k1=P1^0;
- sbit k2=P1^5;
- sbit led=P3^4;
- uchar count,pwm,flag;
- void delay(uint z)//延時(shí)程序
- {
- uint x,y;
- for(x=z;x>0;x--)
- for(y=110;y>0;y--);
- }
- void keyscan()//按鍵掃描函數(shù)
- {
- if(k1==0)
- {
- delay(5);
- if(k1==0)
- {
- pwm++;
- if(pwm>=20)
- pwm=0;
- }
- while(!k1);
- }
- if(k2==0)
- {
- delay(5);
- if(k2==0)
- {
- if(pwm>0)
- pwm--;
- if(pwm<=0)
- pwm=0;
- }
- while(!k2);
- }
- }
- void TimerInit()//定時(shí)器0初始化函數(shù)
- {
- TMOD=0x01;//設(shè)定定時(shí)器0,工作模式為模式1。
- TH0=(65536-50000)/256;//TH0裝初值
- TL0=(65536-50000)%256;//TL0裝初值
- // TH1=0xfc;//TH1裝初值
- // TL1=0x66;//TL1裝初值
- EA=1;//開(kāi)啟定時(shí)器總中斷
- ET0=1;//開(kāi)啟定時(shí)器0中斷開(kāi)關(guān)
- TR0=1;//啟動(dòng)定時(shí)器0
- // ET1=1;//開(kāi)啟定時(shí)器1中斷開(kāi)關(guān)
- // TR1=1;//啟動(dòng)定時(shí)器1
- }
- void timer0() interrupt 1//定時(shí)器0中斷函數(shù)
- {
- TH0=(65536-50000)/256;//中斷定時(shí)50毫秒,表示高低電平占用周期50毫秒,也表示高低電平頻率(計(jì)算工式:F=1/T,其中F單位為赫茲,即Hz,而T單位為秒,即s。)為1/0.05s(由50毫秒除以1000求得0.05秒)=20Hz。
- TL0=(65536-50000)%256;//
- count++;
- if(count>=20)//中斷次數(shù)變量達(dá)到20次,表示1秒(即中斷次數(shù)變量20次X中斷定時(shí)50毫秒)時(shí)間到 ,也表示高低電平占用周期1秒,另外表示高低電平頻率(計(jì)算工式:F=1/T,其中F單位為赫茲,即Hz,而T單位為秒,即s。)為1/1s=1Hz。
- {
- count=0;
- }
- if(count<pwm)
- {
- led=0;//led為低電平
- }
- else
- {
- led=1;//led為高電平
- }
- }
- void main()//主函數(shù)
- {
- TimerInit();
- while(1)
- {
- keyscan();//按鍵掃描函數(shù)
- }
- }
復(fù)制代碼
|
-
評(píng)分
-
查看全部評(píng)分
|