I need to get a serial signal from the Arduino board into a Processing sketch. I am sending values in string format, like "R12" "S40" "T80". When I capture those strings from Processing it will printing vertically (new line for each character). How can I get this as a string as it is what we sent?
I need code that can be put inside Processing's serialEvent method.
void loop() {
int r = random(10, 100);
int s = random(10, 100);
int t = random(10, 100);
Serial.print("R" + String(r));
Serial.print("S" + String(s));
Serial.print("T" + String(t));
delay(1000);
}
String data = "";
int R, S, T;
void serialEvent(Serial p) {
while(p.available() > 0) {
data = p.readString();
}
println(data);
}
I need to get the last received R S T values, respectively, to the R S T variables.
As mentioned previously, it is better to get the all the code to find the problem.
I suppose you did not add the function "bufferUntil()" in the Processing setup, so each time the serial received a value, it just displays it. I can propose you a solution. It is not the only one, but it seems to work.
In your Arduino code, instead of the Serial.print(), you should use Serial.println() to delimit your message.
void setup() {
Serial.begin(9600);
}
void loop() {
int r = random(10, 100);
int s = random(10, 100);
int t = random(10, 100);
Serial.println("R" + String(r));
Serial.println("S" + String(s));
Serial.println("T" + String(t));
delay(1000);
}
So you will send the message as
Rxx
Sxx
Txx
In Processing, you have to use the function "bufferUntil(lf)". It will save all messages from the serial port until it receives a "/n". After that, you should use another function to associate your identifier with the value.
// Example by Tom Igoe
import processing.serial.*;
Serial myPort; // The serial port
PFont myFont; // The display font
String inString; // Input string from serial port
int lf = 10; // ASCII linefeed
String data = "";
int R, S, T;
void setup() {
size(400, 200);
// List all the available serial ports:
printArray(Serial.list());
// Open whatever port is the one you're using, mine is one.
myPort = new Serial(this, Serial.list()[1], 9600);
myPort.bufferUntil(lf); // Delimiter of serial buffer end line
}
void draw() {
background(0);
text("received: " + " R=" + R + " S=" + S + " T=" + T, 10, 50); // Display value on the window
}
void serialEvent(Serial p) {
while(p.available() > 0) {
String buf = p.readString(); // Read serial input
println(buf);
if(!buf.equals('\n')) // Delete null='/n' from arduino println()
data = buf; // Save buffer
}
/*
char id = data.charAt(0); // Get id from buffer
int value = parseInt(data.substring(1, 3)); // Get the value from buffer
identifyVariable(id, value); // Associate id and value
*/
}
void identifyVariable(char ID, int value) {
switch(ID) { // Associate id with value
case('R'):
R = value;
break;
case('S'):
S = value;
break;
case('T'):
T = value;
break;
default:
println("error " + ID + " " + value);
break;
}
}