I'm trying to send data over serial and pick it up in a ruby script. I'm using the serialport gem (https://rubygems.org/gems/serialport) as stated in the Arduino docs (http://playground.arduino.cc/Interfacing/Ruby).
My question is, I'm trying to print out some gyroscope data, particularly the x, y, and z. This is what my arduino sketch looks like:
void setup() {
Serial.begin(9600);
// ... do some gyro stuff here
}
void loop() {
gyro.read();
Serial.print((int)gyro.g.x);
Serial.print(" ");
Serial.print((int)gyro.g.y);
Serial.print(" ");
Serial.print((int)gyro.g.z);
delay(500);
}
My ruby script is pretty straight forward as well:
require "serialport"
port_str = "/dev/tty.usbmodemfa141"
baud_rate = 9600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
while true do
message = sp.gets
if message
message.chomp!
puts message
end
end
However, the output that I get is choppy. What I mean by that is that the numbers don't come out as a single line as I intend:
52 9
5
250
-28
85
25
9 -5
1 69
Even if I replace it with "Hello World", it'll come out as:
He
llo
Wor
ld
or similar.
Any ideas why? Thanks in advance for any help.
2 Answers 2
Firstly, let's look into documentation for Ruby IO#gets:
Reads the next "line" from the I/O stream; lines are separated by sep ...
Secondly, look into documentation for Arduino Serial.print:
Prints data to the serial port as human-readable ASCII text ...
Finally, you don't print new line char \n
in your "arduino sketch" above.
I recommend you to use Serial.println
in the last line from your sketch:
void setup() {
Serial.begin(9600);
// ... do some gyro stuff here
}
void loop() {
gyro.read();
Serial.print((int)gyro.g.x);
Serial.print(" ");
Serial.print((int)gyro.g.y);
Serial.print(" ");
Serial.println((int)gyro.g.z);
delay(500);
}
Yes Arduino code is fine although your should use println() as a terminator.
I think you should read the message into a tmpMessage var. If tmpMessage is empty then break out the loop otherwise concatenate tmpMessage into the message var.
Then print the message var after the loop when no more data arrives.
It must be ruby inserting the line breaks when you use puts
Serial.println()
after printing all x y z.