Search code examples
c++serializationserial-portarduinoopenframeworks

Openframeworks, reading serial data from Arduino


I'm trying to read serial data from an Arduino UNO using an ofSerialobject and assign it as an int. I am able to read in individual bytes, however, the values I'm receiving in the openframeworks console are not the same as the values I'm reading in the Arduino serial monitor.

I have provided screenshots of the respective consoles:

Arduino Serial Monitor

openframeworks console

My Arduino code is simply the basic "AnalogReadSerial" example available with the Arduino IDE.

// the setup routine runs once when you press reset:
void setup() {
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(sensorValue);
    delay(1);        // delay in between reads for stability
}

Whereas my C++ code is mostly copied from the documentation for the ofSerial readByte function.

void serialReader::setup()
{
    serial.listDevices();
    vector <ofSerialDeviceInfo> deviceList = serial.getDeviceList();

    serial.setup("COM4", 9600); //open the first device and talk to it at 9600 baud
}


void serialReader::printByteToConsole()
{
    int myByte = 0;
    myByte = serial.readByte();
    if ( myByte == OF_SERIAL_NO_DATA )
        printf("\nno data was read");
    else if ( myByte == OF_SERIAL_ERROR )
        printf("\nan error occurred");
    else
        printf("\nmyByte is %d ", myByte);
}

Any insight into what may be causing this disparity between the readings would be greatly appreciated. Thank you.


Solution

  • Arduino's Serial.println translates the raw bytes into their ASCII equivalent and then sends those bytes followed by linefeed (10) and carriage return (13) bytes. So, the raw byte 12 is sent as 4 total bytes -- two bytes representing the ASCII 1 (49), 2 (50) and then (10) and (13) for the new line characters. So, since openFrameworks does not automatically translate the ASCII values back into raw bytes, you are seeing the ASCII version. The Arduino console shows you the ASCII version as readable text.

    You can see the translation between ASCII and raw bytes (Decimal / aka DEC) here:

    http://www.asciitable.com/

    If you want the two numbers to match on both sides, consider using Serial.write in Arduino to write the raw bytes without ASCII translation and new line characters.