#include "hal_uart.h"
static uint uart_rx_cnt = 0;
static uint uart_tx_cnt = 0;
uint uart_rx_len;
uint uart_tx_len;
byte * uart_rx_ptr;
byte * uart_tx_ptr;
byte uart_rx_completed;
byte uart_tx_completed;
CALLBACKFUNC pHandleReceive;
static void uart0_isr(void) interrupt
INTERRUPT_UART0
{
if(RI0 == 1)
{
RI0 = 0;
if (uart_rx_cnt < uart_rx_len)
{
*(uart_rx_ptr + uart_rx_cnt) = SBUF0;
uart_rx_cnt++;
if(uart_rx_cnt ==
uart_rx_len)
uart_rx_completed = 1;
}
if(pHandleReceive != 0)
{
(*pHandleReceive)(SBUF0);
}
}
if(TI0 == 1)
{
TI0 = 0;
uart_tx_cnt++;
if(uart_tx_cnt >= uart_tx_len)
uart_tx_completed = 1;
else
{
SBUF0 = *(uart_tx_ptr + uart_tx_cnt);
}
}
}
void hal_uart_init(BAUD_RATE baud)
{
XBR0 |= 0x01;
//UART0 Tx-P0.4,Rx-P0.5
P0MDOUT |= 0x10;
//Tx as Push-Pull
ES0 = 0; // Disable UART0 interrupt while initializing
uart_rx_len = 0;
uart_tx_len = 0;
uart_rx_completed = 0;
uart_tx_completed = 0;
pHandleReceive = 0;
switch(baud)
{
case BAUD_9600:
TMOD = 0x20;
// 8位重装载模式
CKCON = 0x00;
// T1分频系数
TH1 = 0x30;
// 定时器重装载值
break;
case BAUD_14400:
TMOD = 0x20;
CKCON = 0x00;
TH1 = 0x75;
break;
case BAUD_19200:
TMOD = 0x20;
CKCON = 0x00;
TH1 = 0x98;
break;
case BAUD_57600:
TMOD = 0x20;
CKCON = 0x01;
TH1 = 0x98;
break;
case BAUD_115200:
TMOD = 0x20;
CKCON = 0x08;
TH1 = 0x30;
break;
default:
TMOD = 0x20;
CKCON = 0x00;
TH1 = 0x30;
break;
}
SCON0 = 0x10;
//8-bit uart;RI0 will only be activated if stop bit is logic level 1.
TR1 = 1;
ET1 = 0;
ES0 = 1; // Enable UART0 interrupt
}
void hal_uart_tx(byte * pTxBuff,uint length)
{
uart_tx_ptr = pTxBuff;
uart_tx_len = length;
uart_tx_cnt = 0;
uart_tx_completed = 0;
SBUF0 = *uart_tx_ptr;
while(uart_tx_completed == 0);
}
void hal_uart_rx(byte * pRxBuff,uint length)
{
uart_rx_ptr = pRxBuff;
uart_rx_len = length;
uart_rx_cnt = 0;
uart_rx_completed = 0;
while(uart_rx_completed == 0);
}
void hal_uart_tx_overlapped(byte * pTxBuff,uint length)
{
uart_tx_ptr = pTxBuff;
uart_tx_len = length;
uart_tx_cnt = 0;
uart_tx_completed = 0;
SBUF0 = *uart_tx_ptr;
}
void hal_uart_rx_overlapped(byte * pRxBuff,uint length)
{
uart_rx_ptr = pRxBuff;
uart_rx_len = length;
uart_rx_cnt = 0;
uart_rx_completed = 0;
}
void hal_uart_tx_byte(byte txData)
{
hal_uart_tx(&txData,1);
}
byte hal_uart_rx_byte()
{
byte temp;
hal_uart_rx(&temp,1);
return temp;
}
byte hal_uart_rx_count()
{
return uart_rx_cnt;
}
bool hal_uart_tx_complete()
{
return uart_tx_completed;
}
bool hal_uart_rx_complete()
{
return uart_rx_completed;
}
void hal_uart_registe_RecieveEvent(CALLBACKFUNC receiveProc)
{
pHandleReceive = receiveProc;
} |