Processing IDE doesn't read data right from serial

493 views Asked by At

I am trying to make an arduino project with arduino ide and processing ide. I started doing a simple test to see the enviornment where I display the numbers 0,1..9 using arduino ide, but processing ide doesn't read it right for some reason and I can't figure out why, it reads weird numbers from serial like 10, 13, 53 and so on (only these numbers, nothing changes). Here is my processing code:

import processing.serial.*;
Serial port;

void setup() {
  port = new Serial(this,"/dev/ttyUSB0",9600);
}
void draw() {
  if(port.available() > 0) {
  int info = port.read();
  println(info);
  println("===");
  }
}

And here is my arduino code:

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int deg = 0;
  int data = 1;
  for (deg = 0; deg < 10; deg++) {
    Serial.println(deg);
    delay(15);
    delay(1000);
  }
}

Also, the board and processing are using the same port /dev/ttyUSB0. I am running all of this on Ubuntu 20.04. I tried to look on google but can't seem to find anything. Thanks in advance, any tip is welcome.

1

There are 1 answers

2
lurker On BEST ANSWER

Your are sending ASCII from Arduino and reading binary in your Processing IDE. Here is what your sender is doing:

for (deg = 0; deg < 10; deg++) {
  Serial.println(deg);
  ...
}

Serial.println prints the value, meaning it's formatted for display. That means it's converted to ASCII. The output of this will be each number, in ASCII, followed by a new line (thus the 'ln' in the println function):

48 10 13 49 10 13 50 10 13 ... 57 10 13

For example, Serial.println(0) will yield 48 10 13 which is the ASCII code for 0 followed by the new line sequence 10 13 (CR and LF).

Your receiver is doing this:

int info = port.read();
println(info);

Which will read these values as integers and format those numbers as ASCII outputs with new lines. So you will see on your display:

48 
10
13
...

The best way to solve this is to write binary data from Arduino instead of printing the data. On your Arduino, use Serial.write() instead:

for (deg = 0; deg < 10; deg++) {
  Serial.write(deg);
  ...
}