#include "public.h" #include "lcd1602.h" #include "reg52.h" #include "intrins.h" #define LED_PORT P2 sbit LED1 = P1^0; sbit KEY1=P3^1; sbit KEY2=P3^0; sbit KEY3=P3^2; sbit KEY4=P3^3; #define KEY1_PRESS 1 #define KEY2_PRESS 2 #define KEY3_PRESS 3 #define KEY4_PRESS 4 #define KEY_UNPRESS 0 u8 key_scan(unsigned char mode) { static unsigned char key=1; if(mode)key=1; if(key==1&&(KEY1==0||KEY2==0||KEY3==0||KEY4==0)) { delay_10us(1000); key=0; if(KEY1==0) return KEY1_PRESS; else if(KEY2==0) return KEY2_PRESS; else if(KEY3==0) return KEY3_PRESS; else if(KEY4==0) return KEY4_PRESS; } else if(KEY1==1&&KEY2==1&&KEY3==1&&KEY4==1) { key=1; } return KEY_UNPRESS; } void main() { unsigned char k=0; unsigned char i=0; lcd1602_init(); lcd1602_show_string(0,0,"Hell0 W0rld!"); LED1 = 0; delay_10us(50000); while(1) { if(key_scan==KEY1_PRESS) LED_PORT=!LED_PORT; for(i=0;i<7;i++) { LED_PORT=_crol_(LED_PORT,1); delay_10us(50000); } for(i=0;i<7;i++) { LED_PORT=_cror_(LED_PORT,1); delay_10us(50000); } } }优化代码使其在独立按键k1按下后led开始从左向右
时间: 2023-09-05 11:10:57 浏览: 166
intrins.h.rar_INTRINS_Keil C51 intrins.h_c51 _cro_intrins.h xiaz
5星 · 资源好评率100%
移动,直到移动到最右端后再从右向左移动,如此往返。同时,LCD1602 显示 "LED is Moving!"。实现代码如下:
``` c
#include "public.h"
#include "lcd1602.h"
#include "reg52.h"
#include "intrins.h"
#define LED_PORT P2
sbit LED1 = P1^0;
sbit KEY1=P3^1;
#define KEY1_PRESS 1
#define KEY_UNPRESS 0
u8 key_scan(unsigned char mode) {
static unsigned char key=1;
if(mode)key=1;
if(key==1&&(KEY1==0))
{
delay_10us(1000);
key=0;
if(KEY1==0)
return KEY1_PRESS;
}
else if(KEY1==1)
{
key=1;
}
return KEY_UNPRESS;
}
void main() {
unsigned char k=0;
unsigned char i=0;
unsigned char direction = 1;
unsigned char position = 0;
lcd1602_init();
lcd1602_show_string(0,0,"Hell0 W0rld!");
LED1 = 0;
delay_10us(50000);
while(1)
{
if(key_scan() == KEY1_PRESS) {
lcd1602_clear();
lcd1602_show_string(0,0,"LED is Moving!");
while(KEY1 == 0);
}
if(direction == 1) {
LED_PORT = _crol_(LED_PORT, 1);
position++;
if(position == 7) {
direction = 0;
}
} else {
LED_PORT = _cror_(LED_PORT, 1);
position--;
if(position == 0) {
direction = 1;
}
}
delay_10us(50000);
}
}
```
主要的改变是加入了一个方向变量`direction`和一个位置变量`position`,根据这两个变量的值来决定LED的移动方向和位置。在按下K1的时候,清空LCD1602并显示"LED is Moving!",直到K1松开。
阅读全文