5 years, 7 months ago.

Receive a string, serial communication

I want to receive a word through serial communication and store it as a char array. how can I do this?

1 Answer

5 years, 7 months ago.

Obviously there are many examples out there of this. Use the default serial port on the mbed board. You’ll need a serial terminal for your PC like RealTerm. Then if you need to define rules about how you send messages back and forth. The physical connection needs to be defined (baud rate, parity, stop bits, flow control). Then you need to define framing for your messages. This can be as simple as saying you are using ascii encoded strings and that all messages end with a newline character ‘\n’.

The simplest program you can make is to wait in a loop receiving characters and putting them into a string buffer. When newline char is received you handle the new message (e.g. print it out), clear the buffer, and start looking for new characters. Since this prints out the same port it receives on, this is a loopback program. There are problems here (buffer size is not checked), but a simple example is:

#include "mbed.h"

Serial    pc(USBTX, USBRX);

const int kMaxBufferSize = 100;
char      buffer[kMaxBufferSize];
int       len = 0;

int main() {
    
    buffer[0] = '\0';
    
    pc.printf("Start...\n\n");
    
    while (true) {      
        while (pc.readable()) {
            char new_char = pc.getc(); 
            
            buffer[len++] = new_char;    
            buffer[len] = '\0';          
        
            // new message received, handle
            if (new_char == '\n') {
                printf("%s",buffer);
                len = 0;
            }
        }
    }
}

Blocking the whole program to receive, of course is often not a good idea. So people will attach a receive function that runs in interrupt context every time a new char is received on the serial port. The whole while pc.readable() block gets moved to the ISR function. The Serial port should be changed to type RawSerial port if using ISR to avoid problems with mutexes. You could also simply put the above receive code in its own low priority thread. It will spin in the background receiving characters but other threads will still be able to run.