-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadWeight.ino
72 lines (67 loc) · 2.21 KB
/
readWeight.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
// Format: <STX> <SIGN> <WEIGHT(7)> <STATUS> <ETX>
// STX: Start of transmission character (ASCII 02).
// ETX: End of transmission character (ASCII 03).
// SIGN: The sign of the weight reading (space for positive, dash (-) for negative).
// WEIGHT(7): A seven-character string containing the current weight including the decimal point.
// If there is no decimal point, then the first character is a space. Leading zero blanking applies.
// STATUS: a status indication, G/N/U/O/E representing Gross / Net / Underload / Overload / Error, respectively.
#define STX 0x02
#define ETX 0x03
enum {
WAITING,
RECEIVING,
COMPLETING,
} receiveState;
void readWeight() {
static char buff[8]; // Buffer to store the weight.
static byte nChars = 0; // Number of characters in buffer.
static char stat = 0;
if (Serial1.available()) {
char c = Serial1.read();
switch (receiveState) {
case WAITING:
if (c == STX) {
receiveState = RECEIVING;
}
break;
case RECEIVING:
if (nChars == 0) { // receive SIGN
if (c == '-' || c == ' ') {
buff[nChars] = c;
nChars++;
}
}
else if (nChars > 0 && nChars < 8) { // receive WEIGHT
if ((c >= '0' && c <= '9') || c == '.' || c == ' ' ) {
buff[nChars - 1] = c;
nChars++;
}
if (nChars == 8) {
buff[7] = 0;
}
}
else if (nChars == 8) { // receive STATUS
// G = Gross.
// N = Net.
// U = Underload.
// O = Overload.
// E = Error.
// M = unknown status - used by scale simulator.
if (c == 'G' || c == 'N' || c == 'U' || c == 'O' || c == 'E' || c == 'M') {
stat = c;
}
receiveState = COMPLETING;
}
break;
case COMPLETING:
if (c == ETX) {
float f = atof(buff);
scaleWeight = f;
latestWeightReceivedTime = millis();
}
receiveState = WAITING;
nChars = 0;
break;
}
}
}