標題: 單片機按鍵實現一個LED1燈的翻轉等功能的程序問題 [打印本頁]
作者: 99899245 時間: 2019-10-27 23:41
標題: 單片機按鍵實現一個LED1燈的翻轉等功能的程序問題
1.按鍵k2實現一個LED1燈的翻轉
2.按鍵k3按下計時,松開按鍵,單片機串口發送按下的時間(單位ms)
3.LED2閃爍,周期為2s,其中亮1.5秒,滅0.5秒,要求時間準確。
第三個實現不了
# include<reg52.h>
# define uint unsigned int
# define uchar unsigned char
sbit key2=P3^4;
sbit key3=P3^6;
sbit LED1=P1^0;
sbit LED2=P1^1;
uint count1=0;
uint count2=0;
void delay(uint i)
{
while(--i);
}
void init()
{
TMOD=0x21;
TH0=0xfc;
TL0=0x17;
TH1=0xfd;
TL1=0xfd;
TR1=1;
TR0=1;
SM0=0;
SM1=1;
EA=1;
ET0=1;
ET1=1;
ES=1;
}
void main()
{
init();
while(1)
{
if(key2==0)
{
delay(10);
LED1=~LED1;
while(!key2);
}
if(key3==0)
{
while(!key3)
{
TH0=0xfc;
TL0=0x17;
count1++;
}
SBUF=count1;
if(TI==1)
{
TI=0;
count1=0;
}
}
}
}
void timer() interrupt 1
{
TH0=0xfc;
TL0=0x17;
count2++;
TF0=0;
if(count2==500)
LED2=~LED2;
if(count2==2000)
{
LED2=~LED2;
count2=0;
}
}
作者: xianfajushi 時間: 2019-10-28 09:04
周期為2秒的話邏輯應該這樣修改 if(count2==2000)count2=0; if(count2>=1500) LED2=~LED2;
作者: wulin 時間: 2019-10-28 10:06
給你改寫,你試試。串口只能一次發送一個字節,uint count1=0; 16位數據需要分兩次發送。
- #include<reg52.h>
- #define uint unsigned int
- #define uchar unsigned char
- sbit key2=P3^4;
- sbit key3=P3^6;
- sbit LED1=P1^0;
- sbit LED2=P1^1;
- uint count1=0;
- uint count2=0;
- uchar dat_A,dat_B;
- bit flag=0;
- void delay(uint i)
- {
- while(--i);
- }
- void init()
- {
- TMOD=0x21;
- TH0=0xfc; //1毫秒@11.0592MHz
- TL0=0x66;
- TH1=0xfd;
- TL1=0xfd;
- SM0=0;
- SM1=1;
- TR0=1;
- TR1=1;
- EA=1;
- ET0=1;
- }
- void SendData(uchar dat)
- {
- SBUF = dat; //發送當前數據
- while(!TI); //等待發送完畢
- TI = 0; //清除發送標志
- }
- void main()
- {
- init();
- while(1)
- {
- if(key2==0)
- {
- delay(1000);
- if(key2==0)
- {
- LED1=~LED1;
- while(!key2);
- }
- }
- if(key3==0)
- {
- delay(1000);
- if(key3==0 && flag==0)
- flag=1;
- }
- else
- {
- if(flag==1)
- {
- EA=0;//關中斷
- flag=0;
- dat_A=count1; //分解低8位
- dat_B=count1>>8;//分解高8位
- count1=0;
- SendData(dat_A);//發送低8位
- SendData(dat_B);//發送高8位
- EA=1;//開中斷
- }
- }
- }
- }
- void timer() interrupt 1
- {
- TH0=0xfc;
- TL0=0x66;
- count2++;
- if(count2<1500)
- LED2=0;
- else LED2=1;
- if(count2>=2000)
- count2=0;
- if(flag==1)
- count1++;
- }
復制代碼
作者: 99899245 時間: 2019-10-28 22:24
感謝感謝大佬為什么原來的第三問實現不了
作者: wulin 時間: 2019-10-29 16:38
單獨使用T0中斷的閃爍燈程序可以完成,但這樣寫代碼有漏洞。因為你開了沒有必要的ET1=1;ES=1; 雖然沒有寫T1中斷程序和串口中斷程序,但T1約2us周期的高速中斷請求會與T0中斷沖突,有可能錯過 if(count2==2000)而跑飛。
| 歡迎光臨 (http://www.raoushi.com/bbs/) |
Powered by Discuz! X3.1 |