51单片机 uart_test.c

#include 
#include "utilities.h"

bit frameFlag = 0;
bit txdFlag = 0;
uint8_t rxdCnt = 0;
uint8_t pdata rxdBuf[64];

extern void uartAction(uint8_t * buf, uint8_t len);

void configUart(uint8_t baud) {
    SCON = 0x50;
    TMOD &= 0x0F;
    TMOD |= 0x20;
    TL1 = 256 - 11059200 / 12 / 16 / 2 / baud;
    TH1 = TL1;
    ET1 = 0;
    ES = 1;
    //TR1 = 1;
}

void uartWrite(uint8_t * buf, uint8_t len) {
    while (len--) {
        txdFlag = 0;
        SBUF = *buf++;
        while (!txdFlag);
    }
}

uint8_t uartRead(uint8_t * buf, uint8_t len) {
    uint8_t i;

    if (len > rxdCnt)
        len = rxdCnt;
    for (i = 0; i < len; i++) {
        buf[i] = rxdBuf[i];
    }
    rxdCnt = 0;
    return len;
}

void uartRxMonitor(uint8_t ms) {
    static uint8_t backupCnt = 0;
    static uint8_t idleTmr = 0;

    if (rxdCnt > 0) {
        if (backupCnt != rxdCnt) {
            backupCnt = rxdCnt;
            idleTmr = 0;
        } else {
            if (idleTmr < 30) {
                idleTmr += ms;
                if (idleTmr >= 30)
                    frameFlag = 1;
            }
        }
    } else {
        backupCnt = 0;
    }
}

void uartDriver() {
    uint8_t len;
    uint8_t pdata buf[40];

    if (frameFlag) {
        frameFlag = 0;
        len = uartRead(buf, sizeof (buf));
        uartAction(buf, len);
    }
}

void uartIntSrv() interrupt 4 {
    if (RI) {
        RI = 0;
        if (rxdCnt < sizeof (rxdBuf)) {
            rxdBuf[rxdCnt++] = SBUF;
        }
    }
    if (TI) {
        TI = 0;
        txdFlag = 1;
    }
}
 

 

你可能感兴趣的:(51单片机)