STC8H用串口2实现的收发通讯协议

软件开发大郭
0 评论
/
21 阅读
/
1952 字
05 2023-02


#include <STC8H.H> //8H头文件
#include <UART2.H>
#include <UART1.H>
bit busy2;
char Uart2_RecvBuf[30] = {0}; //串口数据缓存
char uart2Index = 0;          //绶存指针
char uart2RXEnd = 0;
char Uart2RXLength = 0;


/*-------------------------------------------屏幕通信初始化----------------------------------------------*/
void Uart2Init(void) //9600bps@11.0592MHz
{
    S2CON = 0x50;        //8位数据,可变波特率
    AUXR |= 0x04;        //定时器2时钟为Fosc,即1T
    T2L = 0xE8;        //设定定时初值
    T2H = 0xFF;        //设定定时初值
    AUXR |= 0x10;        //启动定时器2

    S2CON |= 0x10; //使能接收 S2REN=1
    IE2 |= 0x01;   //使能串口2中断
    EA = 1;
}


/*-------------------------------------------接收信息----------------------------------------------*/
void Uart2() interrupt 8{
    if ((S2CON & S2RI) && uart2RXEnd == 0) {
        S2CON &= ~S2RI; //清除S2RI位
        P47 = ~P47;
        Uart2_RecvBuf[uart2Index] =
                S2BUF;
        if (Uart2_RecvBuf[0] == 0xFE) //Uart2_RecvBuf协议第一个字节是0x5a
        {
            uart2Index++;
        }
        if (uart2Index > 5) {
            uart2Index = 0;
            uart2RXEnd = 1;
        }
    }
    if (S2CON & S2TI) {
        S2CON &= ~S2TI; //清除S2TI位
        busy2 = 0;       //清忙标志
    }
}

char aaa[5] = {0xfe, 0xbb, 0x01, 0x00, 0x16};

void UartRx2(void) {
    if (uart2RXEnd) {
        uart2RXEnd = 0;
        UART1_SendStr(Uart2_RecvBuf);
        SendString2(aaa, 5);
    }

}


/*-------------------------------------------发送----------------------------------------------*/
void SendData2(char dat) {
    while (busy2); //等待前面的数据发送完成
    //ACC = dat;                  //获取校验位P (PSW.0)
    busy2 = 1;
    S2BUF = dat; //写数据到UART2数据寄存器
}


void SendString2(char *s, char length) //发送字符串
{
    while (length != 0) //检测字符串结束标志
    {
        SendData2(*s++); //发送当前字符
        length--;
    }
}
    暂无数据