|
單片機(jī)仿真實(shí)習(xí)任務(wù):
05 定時(shí)器/計(jì)數(shù)器類單片機(jī)系統(tǒng)
05.png (64.26 KB, 下載次數(shù): 38)
下載附件
2019-12-16 10:03 上傳
- //10秒測(cè)按鍵1次數(shù),按鍵2重置
- #include <reg51.h>
- sbit P2_0 = P2^0;//數(shù)碼管選定位
- sbit P2_1 = P2^1;//數(shù)碼管選定位
- sbit P2_2 = P2^2;//數(shù)碼管選定位
- sbit P2_3 = P2^3;//數(shù)碼管選定位
- sbit k1=P1^0;//計(jì)數(shù)
- sbit k2=P1^1;//開(kāi)始
- //共陽(yáng)數(shù)碼管
- unsigned char code table[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
- unsigned int begin = 0;
- unsigned int GE,SHI,BAI,QIAN; //定義變量
- unsigned int time=10;//秒數(shù)
- unsigned char Button_count=0;//按鍵次數(shù)
- unsigned int temp;
- void display();//數(shù)碼管顯示函數(shù),依次點(diǎn)亮數(shù)碼管
- void Daojishi();//倒計(jì)時(shí)
- void delay0(unsigned int z);//延遲函數(shù)
- void scankey();//按鍵掃描
- void timeint0();
- void main()
- {
- while(1)
- {
- if(k2==0)//檢測(cè)鍵是否被按下
- {
- begin=1;
- time=10;
- Button_count=0;
- GE=0;
- SHI=0;
- BAI=0;
- QIAN=0; //定義變量
- timeint0();
- }
- if(begin==1)
- {
- Daojishi();
- scankey();
- }
- display();
- }
- return ;
- }
- /*********************************************************
- //
- //10s倒計(jì)時(shí)
- //
- *********************************************************/
- void Daojishi()//倒計(jì)時(shí)
- {
- if (time!=0)
- {
- if(temp!=0)
- {
- temp=0;
- time--;//變量自增
- QIAN=time/10;//顯示十位
- BAI=time%10;//顯示個(gè)位
- }
- }
- }
- /*********************************************************
- //
- //鍵盤檢測(cè)子函數(shù)
- //
- *********************************************************/
- void scankey()
- {
- if (time!=0)
- {
- if(k1==0) //檢測(cè)鍵是否被按下
- {
- delay0(5); //延時(shí)消除抖動(dòng)
- if(k1==0) //重新讀取k1的值
- {
- Button_count++; //計(jì)數(shù)
- SHI=Button_count/10;
- GE=Button_count%10;
- while(!k1); //等待按鍵釋放
- }
- }
- }
- }
- //數(shù)碼管顯示函數(shù),依次點(diǎn)亮數(shù)碼管
- void display()
- {
- P2_0 = 0;
- P0 = table[QIAN];
- delay0(5);
- P2_0 = 1;
- P2_1 = 0;
- P0 = table[BAI];
- delay0(5);
- P2_1 = 1;
- P2_2 = 0;
- P0 = table[SHI];
- delay0(5);
- P2_2 = 1;
- P2_3 = 0;
- P0 = table[GE];
- delay0(5);
- P2_3 = 1;
- }
- /*********************************************************
- 延時(shí)子函數(shù)0.24ms
- *********************************************************/
- void delay0(unsigned int z)
- {
- unsigned int i,j;
- for(i=0;i<z;i++)
- for(j=0;j<110;j++);
- }
- /*********************************************************
- //
- //定時(shí)器0初始化
- //
- *********************************************************/
- void timeint0()
- {
- TMOD=0X01;//工作方式
- TH0=0XFC;//定時(shí)1ms
- TL0=0X18;//定時(shí)1ms
- TR0=1;//控制
- ET0=1;//定時(shí)器0中斷請(qǐng)求
- EA=1;//總中斷
- }
- /*********************************************************
- //
- //定時(shí)器0中斷1ms
- //
- *********************************************************/
- void time0int () interrupt 1//注意中斷號(hào)
- {
- static int i=0;//注意靜態(tài)變量的使用!
- TH0=0XFC;//定時(shí)器復(fù)位
- TL0=0X18;//定時(shí)器復(fù)位
- i++;
- if(i==1000)//1000個(gè)1ms,構(gòu)成1s
- {
- i=0;
- temp=1;
- }
- }
復(fù)制代碼
|
|