-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimon.ino
158 lines (126 loc) · 2.63 KB
/
Simon.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
148
149
150
151
152
153
154
155
156
157
158
const int BUTTON_1 = 12;
const int LED_1 = 13;
const int BUTTON_2 = 8;
const int LED_2 = 9;
const int BUTTON_3 = 4;
const int LED_3 = 5;
bool scanning;
int clickedButton;
int LEDpins[] = {LED_1, LED_2, LED_3 };
const int numOfLEDs = 3;
int buttonPins[] = {BUTTON_1, BUTTON_2, BUTTON_3};
const int numOfButtons = 3;
int sequenceArray[42];
int level;
int score;
int currentLED;
void setup()
{
randomSeed(analogRead(0));
//Initialize pins:
//LEDs
for (int i = 0; i < numOfLEDs; i++)
pinMode(LEDpins[i], OUTPUT);
//Buttons
for (int i = 0; i < numOfButtons; i++)
pinMode(buttonPins[i], OUTPUT);
score = 0;
level = 1;
currentLED = 0;
initiateArray();
playSequence();
}
void loop()
{
if (scanning)
scan();
}
void LEDpower(int LED, bool value)
{
if (value)
digitalWrite(LED, HIGH);
else
digitalWrite(LED, LOW);
}
void playSequence()
{
for (int i = 0; i < level; i++)
{
LEDpower(sequenceArray[i], true); //Turn LED on
delay(750); //Wait
LEDpower(sequenceArray[i], false); //Turn LED off
if (i != level - 1)
delay(350); //Wait
}
scanning = true;
}
void initiateArray()
{
bool temp;
for (int i = 0; i < 42; i++)
{
sequenceArray[i] = LEDpins[random(3)];
}
}
void scan() //Stay in while loop until the user has pressed one of the three buttons
{
scanning = false;
while (true)
{
if (digitalRead(BUTTON_1) || digitalRead(BUTTON_2) || digitalRead(BUTTON_3))
break;
}
if (digitalRead(BUTTON_1))
clickedButton = BUTTON_1;
else if (digitalRead(BUTTON_2))
clickedButton = BUTTON_2;
else
clickedButton = BUTTON_3;
verify();
}
void verify()
{
int led = clickedButton + 1;
currentLED = sequenceArray[score];
if (led == currentLED) //User is correct, keep going
{
score++;
LEDpower(led, true); //Turn on the clicked LED for half a second, and then turn it off
delay(400);
LEDpower(led, false);
if (score == level) //Last LED, play another sequence, this time more LED to remember
{
delay(250);
score = 0;
level++;
playSequence();
}
else //Not the last LED, keep going
{
scanning = true;
}
}
else //Incorrect, start all over
{
gameOver();
}
}
void gameOver()
{
delay(250);
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < numOfLEDs; i++)
{
LEDpower(LEDpins[i], true);
}
delay(250);
for (int i = 0; i < numOfLEDs; i++)
{
LEDpower(LEDpins[i], false);
}
delay(250);
}
delay(650);
setup();
}