用c语言编写一个51单片机串口助手控制蜂鸣器、LED小灯和LCD
时间: 2024-03-07 12:48:56 浏览: 62
好的,下面是一个简单的示例程序,使用C语言编写,可以通过串口助手控制蜂鸣器、LED小灯和LCD。
```c
#include <reg52.h>
#include <intrins.h>
#include <stdio.h>
#define LED P1_0
#define BUZZER P1_1
#define LCD_RS P2_0
#define LCD_EN P2_1
#define LCD_D4 P2_2
#define LCD_D5 P2_3
#define LCD_D6 P2_4
#define LCD_D7 P2_5
void delay_ms(unsigned int ms)
{
unsigned int i;
while(ms--)
{
for(i=0;i<120;i++);
}
}
void write_com(unsigned char com)
{
LCD_RS = 0;
P0 = com;
LCD_EN = 1;
_nop_();
_nop_();
_nop_();
LCD_EN = 0;
delay_ms(1);
}
void write_data(unsigned char dat)
{
LCD_RS = 1;
P0 = dat;
LCD_EN = 1;
_nop_();
_nop_();
_nop_();
LCD_EN = 0;
delay_ms(1);
}
void init_lcd()
{
write_com(0x02);
write_com(0x28);
write_com(0x0c);
write_com(0x06);
write_com(0x01);
}
void display_lcd(unsigned char line, char *str)
{
unsigned char i;
if(line == 1)
{
write_com(0x80);
}
else if(line == 2)
{
write_com(0xc0);
}
for(i=0;str[i];i++)
{
write_data(str[i]);
}
}
void init_uart()
{
TMOD &= 0x0f;
TMOD |= 0x20;
TH1 = 0xfd;
TL1 = 0xfd;
PCON &= 0x7f;
SCON = 0x50;
TR1 = 1;
}
void putchar(char c)
{
SBUF = c;
while(!TI);
TI = 0;
}
void main()
{
unsigned char cmd;
char str[17];
init_lcd();
init_uart();
display_lcd(1, "Hello, World!");
while(1)
{
if(RI)
{
RI = 0;
cmd = SBUF;
switch(cmd)
{
case 'L':
LED = 1;
display_lcd(2, "LED ON ");
putchar('L');
break;
case 'l':
LED = 0;
display_lcd(2, "LED OFF ");
putchar('l');
break;
case 'B':
BUZZER = 1;
display_lcd(2, "Buzzer ON ");
putchar('B');
break;
case 'b':
BUZZER = 0;
display_lcd(2, "Buzzer OFF ");
putchar('b');
break;
case 'C':
write_com(0x01);
display_lcd(2, "LCD Clear ");
putchar('C');
break;
case 'T':
sprintf(str, "Time:%d:%d:%d", TH0, TL0, TF0);
display_lcd(2, str);
putchar('T');
break;
default:
display_lcd(2, "Unknown Command ");
break;
}
}
}
}
```
该程序使用了51单片机的定时器和串口功能,通过串口接收指令来控制LED灯和蜂鸣器的开关状态,以及LCD的显示内容。您可以在串口助手中发送'L'来打开LED灯,发送'l'来关闭LED灯,发送'B'来打开蜂鸣器,发送'b'来关闭蜂鸣器,发送'C'来清空LCD屏幕,发送'T'来在LCD屏幕上显示当前时间。
阅读全文