Converting string to int or float
in
Programming Questions
•
1 year ago
Here's some code that gets data from Arduino and accumulates into an array, printing out after 5 s. But the data are always zero, even though the string has values of around 9000. I assume it is this:
data[j]=float(inString);
that is wrong. The string has a LF at the end, should I remove that first, and if so how?
data[j]=float(inString);
that is wrong. The string has a LF at the end, should I remove that first, and if so how?
- /*
Read in a string from the serial port and accumulate data for
a period
*/
import processing.serial.*;
String inString = null; // string input from the serial port
Serial inPort; // create object of serial class
int i=0; // counter for time stamps
int j=0; // counter for sampling loop
float ts=5000; // No of millisecs to accumulate
float t0,t; // Start time and running time
float[] data = new float [1000];
void setup() {
// Assign the serial port
inPort = new Serial(this,Serial.list()[0],9600);
inPort.clear(); // clear the buffer
// Discard the first reading in case we started in the middle of a string
inString = inPort.readStringUntil('\n');
inString = null;
// Initialise
t0=millis();
}
void draw() {
while (inPort.available() > 0) {
inString = inPort.readStringUntil('\n');
if (inString != null) {
// Grab elapsed time
t=millis();
// Check whether we've accumulated enough data yet
if (t-t0 < ts) {
// Accumulate data
data[j]=float(inString);
j++;
}
else {
// Print comma separated row of data and increment counter
print(i + "," + "," + j + "," + data[j] + "," + inString);
i++;
// Initialise for next run
j=0;
t0=millis();
}
}
}
}
void keyPressed() { // Press a key to stop
exit(); // stop the program
}
1