/* p4_4.c USART1 echo at 9600 Baud * * This program receives a character from USART1 receiver * then sends it back through USART1 transmitter. * USART1 is connected to PA9-Tx and PA10-Rx. * A 3.3V signal level to USB cable is used to connect PA9/PA10 * to the host PC COM port. * PA9 - USART1 TX (AF1) * PA10 - USART1 RX (AF1) * Use Tera Term on the host PC to send keystrokes and observe the display * of the characters echoed. * * By default, the clock is running at 8 MHz. * The UART2 is configured for 9600 Baud. * * This program was tested with Keil uVision v5.23 with DFP v2.0.0 */ #include "stm32F0xx.h" void USART1_init(void); void USART1_write(int c); char USART1_read(void); /*---------------------------------------------------------------------------- MAIN function *----------------------------------------------------------------------------*/ int main (void) { char c; USART1_init(); while (1) { c = USART1_read(); USART1_write(c); } } /*---------------------------------------------------------------------------- Initialize UART pins, Baudrate *----------------------------------------------------------------------------*/ void USART1_init (void) { RCC->AHBENR |= RCC_AHBENR_GPIOAEN; /* Enable GPIOA clock */ RCC->APB2ENR |= RCC_APB2ENR_USART1EN; /* Enable USART1 clock */ /* Configure PA9 for USART1_TX */ GPIOA->AFR[1] &= ~0x00F0; GPIOA->AFR[1] |= 0x0010; /* alt1 for USART1 */ GPIOA->MODER &= ~0xC0000; GPIOA->MODER |= 0x80000; /* enable alternate function for PA9 */ /* Configure PA10 for USART1_RX */ GPIOA->AFR[1] &= ~0x0F00; GPIOA->AFR[1] |= 0x0100; /* alt1 for USART1 */ GPIOA->MODER &= ~0x300000; GPIOA->MODER |= 0x200000; /* enable alternate function for PA10 */ USART1->BRR = 0x0341; /* 9600 baud @ 8 MHz */ USART1->CR1 = 0x000C; /* enable RxTx , 8-bit data */ USART1->CR2 = 0x0000; /* 1 stop bit */ USART1->CR3 = 0x0000; /* no flow control */ USART1->CR1 |= 0x0001; /* enable USART1 */ } /* Read a character from USART1 */ char USART1_read(void) { while (!(USART1->ISR & USART_ISR_RXNE)) {} // wait until char arrives return USART1->RDR; } /* Write a character to USART1 */ void USART1_write (int ch) { while (!(USART1->ISR & USART_ISR_TXE)) {} // wait until Tx buffer empty USART1->TDR = (ch & 0xFF); }