📄 uart.c
字号:
/*= uart.c =========================================================================================
*
* Copyright (C) 2004 Nordic VLSI ASA
*
* Author(s): Ole Saether
*
* COMPILER:
*
* This program has been tested with Keil C51 V7.08
*
* $Revision: 1 $
*
*==================================================================================================
*/
#include <Nordic\reg24e1.h>
#include "uart.h"
static volatile unsigned char idata rxbuf[32]; // Uart recieve buffer
static volatile unsigned char rxrp; // Uart receive buffer read pointer
static volatile unsigned char rxwp; // Uart receive buffer write pointer
static volatile unsigned char rxn; // Number of characters left in receive buffer
static volatile unsigned char idata txbuf[32]; // Uart transmit buffer
static volatile unsigned char txrp; // Uart transmit buffer read pointer
static volatile unsigned char txwp; // Uart transmit buffer write pointer
static volatile unsigned char txn; // Number of characters left to send
void UartInit(void)
{
rxn = rxwp = rxrp = 0;
txn = txwp = txrp = 0;
RCAP2H = 0xFF;
RCAP2L = 0xF7; // 57600@16MHz
SCON = 0x50; // Serial port mode1, enable receiver
T2CON = 0x34; // Rx and Tx clock from Timer2, enable Timer2
P0_DIR |= 0x02; // P0.1 (RxD) is an input
P0_ALT |= 0x06; // Select alternate functions on pins P0.1 and P0.2
ES = 1; // Enable serial interrupt
}
void Serial (void) interrupt 4 using 2
{
if (RI)
{
RI = 0; // Clear receive interrupt bit
rxbuf[rxwp] = SBUF; // Store received character in receive buffer
rxwp = (rxwp + 1) & 0x1f; // Advance write pointer
rxn++; // Increment number of characters in buffer
}
if (TI)
{
TI = 0; // Clear transmit interrupt bit
txn--; // Decrement number of characters to send
if (txn > 0) // More characters in transmit buffer?
{
SBUF = txbuf[txrp]; // Yes, store next character in uart buffer
txrp = (txrp + 1) & 0x1f; // Advance read pointer
}
}
}
void PutChar(char c)
{
while(txn > 31) // Wait while transmit buffer is full
;
if (txn == 0) // If all previous characters are sent...
{
SBUF = c; // ...write character directly to the uart...
txn = 1;
} else
{
txbuf[txwp] = c; // ...else write it to the transmit buffer
txwp = (txwp + 1) & 0x1f; // Advance write pointer
ES = 0; // Disable serial interrupt while...
txn++; // ...incrementinfg numnber of characters to send
ES = 1; // Enable serial interrupt
}
}
unsigned char GetChar(void)
{
unsigned char c;
while(rxn == 0) // Wait until there is at least one character in the buffer
;
c = rxbuf[rxrp]; // Read next character from buffer
rxrp = (rxrp + 1) & 0x1f; // Advance buffer read pointer
ES = 0; // Disable serial interrupt while...
rxn--; // ...decrementing number of characters in buffer
ES = 1; // Enable serial interrupt
return c;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -