Implementing String Reception via UART on CC2530 for Zigbee Communication
Serial comunication on the CC2530 microcontroller requires proper configuration of UART registers and interrupt handling. The following demonstrates how to receive complete strings from a host computer through UART0.
UART Initialization
void configureUART() {
CLKCONCMD &= ~0x40; // Set 32MHz crystal oscillator
while(CLKCONSTA & 0x40); // Wait for oscillator stabilization
CLKCONCMD &= ~0x47; // Set system clock to 32MHz
PERCFG = 0x00; // Use P0 for peripheral
P0SEL = 0x0C; // Configure P0.2 and P0.3 for UART
P2DIR &= ~0xC0; // Prioritize UART0 on P0
U0CSR |= 0x80; // UART mode
U0GCR |= 8;
U0BAUD |= 59; // 9600 baud rate
UTX0IF = 1; // Clear TX flag
URX0IF = 0; // Clear RX flag
U0CSR |= 0x40; // Enable receiver
IEN0 |= 0x84; // Enable global and UART interrupts
}
Interrupt Handler for Data Reception
volatile uint8_t buffer[128];
volatile uint16_t bufIndex = 0;
volatile uint8_t recvFlag = 0;
#pragma vector = URX0_VECTOR
__interrupt void handleUART() {
URX0IF = 0; // Clear interrupt flag
uint8_t incoming = U0DBUF; // Read received byte
buffer[bufIndex++] = incoming;
recvFlag = incoming; // Store last received character
if(bufIndex >= sizeof(buffer)) {
bufIndex = 0; // Prevent buffer overflow
}
}
String Transmission Functon
void transmitString(uint8_t *data, uint16_t length) {
for(uint16_t i = 0; i < length; i++) {
U0DBUF = data[i]; // Load byte into buffer
while(!UTX0IF); // Wait for transmission complete
UTX0IF = 0; // Clear TX flag
}
}
Main Application Logic
void main() {
configureUART();
while(1) {
if(recvFlag == '}') { // End of JSON detected
processData(buffer);
// Prepare response
uint8_t response[50];
buildResponse(response, buffer);
// Disable RX during transmission
U0CSR &= ~0x40;
transmitString(response, strlen(response));
U0CSR |= 0x40;
// Reset reception state
bufIndex = 0;
recvFlag = 0;
memset(buffer, 0, sizeof(buffer));
}
}
}
Key considerations:
- Buffer management is critical - ensure proper bounds checking
- Atomic operations when switching between transmit/receive modes
- Proper interrupt flag handling to prevant missed characters
- End-of-message detection (in this case using '}' as JSON terminator)