kleydon/Mac-SerialPort-Cpp

Reading from uart

iandownie07 opened this issue · 3 comments

Hi, Kleydon

I think I've been able to set the uart connection up successfully, but I cannot see how I can use "readSerialData" to output a string that's waiting from the microcontroller. Could you give me an idea, please?

Ian

Hi @iandownie07,

Without more context, its a little hard to diagnose - but here are a couple of ideas:

  1. The function readSerialData takes two arguments: char* bytes, and size_t length. bytes is essentially an array, or buffer, passed by reference, so that after the call to readSerialData(), bytes should hold up to length bytes of data from the serial port. Note that bytes is not necessarily a c-string, which is ASCII-encoded, and null-terminated. Could it be the case that you are trying to print bytes, without adding a null-terminator, or ensuring that the bytes are ASCII characters?

  2. There are multiple ways to represent strings. (ASCII, UTF-8, UTF-16, etc.) Historically, micro-controllers (and micro-controller projects) tend to encode strings using ASCII c-strings - but not necessarily. You might check to verify that the data you are sending from the microcontroller is ASCII-formatted bytes (as opposed to some other string encoding, ascii-encoded hexidecimal output, or something else...)

  3. When in doubt, check configuration options (e.g. baud rate), and re-start your machine / microprocessor

  4. Here's a rough code sample that waits indefinitely to receive a byte (as an ascii character), then prints it:

    char rxChar;
    while (true) { //Infinite loop; in reality, you probably don't want to wait indefinitely...
        
        //Receive any new data available from the device, byte by byte
        ssize_t byteReceived = readSerialData(&rxChar, 1);
        if (byteReceived < 0) {
            eLog("readSerialData() failed. Errno:{}", errno); //Or you could use printf; errno is a number (I think...)
            return false;
        }
        else if (byteReceived == 0) { //Not a failure condition; sometimes you just don't receive anything (or are in the middle of receiving something...)
            return false;
        }
        if (byteReceived > 0) {
            
            //Add byte to line, update index, error-check
            lineStr[lineStrIndex] = rxChar;
            ++lineStrIndex;
            
            //Add termination character, to facilitate debugging, parsing, etc.
            lineStr[lineStrIndex] = '\0';
            
            printf("%s\n", lineStr);

            return true;
        }
    }

Hope this helps.

Excellent. Thanks for the reply. I think you've been able to point my in the right direction. I'll try it out and see if it works out.

Good luck!
Serial comms can be profoundly annoying - until they start working. (Then it's sort of magic.)