Instruction:
Code:
- User press a input switch to start the dice.
- The dice displays 1-6 randomly (for 100 milliseconds) through a 7-segment display.
- If user press the input switch again it will stop at the current random
number and display the number - When input switch is pushed once again it will repeat the process from step 1 to 3.
Code:
/* Name: Digital Dice */ int pin_2 = 2; int pin_3 = 3; int pin_4 = 4; int pin_5 = 5; int pin_6 = 6; int pin_7 = 7; int pin_8 = 8; int pin_9 = 9; int buttonPin = 1; int buttonState; int val; int randNumber; int cnt = 0; void displayOne() { digitalWrite(pin_2, LOW); digitalWrite(pin_3, HIGH); digitalWrite(pin_4, HIGH); digitalWrite(pin_5, LOW); digitalWrite(pin_6, LOW); digitalWrite(pin_7, LOW); digitalWrite(pin_8, LOW); } void displayTwo() { digitalWrite(pin_2, HIGH); digitalWrite(pin_3, HIGH); digitalWrite(pin_4, LOW); digitalWrite(pin_5, HIGH); digitalWrite(pin_6, HIGH); digitalWrite(pin_7, LOW); digitalWrite(pin_8, HIGH); } void displayThree() { digitalWrite(pin_2, HIGH); digitalWrite(pin_3, HIGH); digitalWrite(pin_4, HIGH); digitalWrite(pin_5, HIGH); digitalWrite(pin_6, LOW); digitalWrite(pin_7, LOW); digitalWrite(pin_8, HIGH); } void displayFour() { digitalWrite(pin_2, LOW); digitalWrite(pin_3, HIGH); digitalWrite(pin_4, HIGH); digitalWrite(pin_5, LOW); digitalWrite(pin_6, LOW); digitalWrite(pin_7, HIGH); digitalWrite(pin_8, HIGH); } void displayFive() { digitalWrite(pin_2, HIGH); digitalWrite(pin_3, LOW); digitalWrite(pin_4, HIGH); digitalWrite(pin_5, HIGH); digitalWrite(pin_6, LOW); digitalWrite(pin_7, HIGH); digitalWrite(pin_8, HIGH); } void displaySix() { digitalWrite(pin_2, HIGH); digitalWrite(pin_3, LOW); digitalWrite(pin_4, HIGH); digitalWrite(pin_5, HIGH); digitalWrite(pin_6, HIGH); digitalWrite(pin_7, HIGH); digitalWrite(pin_8, HIGH); } void setup() { pinMode(buttonPin, INPUT); pinMode(pin_2, OUTPUT); pinMode(pin_3, OUTPUT); pinMode(pin_4, OUTPUT); pinMode(pin_5, OUTPUT); pinMode(pin_6, OUTPUT); pinMode(pin_7, OUTPUT); pinMode(pin_8, OUTPUT); pinMode(pin_9, OUTPUT); digitalWrite(9, 0); // start with the "dot" off Serial.begin(9600); randomSeed(analogRead(0)); } void randomVisit() { randNumber = random(1, 7); switch(randNumber) { case 1: displayOne(); break; case 2: displayTwo(); break; case 3: displayThree(); break; case 4: displayFour(); break; case 5: displayFive(); break; case 6: displaySix(); break; } delay(100); } void loop() { val = digitalRead(buttonPin); if(cnt % 2 == 1) { randomVisit(); } if(val != buttonState) { if(val == HIGH) { cnt++; if(cnt % 2 == 1) { randomVisit(); } } } buttonState = val; }
No comments:
Post a Comment