Reputation: 2409
I am reading in serial values in Processing. An example:
...
297.5
297.1
297.1
...
These numbers do not vary by much more than shown here.
Then, I run the following code:
if (val > 100) {
println(val);
}
It prints exactly what I have written above.
Then I run this code:
if (val > 100) {
val -= 230;
val *= 2;
println(val);
}
It prints out wildly differing numbers:
...
-189.59998
136.0
-188.0
135.0
-190.0
...
Thinking that something was screwy with my math (but how?!), I reduced my code to this:
if (val > 100) {
val -= 230;
println(val);
}
It prints, as expected, 67ish.
What is wrong with val *= 2
?!
The only thing I can think of is that I'm 'overflowing' the memory allocated for the float
datatype and so it's 'rolling over' to be negative... But how is that possible? I thought Processing was just a thin skin over Java.
import processing.serial.*;
Serial s;
float val;
void setup() {
size(600, 400);
String portName = Serial.list()[1];
s = new Serial(this, portName, 9600);
s.bufferUntil('\n');
}
void draw() {
if ( s.available() > 0) {
try {
val = Float.parseFloat(s.readStringUntil('\n').trim());
}
catch (Exception e) {
}
if (val > 100) {
val -= 230;
val = val * 2.0;
println(val);
}
}
}
I have pasted the unabridged version of the outputs at the following site. The first is the output without the arithmetic; then there is a line of ###
, and then the values after arithmetic is performed.
http://pastebin.com/raw.php?i=Du7TmZFv
Upvotes: 1
Views: 59
Reputation: 79875
The culprit is catch(Exception e){}
. Never do this.
When your exception is thrown, val
has the same value it had before. I'm guessing you've got some blank lines, or some illegal values in your input stream. Your program is failing to parse these as floats, throwing the exception, then just continuing onwards.
Upvotes: 6