Indice
Descrizione
In questo video tutorial vedremo come realizzare il gioco Simon sulla breadboard utilizzando la scheda di Arduino. Vedremo come costruire il circuito e come scrivere il codice per far funzionare il gioco.
#define BUZZER_PIN 10
#define START_BUTTON_PIN 11
#define LEVELS 100
#define STATE_STOPPED 0
#define STATE_SHOW 1
#define STATE_REPEAT 2
int buttons[4] = {9, 7, 5, 3};
int led[4] = {8, 6, 4, 2};
int notes[4] = {523, 587, 659, 698};
int sequence[LEVELS];
int level = 0;
int index = 0;
int state = STATE_STOPPED;
void setup(){
for(int i = 0; i < 4; i++){
pinMode(buttons[i], INPUT);
pinMode(led[i], OUTPUT);
}
pinMode(START_BUTTON_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
randomSeed(analogRead(A0));
}
void loop(){
if(digitalRead(START_BUTTON_PIN) == HIGH){
welcome();
}
if(state == STATE_SHOW){
showNextLevel();
}
if(state == STATE_REPEAT){
repeatSequence();
}
delay(10);
}
void playNote(int note){
tone(BUZZER_PIN, notes[note], 150);
digitalWrite(led[note], HIGH);
delay(150);
digitalWrite(led[note], LOW);
}
int readButtons(){
for(int i = 0; i < 4; i++){
if(digitalRead(buttons[i]) == HIGH){
return i;
}
}
return -1;
}
void welcome(){
int randomNumber;
for(int i = 0; i < 7; i++){
randomNumber = random(4);
tone(BUZZER_PIN, notes[randomNumber], 150);
digitalWrite(led[randomNumber], HIGH);
delay(75);
digitalWrite(led[randomNumber], LOW);
delay(75);
}
level = 0;
state = STATE_SHOW;
delay(1200);
}
void showNextLevel(){
sequence[level] = random(4);
for(int i = 0; i <= level; i++){
playNote(sequence[i]);
delay(200);
}
index = 0;
level++;
state = STATE_REPEAT;
}
void error(int note){
tone(BUZZER_PIN, 200, 1000);
digitalWrite(led[note], HIGH);
delay(1000);
digitalWrite(led[note], LOW);
state = STATE_STOPPED;
}
void win(){
int randomNumber;
delay(200);
for(int i = 0; i < 12; i++){
randomNumber = random(4);
tone(BUZZER_PIN, notes[randomNumber], 150);
for(int j = 0; j < 4; j++){
digitalWrite(led[j], HIGH);
}
delay(75);
for(int j = 0; j < 4; j++){
digitalWrite(led[j], LOW);
}
delay(75);
}
state = STATE_STOPPED;
}
void repeatSequence(){
int selectedNote = readButtons();
if(selectedNote >= 0){
if(selectedNote == sequence[index]){
playNote(selectedNote);
while(readButtons() != -1);
index++;
if(index >= level){
if(level < LEVELS){
state = STATE_SHOW;
delay(1000);
}else{
win();
}
}
}else{
error(selectedNote);
}
}
}