Receive input via serial

I am using the code from Example 2 in this post: Serial Input Basics - updated to read data coming via serial. I'm using an ESP32 using Arduino framework on PlatformIO.

The code below is only allowing me to use keyboard input but I would like to send commands from a Qt program using QSerialPort to write("hello").

Any suggestions on how to modify the code?

const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;
void recvWithEndMarker();
void showNewData();

void setup() {
    Serial.begin(9600);
    Serial.println("");
}

void loop() {
    recvWithEndMarker();
    showNewData();
}

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        } else {
            receivedChars[ndx] = '\0';  // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(receivedChars);
        newData = false;
    }
}

I have opted for an alternative code and it is now working for me:

char buffer[16];
void process();

void setup() {
    Serial.begin(500000);
    Serial.flush();
}

void loop() { process(); }

void process() {
    while (Serial.available() > 1) {
        Serial.readBytesUntil('\n', buffer, 16);
        Serial.println(buffer);
    }
}

Check out my Arduino Software Solutions for lots of alternatives for reading text from Serial.
Both blocking and non-blocking.
Not clear from your post if you are reading text (null terminated) or just bytes of data.

You can easily interface Python and your Arduino using the compatible libraries pySerialTransfer and SerialTransfer.h (respectively). pySerialTransfer is pip-installable, SerialTransfer.h is installable via the Arduino IDE, and both come with many examples.

Basically, these libraries automatically packetize and parse USB/Serial data for fast and reliable communication without the hassle!

@Power_Broker I wonder if Python would be fast enough to handle the bandwidth. I will need 18 kilobytes per second from a 24bit ADC at 250 samples per second x 24 channels (TI ADS1299 daisy chained x 3). Do you think?

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.