Portfolio. BHSAD Arduino Prototyping | L4, Harduino: Drawing light | Page 8
LED Dice
void setup() {
for (int i=first; i<=fifth; i++) {
pinMode(i, OUTPUT); }
pinMode(button, INPUT);
randomSeed(analogRead(0));
}
void buildUpTension() {
for (int i=first; i<=fifth; i++) {
if (i!=first) {
digitalWrite(i-1, LOW); }
digitalWrite(i, HIGH);
delay(100);
}
for (int i=fifth; i>=first; i--) {
if (i!=fifth) {
digitalWrite(i+1, LOW); }
digitalWrite(i, HIGH);
delay(100);
}
}
void showNumber(int number) {
digitalWrite(first, HIGH);
if (number >= 2) {
digitalWrite(second, HIGH);
}
if (number >= 3) {
digitalWrite(third, HIGH); }
if (number >= 4) {
digitalWrite(fourth, HIGH);
}
if (number >= 5) {
digitalWrite(fifth, HIGH);
}
}
int throwDice() {
// get a random number in the
range [1,6]
int randNumber = random(1,7);
return randNumber;
}
void setAllLEDs(int value) {
for (int i=first; i<=fifth; i++) {
digitalWrite(i, value);
}
}
void loop() {
pressed = digitalRead(button);
if (pressed == HIGH) {
setAllLEDs(LOW);
buildUpTension();
int thrownNumber =
throwDice();
showNumber(thrownNumber);
}
}
int first = 5;
int second = 6;
int third = 9;
int fourth = 10;
int fifth = 11;
int button = 13;
int pressed = 0;