模块:串口通信 LED
此图片来源于 21ic www.xmf393.com / 广东职院 欧浩源
#include <STC15F2K60S2.H>
#define uchar unsigned char
#define uint unsigned int
uchar dat;
void HC138init (uchar n)
{
switch (n)
{
case 4:
P2 = (P2&0x1f)|0x80;
break;
case 5:
P2 = (P2&0x1f)|0xa0;
break;
case 6:
P2 = (P2&0x1f)|0xc0;
break;
case 7:
P2 = (P2&0x1f)|0xe0;
break;
}
}
void cl_init () // 关闭蜂鸣器 继电器 流水灯
{
HC138init (5);
P0 = 0x00;
HC138init (4);
P0 = 0xff;
}
//=====================================
void init ()
{
TMOD=0x20; // 八位自动重载
TH1=0xfd;
TL1=0xfd; // 9600 波特率
AUXR=0x00; // 辅助寄存器
TR1=1;
SCON = 0x50; // SM1 = 1 SM0 = 0 REN = 1
ES=1;
EA=1;
}
void initrt () interrupt 4
{
if(RI == 1)
{
RI = 0;
dat = SBUF; // 把接收的数据给dat
}
}
void sendbit (uchar dat) // 发送一个字节
{
SBUF = dat;
while(TI == 0);
TI = 0;
}
void sendstring (uchar *str) // 发送字符串
{
while (*str != '\0')
{
sendbit (*str);
str++;
}
}
void working ()
{
if(dat != 0x00)
{
switch (dat & 0xf0) // 例如 你要让 第一个LED 亮 低四位 就要赋值 1110
{ case 0xa0: //
P0 = (P0 |0x0f)&(dat|0xf0); // 例如 你要让 第五个LED 亮 高四位 就要赋值 1110
dat = 0x00; //
break;
case 0xb0 :
P0 = (P0 |0xf0)&((dat<<4)|0xf0);
dat = 0x00;
break;
case 0xc0:
sendstring ("中国 加油!\r\n") ;
dat = 0x00;
break;
}
}
}
//=====================================
void main ()
{
cl_init ();
init ();
sendstring ("加油 武汉!\r\n") ;
while(1)
{
working ();
}
}