This repository has been archived by the owner on May 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path17_0077_0107_slave_1.ino
147 lines (137 loc) · 2.28 KB
/
17_0077_0107_slave_1.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include <Wire.h>
#define BOARD1 1
#define BOARD2 2
#define BOARD3 3
#define BOARD4 4
int debug = 1;
int currentBoard = BOARD2;
int nextBoard = BOARD1;
int numBoard = 3;
char receiveMessage[64] = "\0";
String serialInput;
String message;
String token;
int i = 0;
long time = 0;
bool haveReceived = 0;
int n = 0;
int checkMessage = 0;
int state = 0;
void setup()
{
Wire.begin(currentBoard);
Wire.onReceive(receiveEvent);
Serial.begin(9600);
}
bool cooldown()
{
if (millis() - time > 200)
{
haveReceived = 0;
return 1;
}
return 0;
}
void createToken()
{
if (checkMessage == 2 && state == 0)
{
token = "Token#1#";
token += n;
token += "#";
token += message;
n = 0;
checkMessage = 0;
message = "";
}
else if (state == 1)
{
token = receiveMessage;
}
else
{
token = "Token#0#";
}
if (debug)
{
Serial.print("Send Token : ");
Serial.println(token);
}
}
void sendToken()
{
Wire.beginTransmission(nextBoard);
createToken();
Wire.write(&token[0]);
Wire.endTransmission();
}
void printMessage()
{
for (int j = 10; j < i; ++j)
{
Serial.print(receiveMessage[j]);
}
}
void receiveEvent(int lenByte)
{
for (i = 0; i < lenByte; i++)
{
receiveMessage[i] = Wire.read();
}
receiveMessage[i] = '\0';
if (debug)
{
Serial.print("Receive : ");
Serial.println(receiveMessage);
}
state = receiveMessage[6] - '0';
if (receiveMessage[8] - '0' == currentBoard)
{
state = 0;
printMessage();
}
time = millis();
haveReceived = 1;
}
void loop()
{
// delay(100);
while (Serial.available())
{
serialInput = Serial.readString();
if (checkMessage == 0)
{
n = serialInput.toInt();
if (n > numBoard || n <= 0)
{
Serial.println("Invalid Input Board");
Serial.println("Available Board : 1 2 3");
n = 0;
}
else
{
checkMessage = 1;
}
}
else if (checkMessage == 1)
{
message = serialInput;
checkMessage = 2;
Serial.print("Create Token : Token#1#");
Serial.print(n);
Serial.print("#");
Serial.println(message);
}
else
{
Serial.println("Can't queue more than 1 message");
}
}
if (haveReceived)
{
if (cooldown())
{
sendToken();
}
}
}