51单片机用串口控制流水灯
时间: 2023-10-16 15:06:17 浏览: 71
以下是51单片机用串口控制流水灯的代码:
```c
#include <reg51.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit SDA = P1^0; //IIC总线数据线
sbit SCL = P1^1; //IIC总线时钟线
uchar led = 0xFE; //LED灯初始状态,刚开始为11111110
void delay(uint t)
{
while(t--);
}
void start()
{
SDA = 1;
SCL = 1;
_nop_();
_nop_();
_nop_();
SDA = 0;
_nop_();
_nop_();
_nop_();
SCL = 0;
}
void stop()
{
SDA = 0;
_nop_();
_nop_();
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
SDA = 1;
}
void ack()
{
SDA = 0;
_nop_();
_nop_();
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
SCL = 0;
_nop_();
_nop_();
_nop_();
SDA = 1;
}
void write_byte(uchar dat)
{
uchar i;
for(i = 0; i < 8; i++)
{
SDA = dat & 0x80;
dat <<= 1;
_nop_();
_nop_();
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
SCL = 0;
}
ack();
}
void set_led(uchar dat)
{
start();
write_byte(0xA0); //写入设备地址,此处为0xA0
write_byte(0x00); //写入LED灯的寄存器地址,此处为0x00
write_byte(dat); //写入LED灯的状态
stop();
}
void main()
{
TMOD = 0x20; //定时器1工作在模式2
TH1 = 0xFD; //波特率9600
TL1 = 0xFD;
TR1 = 1; //启动定时器1
SCON = 0x50; //串口工作在模式1
ES = 1; //使能串口中断
EA = 1; //开启总中断
while(1)
{
set_led(led); //设置LED灯状态
delay(50000); //延时
led = _crol_(led, 1); //左移一位
}
}
void uart() interrupt 4
{
uchar dat;
if(RI) //接收中断
{
RI = 0;
dat = SBUF;
switch(dat)
{
case '1': led = 0xFE; break; //设置LED灯为初始状态
case '2': led = 0xFF; break; //设置LED灯全亮
default: break;
}
}
}
```
上述代码中,我们使用了串口通信来控制LED灯的状态。通过`set_led()`函数来设置LED灯的状态,其中通过I2C总线来写入数据到LED灯的寄存器中。在`main()`函数中,我们不断地循环移位来实现LED灯的流水效果。在串口中断函数`uart()`中,我们接收上位机发送过来的数据,并根据数据的内容设置LED灯的状态。