UART操作的程序
[b]UART操作的程序[/b]作者:转载
#include "config.h"
/*define UARTs data structure*/
typedef struct UartMode
{
uint8 datab; // byte length
uint8 stopb; // stop bit,1/2
uint8 parity; // parity bit setting
}UARTMODE;
uint8 rcv_buf[8];
uint8 rcv_byte[8];
volatile uint8 add_data_num;
volatile uint8 rcv_new; //flag for rcving new data
volatile uint8 add_data;
void __irq IRQ_UART0(void)
{
uint8 i;
if ((U0IIR & 0x0F) == 0x04)
{
rcv_new = 1;
for (i = 0; i<8; i )
{
rcv_buf[i] = U0RBR;
}
}
// read all the data in FIFO once. Then there is no too much interruptions
if ((U0IIR & 0xF) == 0x0C)
{
add_data_num = 0;
while (U0LSR & 0x00000001)// Read UARTs LSR register first,
{ // and determine whether FIFO is empty
add_data = 1; // or not.
rcv_byte[add_data_num] = U0RBR;
add_data_num ;
}
}
VICVectAddr = 0x00;
}
void UART0_SendByte(uint8 dat)
{
U0THR = dat;
}
void UART0_SendBuf(void)
{
uint8 i;
for (i=0; i<8; i )
UART0_SendByte(rcv_buf[i]);
while ((U0LSR & 0x20) == 0) ;
}
void UART0_SendAddByte(uint8 j)
{
uint8 i;
for (i = 0; i
while ((U0LSR & 0x20) == 0) ;
}
int UART0_Init(uint32 baud, UARTMODE set)
{
uint32 bak;
if ((baud == 0)||(baud > 115200))
return (0);
if ((set.datab < 5)||(set.datab > 8))
return (0);
if ((set.stopb == 0)||(set.stopb > 2))
return (0);
if (set.parity > 4)
return (0);
/*set UARTs baud rate*/
U0LCR = 0x80; //DLAB = 1
bak = (Fpclk >> 4)/baud;
U0DLM = bak >> 8;
U0DLL = bak &0xFF;
/*set UARTs mode*/
bak = set.datab - 5;
if (set.stopb == 2)
bak |= 0x04;
if (set.parity != 0)
{
set.parity = set.parity - 1;
bak |= 0x08;
}
bak |= set.parity << 4;
U0LCR = bak;
return (1);
}
int main (void)
{// add user source code
UARTMODE set;
set.datab = 8;
set.stopb = 1;
set.parity = 0;
rcv_new = 0;
PINSEL0 = (PINSEL0 & 0xFFFFFFF0) | 0x5;
UART0_Init(115200, set);
U0FCR = 0x81;
U0IER = 0x01;
IRQEnable();
/*Enable UART0 Interruption*/
VICIntSelect = 0x00000000;
VICVectCntl0 = 0x20|0x06;
VICVectAddr0 = (uint32)IRQ_UART0;
VICIntEnable = 1<<0x06; //Enable UART0s Interruption
while (1)
{
if (rcv_new == 1)
{
rcv_new = 0;
UART0_SendBuf();
}
if (add_data == 1)
{
add_data = 0;
UART0_SendAddByte(add_data_num);
}
}
return 0;
}