#include "stm32f4xx.h" void USART2_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; /* 1. Enable Clocks */ // GPIOA is on AHB1 RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); // IMPORTANT: USART2 is on APB1 (unlike USART1 which is APB2) RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); /* 2. Configure GPIO Pins (PA2 = TX, PA3 = RX) */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; // Alternate Function GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; // Pull-up is good for idle lines GPIO_Init(GPIOA, &GPIO_InitStructure); /* 3. Connect GPIO pins to Alternate Function 7 (USART2) */ // This step is required for STM32F4! GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2); // PA2 -> USART2_TX GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2); // PA3 -> USART2_RX /* 4. Configure USART Parameters */ USART_InitStructure.USART_BaudRate = 115200; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_Init(USART2, &USART_InitStructure); /* 5. Enable USART2 */ USART_Cmd(USART2, ENABLE); } void USART2_SendChar(char ch) { // Wait until Transmit Data Register is Empty (TXE) while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET); // Write data to register USART_SendData(USART2, (uint16_t)ch); } char USART2_ReadChar(void) { // Wait until Receive Data Register is Not Empty (RXNE) while (USART_GetFlagStatus(USART2, USART_FLAG_RXNE) == RESET); // Read data return (char)USART_ReceiveData(USART2); } int main(void) { // Initialize USART2 USART2_Init(); while (1) { /* ECHO LOGIC */ // 1. Wait for a character to arrive and read it char received = USART2_ReadChar(); // 2. Send the character back immediately USART2_SendChar(received); // Optional: If you press 'Enter' (CR), also send New Line (LF) if (received == '\r') { USART2_SendChar('\n'); } } }