In Processing, I'm trying to use an incoming string value using Serial.readString(), from a slide pot. Checking the value with 'print' works just fine, however whenever I try to convert it, no luck. Any suggestions? The basic code is pretty straightforward:
import processing.serial.*;
Serial myPort;
String val;
Integer valInt;
void setup() {
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
}
void draw()
{
while(myPort.available() > 0){
val = myPort.readString();
println(val);
valInt = int(val); //<--- here's the problem, doesn't covert to integer
}
}
system
March 14, 2016, 6:57pm
2
valInt = int(val); //<--- here's the problem, doesn't covert to integer
What do you think the int() "function" is doing? It does NOT convert a string to an int.
Integer.parseInt(string) does.
Thanks PaulS,
After changing the code per your suggestion to:
valInt = Integer.parseInt(val);
println(valInt);
I get the error message:
NumberFormatExcpetion: For input string: "2ÿ"
any ideas? Sorry if this is basic, I'm just starting out! Any advice much appreciated.
system
March 14, 2016, 9:49pm
4
any ideas?
Yes. Don't call the function with strings that are not representations of numeric values.
Serial input does not belong in draw(). Use the serialEvent() method. Use Serial::bufferUntil() to define when serialEvent() will be called.
After getting the string, using readStringUntil(), use String::trim() to make sure that there is no garbage in the string.
Robin2
March 15, 2016, 8:16am
5
Have a look at Serial Input Basics - simple reliable non-blocking ways to receive data. There is also a parse example.
...R
system
March 15, 2016, 10:06am
6
Robin2:
Have a look at Serial Input Basics - simple reliable non-blocking ways to receive data. There is also a parse example.
...R
Not written for Processing, though...
PaulS:
Use the serialEvent() method
awesome, this worked a charm, thanks!
Robin2:
Have a look at Serial Input Basics - simple reliable non-blocking ways to receive data. There is also a parse example.
...R
Thanks Robin2, great material for someone starting out!
Robin2
March 15, 2016, 8:13pm
9
PaulS:
Not written for Processing, though...
Shoot. I was sure this was the Arduino Forum. Apologies ....
...R