Created
October 25, 2024 12:22
-
-
Save ryansturmer/cd44c887ec0b0a8fdafb31fef978d77c to your computer and use it in GitHub Desktop.
Embedded C Code Review Example 1 - UART Command Prompt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <string.h> | |
#define UART_RX_BUFFER_SIZE 64 | |
#define COMMAND_BUFFER_SIZE 32 | |
// Pseudo HAL for UART - definitions elsewhere | |
void UART_SendString(char *str); | |
void UART_ReceiveInterruptEnable(void); | |
void UART_ReceiveInterruptDisable(void); | |
uint8_t UART_GetReceivedData(void); | |
// Global variables | |
static uint8_t uart_rx_buffer[UART_RX_BUFFER_SIZE]; | |
static uint8_t command_buffer[COMMAND_BUFFER_SIZE]; | |
static uint8_t uart_rx_index = 0; | |
// Main function to initialize UART and enable interrupts | |
int main(void) { | |
UART_ReceiveInterruptEnable(); | |
while (1) {} | |
return 0; | |
} | |
void UART_IRQHandler(void) { | |
uint8_t data = UART_GetReceivedData(); // Fetch data from UART | |
if (uart_rx_index < UART_RX_BUFFER_SIZE) { | |
uart_rx_buffer[uart_rx_index++] = data; | |
} | |
if (data == '\n') { // Command received | |
UART_ProcessCommand(); | |
uart_rx_index = 0; | |
} | |
} | |
// Process the received command from UART buffer | |
void UART_ProcessCommand(void) { | |
strncpy((char *)command_buffer, (char *)uart_rx_buffer, uart_rx_index); | |
if (strcmp((char *)command_buffer, "ON\n") == 0) { | |
UART_SendString("Turning ON...\n"); | |
LED_TurnOn(); | |
} else if (strcmp((char *)command_buffer, "OFF\n") == 0) { | |
UART_SendString("Turning OFF...\n"); | |
LED_TurnOff(); | |
} else { | |
UART_SendString("Unknown command!\n"); | |
} | |
} | |
// LED control functions | |
void LED_TurnOn(void) { | |
GPIO_WritePin(LED_PORT, LED_PIN, 1); | |
} | |
void LED_TurnOff(void) { | |
GPIO_WritePin(LED_PORT, LED_PIN, 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment