aragonj5:
hello,
so i have made a code that in generates a rondom number 1, 15, and it displays binair on 4 leds i have installed.
that works so far.
de problem is it keeps generating, it needs to stop, so i can press a button the amount of time the random number is,
so if the number is 7, show with the leds, i have to press the button 7 times, if it is correct it must light led10 and if wrong must light led13, then it must restart and generate a random number again so i can play the "game" again
this is my code so far, but cant fix it
:
int buttonPin = 2;
int ledPin1 = 10;
int ledPin2 = 11;
int ledPin3 = 12;
int ledPin4 = 13;
byte randNumber;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
void setup() {
// put your setup code here, to run once:
pinMode (buttonPin, INPUT);
pinMode (ledPin1, OUTPUT);
pinMode (ledPin2, OUTPUT);
pinMode (ledPin3, OUTPUT);
pinMode ( ledPin4, OUTPUT);
Serial.begin(9600);
randomSeed(analogRead(0));
}
void loop() {
buttonState = digitalRead(buttonPin);
randNumber = random(1, 15);
Serial.println(randNumber);
if (randNumber & 0b0000001){digitalWrite(10, HIGH);} else {digitalWrite(10, LOW);}
if (randNumber & 0b0000010){digitalWrite(11, HIGH);} else {digitalWrite(11, LOW);}
if (randNumber & 0b0000100){digitalWrite(12, HIGH);} else {digitalWrite(12, LOW);}
if (randNumber & 0b0001000){digitalWrite(13, HIGH);} else {digitalWrite(13, LOW);}
delay(2000);
if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
buttonPushCounter++;
}
delay(50);
}
lastButtonState = buttonState;
if (buttonPushCounter % randNumber == 0) {
digitalWrite(10, HIGH);
}
else {
digitalWrite(13, HIGH);
}
}
Your code is changing the random number every time around the loop.
instead of doing everything in the loop() function break the program into more functions:
- void displayBinary(int randomNumber);
- int readButton();
- void allOn();
This function lights all LEDS, (correct Answer)
- void allOff();
Bad answer!
loop(){
int randomNumber =random(1,15);
displayBinary(randomNumber);
int buttonPresses = readButton();
if(buttonPresses == randomNumber) allOn();
else allOff();
delay(2000);
allOff();
}
Chuck.