Hello everyone !
I recieved my first Arduino yesterday. I'm very new to electronic and prgoramming but it appears that this wonderful device is very easy to play with.
So I started my little project. It's an ultra simple game using a button, 6LEDs (3 reds, 3 greens, along with the resistors) and a speaker (not used for now, will be used later to play a little music.
The idea is pretty simple : When the button is pushed, the Arduino choose a random number between 0 and 1. If the number is equal to 0, you lose so the 3 red LEDs will flash ; if the number is something else, you won so the 3 green LEDs will flash.
The only difficulty I had was to know how to choose a random number, I simply read the documentation for that.
But my device isn't working. If it works when I loose (apparently, because sometimes red LEDs are flashing when I push the button) it seems that the win condition isn't working at all (I never saw the green LEDs flashing, plus sometimes nothing happens when I push the button).
Here is my code, I think how I build my board is pretty obvious only by reading the code, but if you need it I'll post a photo of it.
const int ledPins[] = {2,3,4,5,6,7};
const int buttonPin = 9;
int buttonState = 0;
int randNumber;
void win() {
digitalWrite(ledPins[3], HIGH);
digitalWrite(ledPins[4], HIGH);
digitalWrite(ledPins[5], HIGH);
}
void lose() {
digitalWrite(ledPins[0], HIGH);
digitalWrite(ledPins[1], HIGH);
digitalWrite(ledPins[2], HIGH);
}
void setup() {
for(int i = 0; i < 6; i++){ pinMode(ledPins[i], OUTPUT);}
pinMode(buttonPin, INPUT);
digitalWrite (buttonPin, HIGH); //suggested by Groove
randomSeed(analogRead(0));
}
void loop() {
if (digitalRead(buttonPin) == LOW) {
randNumber = random(2); // Select a random number from 0 to 1. Fixed by Groove
if (randNumber == 0) {
lose();
} else { win(); }
while (digitalRead(buttonPin) == LOW) {/*WAIT FOR A RELEASE*/} // suggested by AlphaBeta
}
}
Thank you very much in advance for your answers !