标题: 单片机按键实现一个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.51hei.com/bbs/) |
Powered by Discuz! X3.1 |