-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswitch_manager.ino
116 lines (97 loc) · 2.32 KB
/
switch_manager.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
110
111
112
113
114
115
116
#define arr_len(x)(sizeof(x) / sizeof( * x))
const uint8_t SIGNAL_PINS[] = {A0, A1, A2, A3, A4, A5, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
bool is_receiver;
int NUM_PINS;
char startMarker = '<';
char endMarker = '>';
bool flashState;
char receivedChars[32];
int failedAttempts;
int bailThreshold = 10;
void setup() {
NUM_PINS = arr_len(SIGNAL_PINS);
failedAttempts = 0;
flashState = true;
pinMode(13, OUTPUT);
pinMode(12, INPUT);
Serial.begin(9600);
}
void loop() {
is_receiver = digitalRead(12);
digitalWrite(13, is_receiver);
if (is_receiver) {
receiver_loop();
} else {
sender_loop();
}
}
void sender_loop() {
for (int i = 0; i < NUM_PINS; i++) {
pinMode(SIGNAL_PINS[i], OUTPUT);
digitalWrite(SIGNAL_PINS[i], false);
}
delay(1);
unsigned int pinValue;
Serial.write(startMarker);
for (int i = 0; i < NUM_PINS; i++) {
pinMode(SIGNAL_PINS[i], INPUT);
pinValue = digitalRead(SIGNAL_PINS[i]);
char writeVal = 'F';
if(pinValue == HIGH)
{
writeVal = 'T';
}
Serial.write(writeVal);
}
Serial.write(endMarker);
}
void receiver_loop() {
for (int i = 0; i < NUM_PINS; i++) {
pinMode(SIGNAL_PINS[i], OUTPUT);
}
static boolean recvInProgress = false;
static byte ndx = 0;
char rc;
unsigned int serialAvailable = Serial.available();
if(serialAvailable <= 0)
{
failedAttempts += 1;
delay(10);
if(failedAttempts > bailThreshold)
{
for (int i = 0; i < arr_len(SIGNAL_PINS); i++) {
digitalWrite(SIGNAL_PINS[i], false);
}
digitalWrite(13, flashState);
flashState = !flashState;
delay(100);
}
return;
}
while (serialAvailable > 0) {
failedAttempts = 0;
rc = Serial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= NUM_PINS) {
ndx = NUM_PINS - 1;
}
} else {
receivedChars[ndx] = '\0'; // terminate the string
recvInProgress = false;
ndx = 0;
}
} else if (rc == startMarker) {
recvInProgress = true;
ndx = 0;
}
serialAvailable = Serial.available();
}
for (int i = 0; i < arr_len(SIGNAL_PINS); i++) {
char x = receivedChars[i];
bool pinValue = x == 'T';
digitalWrite(SIGNAL_PINS[i], pinValue);
}
}