MSP430 串口函數
發布時間:2008-10-22 21:56
發布者:
MSP430
#include
#include
void Usart0init()
{
char i=0;
WDTCTL = WDTPW + WDTHOLD; // Stop WDT
BCSCTL1 |= XTS; // ACLK = LFXT1 = HF XTAL
do
{
IFG1 &= ~OFIFG; // Clear OSCFault flag
for ( i = 0xFF; i > 0; i--); // Time for flag to set
}
while ((IFG1 & OFIFG) != 0); // OSCFault flag still set?
BCSCTL2 |= SELM1+SELM0; // MCLK = LFXT1 (safe)
UCTL0|=SWRST; //控制寄存器位
UCTL0|=CHAR;
//UCTL0 = CHAR; // 8-bit character
UTCTL0 = SSEL0; // UCLK = ACLK
UBR00 = 0x41; // 8MHz 9600
UBR10 = 0x3; // 8MHz 9600
UMCTL0 = 0xa4; // 8MHz modulation
UCTL0&=~SWRST; //選擇發送時鐘源置位
ME1 |= UTXE0 + URXE0; // Enable USART0 TXD/RXD
IE1 |= URXIE0; // Enable USART0 RX/TX interrupt
IE1 |= UTXIE0;
IFG1=0X00;
P3SEL |= 0x30; // P3.4,5 = USART0 TXD/RXD
P3DIR |= 0x10; // P3.4 output direction
_EINT(); // Enable interrupts
}
// USART Receiver buffer
#define RX_BUFFER_SIZE 8
char rx_buffer[RX_BUFFER_SIZE];
unsigned char rx_wr_index,rx_rd_index,rx_counter;
// This flag is set on USART Receiver buffer overflow
char rx_buffer_overflow;
// USART Receiver interrupt service routine
#pragma vector=USART0RX_VECTOR
__interrupt void usart0_rx (void)
{
char status,data;
status=URCTL0;
data=RXBUF0;
if ((status & (FE | PE | OE))==0)
{
_DINT();
rx_buffer[rx_wr_index]=data;
if (++rx_wr_index == RX_BUFFER_SIZE) rx_wr_index=0;
if (++rx_counter == RX_BUFFER_SIZE) //如果接收緩沖區滿,則置位溢出,并且清除緩沖區
{
rx_counter=0;
rx_buffer_overflow=1;
};
_EINT();
};
}
#ifndef _DEBUG_TERMINAL_IO_
// Get a character from the USART Receiver buffer
#define _ALTERNATE_GETCHAR_
char getchar(void)
{
char data;
while (rx_counter==0);
data=rx_buffer[rx_rd_index];
if (++rx_rd_index == RX_BUFFER_SIZE) rx_rd_index=0;
_DINT();
--rx_counter;
_EINT();
return data;
}
#endif
// USART Transmitter buffer
#define TX_BUFFER_SIZE 8
char tx_buffer[TX_BUFFER_SIZE];
unsigned char tx_wr_index,tx_rd_index,tx_counter;
// USART Transmitter interrupt service routine
#pragma vector=USART0TX_VECTOR
__interrupt void usart0_tx (void)
{
if (tx_counter>0)
{
_DINT();
--tx_counter;
TXBUF0=tx_buffer[tx_rd_index];
_EINT();
if (++tx_rd_index == TX_BUFFER_SIZE) tx_rd_index=0;
}
}
#ifndef _DEBUG_TERMINAL_IO_
// Write a character to the USART Transmitter buffer
#define _ALTERNATE_PUTCHAR_
void putchar(char c)///將這個庫函數定向到串口
{
while (tx_counter == TX_BUFFER_SIZE); //發送緩沖區滿,則等待
if (tx_counter || ((UTCTL0 & TXEPT)!=1))
{
_DINT();
tx_buffer[tx_wr_index]=c;
if (++tx_wr_index == TX_BUFFER_SIZE) tx_wr_index=0;
++tx_counter;
_EINT();
}
else
{
TXBUF0=c;
}
}
#endif
|