-
Notifications
You must be signed in to change notification settings - Fork 5
/
OnOff.ino
92 lines (80 loc) · 1.72 KB
/
OnOff.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
bool isOn = false;
enum messages {INERT, CLICKED, LISTENING};
byte messageState = INERT;
byte clickedNeighbor;
void setup() {
// put your setup code here, to run once:
randomize();
if (random(1) == 1) {
isOn = true;
}
}
void loop() {
// put your main code here, to run repeatedly:
if (buttonSingleClicked()) {
//change color, make neighbors change color
messageState = CLICKED;
}
switch (messageState) {
case INERT:
inertLoop();
break;
case CLICKED:
clickedLoop();
break;
case LISTENING:
listeningLoop();
break;
}
setValueSentOnAllFaces(messageState);
if (messageState == INERT) {
if (isOn) {
setColor(WHITE);
} else {
setColor(dim(WHITE, 75));
}
} else if (messageState == CLICKED) {
setColor(RED);
} else if (messageState == LISTENING) {
setColor(BLUE);
}
}
void inertLoop() {
FOREACH_FACE(f) {
if (!isValueReceivedOnFaceExpired(f)) {//neighbor!
if (getLastValueReceivedOnFace(f) == CLICKED) {
messageState = LISTENING;
clickedNeighbor = f;
}
}
}
}
void clickedLoop() {
byte inertNeighborsRemaining = 0;
FOREACH_FACE(f) {
if (!isValueReceivedOnFaceExpired(f)) {//neighbor!
if (getLastValueReceivedOnFace(f) == INERT) {
inertNeighborsRemaining++;
}
}
}
if (inertNeighborsRemaining == 0) {
switchOn();
messageState = INERT;
}
}
void listeningLoop() {
if (!isValueReceivedOnFaceExpired(clickedNeighbor)) {//clicked neighbor still there
if (getLastValueReceivedOnFace(clickedNeighbor) == INERT) {
switchOn();
messageState = INERT;
}
}
}
void switchOn() {
if (isOn) {
isOn = false;
} else {
isOn = true;
}
}