I am trying to send a value from Arduino to Processing but Processing receives different values that are not the one Arduino sent. For example Arduino sends a 3 but Processing receives a 51.
Could anybody help me?
Thank you very much.
The Arduino didn't send a 3. It sent the ascii representation of the character '3', which is 51.
The processing application read that byte, and stored it in an int. Why? If you were expecting to read character data, why did you store the value in an int? I would have stored it in a char.
Then, when you printed out the value, as an int, Processing printed the value 51. Had you stored the value as a char, Processing would have printed the value as a character, '3'.
Thank you PaulS,
I think I have followed your advise but I still receiving a 51 (printed like an int) in processing when I sent a int = 3 from Arduino.
In this code, the Arduino is not being told specifically how to send the 3, so it assumed that you meant for it to be converted to a string. If that is not what you want to do, then you need to pay more attention to your variable types.
Integers can not be send directly as numbers. Bytes can, if you use the optional argument to the print function, and supply a value of BYTE.
byte val = 3;
Serial.print(val, BYTE);
Bytes are limited to a range of values from 0 to 255.
It isn't clear what you want to do with the value that the Arduino sends, so whether this limit is acceptable, or not, is not clear.
There are ways to convert integers and larger types to a series of bytes that can be sent.
import processing.serial.*;
Serial myPort;
byte[] byteBuffer = new byte[10];
int val;
void setup() {
myPort = new Serial(this, Serial.list()[0], 9600);
}
void draw() {
if (myPort.available() > 0) {
int byteCount = myPort.readBytes(byteBuffer);
if (byteCount > 0 ) {
// Convert the byte array to a String
String myString = new String(byteBuffer);
// Show it text area
println(myString);
}
}
myPort.clear();
}