蓝桥杯,小蜜蜂,单元训练13:串行接口的进阶应用

/*
 * @Description:
 * @Author: fdzhang
 * @Email: zfdc@qq.com
 * @Date: 2024-08-17 15:41:34
 * @LastEditTime: 2024-08-17 19:48:35
 * @LastEditors: fdzhang
 */
#include "stc15f2k60s2.h"
#define Led(x)                 \
    {                          \
        P0 = x;                \
        P2 = P2 & 0x1F | 0x80; \
        P2 &= 0x1f;            \
    }
// 定义控制蜂鸣器
#define Buzz(x)                \
    {                          \
        P0 = x;                \
        P2 = P2 & 0x1F | 0xA0; \
        P2 &= 0x1F;            \
    }
// 定义控制继电器
#define Relay(x)               \
    {                          \
        P0 = x;                \
        P2 = P2 & 0x1F | 0xA0; \
        P2 &= 0x1F;            \
    }
typedef unsigned char uint8_t;
uint8_t ledinfo = 0xff; // LED信息,初始化全灭
uint8_t recv_data;
void UartInit(void) // 9600bps@12.000MHz
{
    PCON &= 0x7F; // 波特率不倍速
    SCON = 0x50;  // 8位数据,可变波特率
    AUXR |= 0x40; // 定时器时钟1T模式
    AUXR &= 0xFE; // 串口1选择定时器1为波特率发生器
    TMOD &= 0x0F; // 设置定时器模式
    TMOD |= 0x20; // 设置定时器模式
    TL1 = 0xD9;   // 设置定时初始值
    TH1 = 0xD9;   // 设置定时重载值
    ET1 = 0;      // 禁止定时器中断
    TR1 = 1;      // 定时器1开始计时
    ES = 1; // 要手动写
    EA = 1; // 要手动写
}
void uartSend(uint8_t uartData) // 发送数据
{
    SBUF = uartData;
    while (TI == 0)
        ;
    TI = 0;
}
void uartSendString(uint8_t *str) // 发送字符串
{
    while (*str != '\0')
    {
        uartSend(*str++);
    }
}
uint8_t uartRecv() // 接收数据
{
    uint8_t recv_data;
    while (RI == 0)
        ;
    RI = 0;
    recv_data = SBUF;
    return recv_data;
}
void initSys() // 初始化系统
{
    Led(0xff);   // 关闭LED
    Buzz(0xff);  // 关闭蜂鸣
    Relay(0x00); // 关闭中继
}
void welcome() // 上电启动输出欢迎
{
    uint8_t *InitStr = "Welcome to XMF system!\r\n"; //\r回车,\n换行
    uartSendString(InitStr);
}
void runningMessage() // 按c0输运行信息
{
    uint8_t *MessageInfo = "The System is Running....\r\n";
    uartSendString(MessageInfo);
}
void decideLed()
{
    if ((recv_data & 0xF0) == 0xA0) // 0xA?
    {
        ledinfo = ~(recv_data & 0x0f);
    }
    else if ((recv_data & 0xF0) == 0xB0) // 0xB?
    {
        recv_data = recv_data << 4; // 0x?0
        ledinfo = ~recv_data;
    }
    Led(ledinfo);
    if (recv_data == 0xc0)
    {
        runningMessage();
        recv_data = 0x00; // 设定接收值为非C0情况,使得只输出一次running message。
    }
}
void main()
{
    UartInit();
    initSys();
    welcome();
    while (1)
    {
        decideLed();
    }
}
void uart_isr(void) interrupt 4
{
    if (RI == 1)
    {
        RI = 0;
        recv_data = SBUF;
    }
}



















