[solved] Strange problem when interfacing Arduino with Ruby (serialport gem)

I'm coding a serial protocol to control the arduino (like the "arduino" gem).

The problem I have is that the transmission will hit timeouts continuosly, making it unusable. I also tried the "arduino" gem and got the same problem.

So, after a lot of trials and errors, I found the solution/bug.

Start the arduino IDE -> Start the Serial Monitor -> Close it.

Doing this, the serial port gets "fixed" and no more timeouts happen with the "arduino" gem or my own code.

I initialize the serial port like this:

def initialize(port = "/dev/ttyUSB0")
    @serial = SerialPort.new(port, BAUDRATE, 8, 1, SerialPort::NONE)
    @serial.sync = true
    @serial.read_timeout = TIMEOUT

My conclussion is the "serialport" gem initializes in a wrong way the serial port, and the Arduino Serial Monitor fixes that.

Have you faced this trouble?

As you have not posted a full program it is hard to comment.

An issue that is commonly overlooked is the fact that the Arduino resets when the PC program (in any language) opens the serial port. The PC program needs to allow time for the Arduino to reset. It is also essential that the PC program keeps the serial port open until it is completely finished with the Arduino.

I have not use MRI Ruby for a long time - but I did use JRuby for a considerable time until I got fed up with the fact that there are so few people with whom I can share code and switched to Python. Your code makes me homesick - but I will be practical and stick with Python.

This Thread with a Python demo also includes a JRuby version of the same program.


Hi, I fixed the issue. For some reason the XON/XOFF protocol is not deactivated by default when initializing the serial port in ruby (when using the serialport gem).

So adding a:

@serial.flow_control = SerialPort::NONE

fixed the issue.