- Create a project that can simulate rolling a dice. When a button is pressed the program must be able to randomly choose a number and light up the appropriate LEDs. The program ends when you press the other push button. The program should also start randomly upon turning on the Arduino on its first run.
int time = 500;
long randNumber;
int led1 = 3;
int led2 = 4;
int led3 = 5;
int led4 = 6;
int led5 = 7;
int led6 = 8;
int led7 = 9;
int btn1 = 10;
int btn2 = 2;
int leds[] = {led1,led2,led3,led4,led5,led6,led7};
// the setup routine runs once when you press reset:
void setup() {
Serial.begin(9600);
// initialize the digital pin as an output.
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(led5, OUTPUT);
pinMode(led6, OUTPUT);
pinMode(led7, OUTPUT);
pinMode(btn1, INPUT);
pinMode(btn2, INPUT);
randomSeed(analogRead(0));
}
// the loop routine runs over and over again forever:
void loop() {
if(digitalRead(btn2) == HIGH){
TurnOffLeds();
//delay(time);
randNumber = random(1, 7);
Serial.println(randNumber);
switch (randNumber){
case 1:
digitalWrite(led7, HIGH);
delay(time);
break;
case 2:
digitalWrite(led5, HIGH);
digitalWrite(led2, HIGH);
delay(time);
break;
case 3:
digitalWrite(led5, HIGH);
digitalWrite(led2, HIGH);
digitalWrite(led7, HIGH);
delay(time);
break;
case 4:
digitalWrite(led5, HIGH);
digitalWrite(led1, HIGH);
digitalWrite(led6, HIGH);
digitalWrite(led2, HIGH);
delay(time);
break;
case 5:
digitalWrite(led5, HIGH);
digitalWrite(led7, HIGH);
digitalWrite(led1, HIGH);
digitalWrite(led6, HIGH);
digitalWrite(led2, HIGH);
delay(time);
break;
case 6:
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led1, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led2, HIGH);
delay(time);
break;
}
}
if(digitalRead(btn1) == HIGH){
TurnOffLeds();
}
}
void TurnOffLeds()
{
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
digitalWrite(led5, LOW);
digitalWrite(led6, LOW);
digitalWrite(led7, LOW);
}
What I learned:
Problems:
You can do it, too! Sign up for free now at https://www.jimdo.com