In the previous article, we tried to run the DigitalOut class (GPIO output port) of Mbed.
This time, I will try to run the Serial class.
Here is the development environment at the time of posting.
PC: Windows 10 OS
IDE: STM32CubeIDE Version1.6.0
Configurator: STM32CubeMX Version6.2.1
Board: STM32Nucleo-F401RE
What is the Serial class in Mbed?
You can get an overview by looking at here.
Let’s try coding
Now let’s start writing the code.
Since the amount of code is small, you can use the previous project F401mbedBase as it is.
Try writing the while loop in main.cpp as follows.
/* USER CODE BEGIN WHILE */
Serial s(SERIAL_TX, SERIAL_RX);
s.baud(9600);
s.format(8, SerialBase::None, 1);
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
char c;
while (s.readable())
{
c = s.getc();
s.putc(++c);
}
}
/* USER CODE END 3 */
Set up the communication partner
It is convenient to use a PC connected with a debugger as a communication partner.
By using Tera Term and selecting STMicro’s VCP (Virtual COM Port), you can easily set up a communication environment.
What is VCP? If you are wondering what VCP is, please refer to the article here.
In this case, the baud rate is set to 9600, so please set it as follows.
It is necessary to match the contents of baud() and format() of the Serial class.
For the COM port, please select the Virtual COM Port that is detected when the board is connected with the USB cable.

Build and run it
Now try to build and run it.
If you just echo back the message, it is not clear whether the message is echoed on Tera Term or not.
This is the part of “s.putc(++c)”.
If you send a from your computer, b will be displayed, and if you send 3, 4 will be displayed.
If you don’t know why this happens, please look up “ASCII code table” on the net.
Explanation of the code
This is so simple that I don’t think it needs to be explained, but I’ll give you a glimpse.
Calling the constructor and the baud() and format() functions will finish the setup.
baud() is used to set the communication speed, and format() is used to set the communication parameters.
Compared to the HAL API, this requires less code.
readable() is defined in the base class SerialBase.
It returns 1 if there is data in the receive buffer, in which case it adds 1 to the read value and sends it back.
The familiar putc() and getc() are defined in the base class Stream.
How did you like it?





