-
Notifications
You must be signed in to change notification settings - Fork 1
/
ard-pi_tx-rx.ino
109 lines (92 loc) · 2.56 KB
/
ard-pi_tx-rx.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//Message structure: <message>
const byte numChars = 64;
char receivedChars[numChars];
int id, spin, brake, dir1, vel1, dir2, vel2;
boolean newData = false;
byte ledPin = 13; // the onboard LED
//===============
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
delay(200);
digitalWrite(ledPin, LOW);
delay(200);
digitalWrite(ledPin, HIGH);
Serial.println("<Arduino is ready>");
}
//===============
void loop() {
rxMessage();
if(newData)
{
Serial.println(receivedChars);
char* token = strtok(receivedChars, " ");
id = atoi(token);
spin = atoi(strtok(0, " "));
brake = atoi(strtok(0, " "));
dir1 = atoi(strtok(0, " "));
vel1 = atoi(strtok(0, " "));
dir2 = atoi(strtok(0, " "));
vel2 = atoi(strtok(0, " "));
}
returnMessage();
}
//===============
// TODO
// add message timeout
// add parsing of values x
//===============
void rxMessage() {
static boolean rxInProgress = false;
static byte index = 0;
char startMarker = '<';
char endMarker = '>';
char receivedString;
while (Serial.available() > 0 && newData == false) {
receivedString = Serial.read();
if (rxInProgress == true) {
if (receivedString != endMarker) {
receivedChars[index] = receivedString;
index++;
if (index >= numChars) {
index = numChars - 1;
}
}
else {
receivedChars[index] = '\0'; // terminate the string
rxInProgress = false;
index = 0;
newData = true;
}
}
else if (receivedString == startMarker) {
rxInProgress = true;
}
}
}
//===============
void returnMessage() {
if (newData == true) {
Serial.print("<");
Serial.print(id);
Serial.print(" ");
Serial.print(spin);
Serial.print(" ");
Serial.print(brake);
Serial.print(" ");
Serial.print(dir1);
Serial.print(" ");
Serial.print(vel1);
Serial.print(" ");
Serial.print(dir2);
Serial.print(" ");
Serial.print(vel2);
Serial.print('>');
// change the state of the LED everytime a reply is sent
digitalWrite(ledPin, ! digitalRead(ledPin));
newData = false;
delay(1000);
}
}
//===============