ofSerial can't read integers from the Arduino! (only strings)

Hi,

I’m trying to send integers from the Arduino to my openFrameworks program. oF is behaving very strangely. It seems to be translating integers into a string of characters before it even gets to the openFrameworks readByte() function. Why would oF translate an integer into its string representation before it reads it from the serial buffer? What’s going on here? I’m using Ubuntu and of_v0.8.4_linux64_release.

The result is a 500X200 oF window that displays: 48 49

Note1: 48 is ascii code for ‘0’ and 49 is code for ‘1’. I used small numbers, but if I used 65 (ie Serial.print(65,DEC)) then the oF window would display the ascii code for 6 (ie the first digit of 65).

Note2: ofToString(255) displays 255 in the oF window, so I don’t think I’m using that wrong. readByte() just doesn’t seem to be reading the incoming byte properly.

Below is the Arduino Code, the openFrameworks Code, and a Partial Header file:

Arduino Code:

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

void loop() {
	Serial.print(0,DEC);
	Serial.print(1,DEC);

	delay(1000);
}}

openFrameworks Code:

 #include "ofApp.h"
int byte8;

//--------------------------------------------------
void ofApp::setup(){
    ofSetWindowShape(500, 200);
    ofBackground(255);
    font.loadFont("DIN.otf", 64);
    ofSetColor(0);
    serial.setup("/dev/ttyACM0", 9600);
}
//-------------------------------------------------
void ofApp::update(){   
    if (serial.available() == 0) return;
    else if (serial.available() > 1){
        msg = "";
        while(serial.available() > 0){
            byte8 = serial.readByte();
            msg += " " + ofToString(byte8);      }
    }
}
//----------------------------------------------
void ofApp::draw(){
    font.drawString(msg, 50, 100);
}

Partial Header File

    string msg;
    ofTrueTypeFont font;
    ofSerial serial;

Arduino’s Serial.print method always sends the ASCII string representation of input. You may want to try Serial.write to send raw bytes.

http://arduino.cc/en/serial/print

Also, be aware, if you are truly sending int (and not byte) you will need to break it up into several bytes before using Serial.write and reconstruct it in openFrameworks.

2 Likes