/
improvedGraphSerialEvent.ino
73 lines (53 loc) · 1.77 KB
/
improvedGraphSerialEvent.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
Replacement serialEvent() for that in the built-in example
Communication -> Graph
which does more thorough error checking and discards invalid data
It seems to capture most (all?) of the reasons for the float() conversion
to return NaN
Original code written
Created 20 Apr 2005 by Tom Igoe
Updated 24 Nov 2015 by Tom Igoe
Change log for this replacement:
October 30, 2017 - Michael Shiloh - check for non-numeric and invalid data
This example code is in the public domain.
Instructions for use:
1. In Arduino, open File -> Examples -> Communication -> Graph
2. Copy the Processing code from the Arduino code into a new Processing
window
3. In Processing, delete the serialEvent() function
4. In processing, paste the contents of this file
*/
void serialEvent (Serial myPort) {
// get the ASCII string:
String inString = myPort.readStringUntil('\n');
print(inString);
// trim off any whitespace
inString = trim(inString);
// Discard null strings
if (inString == null) {
println("discarding null string after trimming");
return;
}
// Discard strings that have fewer than 1 character
if (inString.length() < 1) {
println("discarding strings shorter than 1");
return;
}
// Discard strings that have any non-numeric characters
for (int i=0; i < inString.length(); i++) {
if ( (inString.charAt(i) < '0') || (inString.charAt(i) > '9') ) {
println("discarding non-numeric character");
return;
}
}
// convert the string to a float
float temp = float(inString);
// Values from Arduino analogRead() can only be
// between 0 and 1023
if ( (temp > 1023) || (temp < 0) ) {
println("discarding unreasonable value = " + temp);
return;
}
// map to the screen height
inByte = map(temp, 0, 1023, 0, height);
}