This example demonstrates the use of the UART with the STM32F0Discovery board. The example outputs a startup messages and echos back any line of text you enter. The example uses interrupt driven serial input/output.
The layout for the circuit is shown below

As you can see you need to use a USB to 3.3V serial converter which relays communications between a terminal application on your PC and the ‘Discovery board. These can be bought for as little as €3 online if you shop around. I use one from dx.com but you will find them on lots of other sites.
The main body of the code looks like this:
#include "stm32f05xxx.h"
#include <stdio.h>
void delay(int dly)
{
while( dly--);
}
char UserInput[10];
int main()
{
int i=0;
initUART(9600);
while(1) {
eputs("Hello World\n");
egets(UserInput,10);
eputs("You entered : ");
eputs(UserInput);
eputs("\n");
delay(100000);
}
return 0;
}
The UART is initialized to run at 9600bps. Following this an endless while loop is entered which calls on two communications functions: eputs and egets. These functions behave just like puts and gets in a text based PC application. The function eputs outputs a given string to the UART while egets reads a string up to a maximum size from the terminal. Input is completed when the user presses Enter.
The serial communications functions are all implemented in a file called serial.c. This file contains the following functions:
- High level I/O functions
eputs -> Write a string to the serial port
egets -> Get a string from the serial port
- Intermediate level I/O functions
WriteCom -> Write bytes to the transmit circular buffer
ReadCom -> Read bytes from the receive circular buffer
PutBuf -> Put a byte into a circular buffer
GetBuf -> Get a byte from a circular buffer
GetBufCount -> Get the number of bytes in a circular buffer
- Low level UART functions
initUART -> Configure I/O pins and the USART hardware to run at the specified baud rate. Transmit and receive circular buffers are initialized.
isr_usart2 -> Interrupt service routine for USART2
usart_tx -> This function handles a transmit interrupt. If sends the next byte in the transmit circular buffer. If there are no bytes left to send it disables the transmitter.
usart_tx -> This function handles a receive interrupt. It places the received byte into the receive circular buffer. If the buffer is full it sets a global error flag.
Source code may be downloaded from here