一、任务要求
在CT107D单片机上,
1.系统上电初始化后,关闭蜂鸣器和继电器等无关设备,并向上位机发送字符串:“Welcome to Born_toward system!”,回车换行;
2.上位机通过串口发送单字节命令可以控制下位机的8个LED灯开关;
3.上位机通过串口发送单字节命令可以读取下位机运行信息。
二、实现方法
对于串口通信,在之前已经讲过了,在此不作特别说明。控制灯光可以用单字节命令来控制,则需要建立一个能够识别command并且让LED灯做出相应反应的函数——Working(),看代码块可以更加容易理解。
三、参考代码
#include "reg52.h"
sfr AUXR = 0x8e;
void Select_HC573(unsigned char channel)
{
switch(channel)
{
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;
case 0:
P2 = (P2 & 0x1f) | 0x00;
break;
}
}
void Initial_System()
{
Select_HC573(5);
P0 = 0x00;
Select_HC573(4);
P0 = 0xff;
}
void Initial_UART()
{
TMOD = 0x20;
TH1 = 0xfd;
TL1 = 0xfd;
TR1 = 1;
SCON = 0x50;
AUXR = 0x00;
ES = 1;
EA = 1;
}
unsigned char command = 0x00;
void Service_UART() interrupt 4
{
if(RI == 1)
{
command = SBUF;
RI = 0;
}
}
void Send_Byte(unsigned char dat)
{
SBUF = dat;
while(TI == 0);
TI = 0;
}
void Send_String(unsigned char *str)
{
while(*str != '\0')
{
Send_Byte(*str++);
}
}
void Working()
{
if(command != 0x00)
{
switch(command & 0xf0)
{
case 0xa0:
P0 = (P0 | 0x0f) & (~command | 0xf0); //保留P0高四位,改变低四位,command保留低四位。
command = 0x00;
break;
case 0xb0:
P0 = (P0 | 0x0f) & ((~command << 4)| 0x0f); //同上,只不过是左移四位,即保留P0高四位,改变低四位,command保留高四位。
command = 0x00;
break;
case 0xc0:
Send_String("The System is running!\r\n");
command = 0x00;
break;
}
}
}
void main()
{
Initial_System();
Initial_UART();
Send_String("Welcome to China!\r\n");
while(1)
{
Working();
}
}
学习来源于:https://www.bilibili.com/video/BV1Bt41187hw?p=3