#include "stm32c0xx.h"
// Function prototypes
void UART1_Init(void);
void UART1_Receive(void);
void LED_Init(void);
void LED_On(void);
void LED_Off(void);
char received_data[100];
volatile int index_1 = 0;
int main(void) {
UART1_Init();
LED_Init();
Serial.begin(115200);
Serial.print("hello");
while (1) {
UART1_Receive(); // Receive data from UART
// Check the received command and control LED accordingly
if (received_data[0] == 'O' && received_data[1] == 'N' && received_data[2] == '\0') {
LED_On();
} else if (received_data[0] == 'O' && received_data[1] == 'F' && received_data[2] == 'F' && received_data[3] == '\0') {
LED_Off();
}
// Clear received data buffer
for (int i = 0; i < 100; i++) {
received_data[i] = 0;
}
index_1 = 0;
}
}
void UART1_Init(void) {
// Enable GPIOA and USART1 clocks
RCC->AHBENR |= RCC_IOPENR_GPIOAEN;
RCC->AHBENR |= RCC_APBENR2_USART1EN;
// Configure PA2 (TX) and PA3 (RX) for USART1
GPIOA->MODER &= ~(GPIO_MODER_MODE2 | GPIO_MODER_MODE3); // Clear mode bits
GPIOA->MODER |= (GPIO_MODER_MODE2_1 | GPIO_MODER_MODE3_1); // Set to alternate function mode
GPIOA->AFR[0] |= (4 << GPIO_AFRL_AFSEL2_Pos) | (4 << GPIO_AFRL_AFSEL3_Pos); // AF4 for USART1
// Configure USART1
USART1->BRR = 0x1A1; // Baud rate 115200 (assuming 16MHz clock, adjust if different)
USART1->CR1 = USART_CR1_TE | USART_CR1_RE | USART_CR1_UE; // Enable TX, RX, and USART
}
void UART1_Receive(void) {
while (!(USART1->ISR & USART_ISR_NE)); // Wait until RXNE (Receive Data Register Not Empty) is set
received_data[index_1++] = USART1->RDR; // Read received data
if (received_data[index_1-1] == '\n' || index_1 >= 100) { // End of command or buffer full
received_data[index_1-1] = '\0'; // Null-terminate the string
index_1= 0; // Reset index
}
}
void LED_Init(void) {
// Enable GPIOA clock
RCC->AHBENR |= RCC_IOPENR_GPIOAEN;
// Configure PA5 as output
GPIOA->MODER &= ~GPIO_MODER_MODE5; // Clear mode bits for PA5
GPIOA->MODER |= GPIO_MODER_MODE5_0; // Set to general purpose output mode
}
void LED_On(void) {
GPIOA->ODR |= GPIO_ODR_OD5; // Set PA5 high
}
void LED_Off(void) {
GPIOA->ODR &= ~GPIO_ODR_OD5; // Set PA5 low
}