We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I wrote a piece of code to read serial data (hex) and turns the data to dec for future usage, the code is as follows. But there's something wrong with the line: brightness=unhex(brightnessHEX). I have no idea about it and really hope somebosy here to help me with that.
import processing.serial.*;
Serial myPort;
int brightness = 0;
PFont font;
String brightnessHEX;
void setup() {
size(800, 600);
smooth();
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
myPort.bufferUntil('\n');
}
void draw() {
background(0);
while (myPort.available () > 0) {
brightnessHEX = myPort.readStringUntil('\n');
if (brightnessHEX != null) {
println(brightnessHEX);
brightness=unhex(brightnessHEX);
println(brightness);
}
}
......
}
Answers
Add this line before you unhex(): brightnessHEX = brightnessHEX.replaceAll("\n", "");
thanks amnon very much, I changed the code as you suggested, but the problem is still existed there.
Perhaps try out trim(): http://processing.org/reference/trim_.html
brightnessHEX = trim( myPort.readStringUntil('\n') );
or: http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#trim--
brightnessHEX = myPort.readStringUntil('\n').trim();
thanks GoToLoop a lot! the problem get resolved with via using trim() method. the workable code is as follows.
it's often helpful to do this, add things before and after your string, so you can see if it is really how it looks:
Also method length() is useful to check whether the # of
char
values are indeed what's expected:http://processing.org/reference/String_length_.html
koogs and GoToLoop, your tips are really great!