How to use scanf with USART

I’ve already posted how to use printf (send data to stream) on STM32Fxxx devices. Recently, I received a comment, how to use scanf function to read strings and convert them from USART. Here is a little bit more to do before it will work correct.

When you call scanf function, it calls subfunction fgetc, where you return a character. This function is called until it does not return EOF (-1). And it is called very fast. If you check in this function, if character is received from USART, then you return it, but because function is called faster than your USART data will be received, you will return EOF next time it is called and scanf function will detect we are done from receiving string, let’s convert string to desired formats. Technically, you will receive only one character maximum at a time to scanf function which is not correct.

To make it properly, you should write all characters received from USART to some temporary buffer (I suggest cyclic buffer) and when you call scanf, first check in function fgetc if there is end of string in your buffer. If it is, return the first character from buffer and do that until string delimiter is detected. When you detect string delimiter, return EOF.

scanf function will now wait for string delimiter received in buffer. When it will be received, entire string will be passed to scanf and converting will be successfully done if needed.

I hope you understand what I mean here.

tilz0R

Owner of this site. Application engineer, currently employed by STMicroelectronics. Exploring latest technologies and owner of different libraries posted on Github.

You may also like...