How to read from multiple serial ports?

I have code that works well when connecting one Arduino and reading it’s data.
But now, I want multiple ofSerial() objects.
I think I am setting them up correctly; since the code works when not looping through my ofSerial array but just connecting 1 serial device.

But with this current arrayed version I only get data from 1 of my 3 ports. The other always report that 0 bytes are available.


 for(int serialIndex=0; serialIndex<3;serialIndex++){
        int availableData = serial[serialIndex].available();
        ofLog()<<serialIndex<<" serial[serialIndex].available() > 0, = "<<availableData;
        if(availableData > 0){
            receivedMessage = "";
            while(serial[serialIndex].available() > 0){
                //this is a dump of all the data in the serial buffer. can be a lot of characters
                char r = (char)serial[serialIndex].readByte();
                receivedMessage = receivedMessage + r;
            ofLog()<<"receivedMessage "<<receivedMessage;
void ofApp::getSerialDevice(){
    vector<ofSerialDeviceInfo> serialDevices = testSerial.getDeviceList();
    string deviceLine;
    int serialCounter = 0;
    for(int i=0; i<serialDevices.size();i++){
        deviceLine = serialDevices[i].getDeviceName().c_str();

        if(deviceLine.substr(0,11) == "cu.usbmodem"){
            serialID = "/dev/" +deviceLine;
            myBaud = 9600;
            ofLog()<<serialCounter<<" serialID "<<serialID<<" , myBaud "<<myBaud;


hi. i prefer to use ofxSerial.
It gives a lot more options and I like that I can connect to each serial object based on the name of its port.
I was using something like the following to connect to the correct serial port.

		std::vector<ofxIO::SerialDeviceInfo> devicesInfo = ofxIO::SerialDeviceUtils::listDevices();
		for (std::size_t i = 0; i < devicesInfo.size(); ++i){
			ofLogNotice("ModulesController::setup") << "\t" << devicesInfo[i];
		std::string arduinoPort = "";
		std::string dynamixelPort = "/dev/cu.usbserial-FT2N09VO";
		for(auto& d: devicesInfo){
			if(ofIsStringInString(d.description(), "Arduino")){
				arduinoPort = d.port();
			}else if(ofIsStringInString(d.description(), "ROBOTIS")){
				dynamixelPort = d.port();
		if (!arduinoPort!=""){
			bArduinoConnected = arduinoSerial.setup(arduinoPort, 115200);
				ofLogNotice("ModulesController::setup") << "Successfully connected to Arduino" << devicesInfo[0];
				ofLogNotice("ModulesController::setup") << "Unable to connect to Arduino :( " << devicesInfo[0];
			ofLogNotice("ModulesController::setup") << "No devices connected.";
	//Then just do the same for the other port.

It works for me. Look at ofxSerial’s examples. It is really nice. I really like the feature that it has to pack and unpack bytes to and from the arduino.

thanks for the advice.
I will give it a try inn the next couple of days. hope it works with multiple simultaneously running connections.

cool yes this worked very well.

1 Like