#define grupA 8 // Arduino pin driving LED at center
#define grupB 9 // Ardn pin to 2 LEDs at diagonal
#define grupC 10 // Ardn pin to 2 LEDs at the other diagonal
#define grupD 11 // Ardn pin to 2 LEDs at the sides, lit when showing 6.
int Btn; // reading of button
int ledState=0; // variable to count 0 to 5. Zero represents 6.
int dt=400; // delay time
int dtMin= 20; // delay time minimum, fastest
int dtMax= 400; // delay time maximum, slowest
int dtInc= 20; // delay time increment
void setup() {
pinMode(btnPin,INPUT_PULLUP);
pinMode(grupA,OUTPUT);
pinMode(grupB,OUTPUT);
pinMode(grupC,OUTPUT);
pinMode(grupD,OUTPUT);
}
void speedUp() {
if (dt > dtMax) { dt = dtMax; } // when dt is already very big, we just start from dtMax
dt = dt - dtInc; // reduce delay time dt, move faster
if (dt < dtMin) { dt = dtMin; } // when dt reaches minimum, no need to go below minimum
}
void slowDown() {
dt = dt + dtInc; // To slow down, we increace dt.
// In the main loop we check when button button is released, slow down,
// then if dt > dtMax we stop the rolling.
}
void showDice(int number) {
switch (number) {
case 0: { digitalWrite(grupA,LOW); digitalWrite(grupB,HIGH); digitalWrite(grupC,HIGH);
digitalWrite(grupD,HIGH); break; } // 6: all HIGH except groupA
case 1: { digitalWrite(grupA,HIGH); digitalWrite(grupB,LOW); digitalWrite(grupC,LOW);
digitalWrite(grupD,LOW); break; } // 1: only group A at the center
case 2: { digitalWrite(grupA,LOW); digitalWrite(grupB,HIGH); digitalWrite(grupC,LOW);
digitalWrite(grupD,LOW); break; } // 2: group B LEDs lit
case 3: { digitalWrite(grupA,HIGH); digitalWrite(grupB,LOW); digitalWrite(grupC,HIGH);
digitalWrite(grupD,LOW); break; } // 3: group A and C
case 4: { digitalWrite(grupA,LOW); digitalWrite(grupB,HIGH); digitalWrite(grupC,HIGH);
digitalWrite(grupD,LOW); break; } // 4: group B and C
case 5: { digitalWrite(grupA,HIGH); digitalWrite(grupB,HIGH); digitalWrite(grupC,HIGH);
digitalWrite(grupD,LOW); break; }// 5: A, B, and C
}
}
void loop() {
Btn = digitalRead(btnPin);
while (Btn==LOW) { // Button is pushed ON, start rolling
ledState = (ledState+1) % 6 ; // roll 0,1,2,3,4,5,0,1,...
showDice(ledState);
speedUp(); delay(dt);
Btn = digitalRead(btnPin);
} // Randomness is obtained from the fact that button is released at any random moment,
// at which moment the ledState is unknown by user because the die is rolling fast.
while ((Btn==HIGH) & (dt < dtMax)) { // high = button released, slow down.
ledState = (ledState+1) % 6 ; // still rolling while dt < dtMax. After reaching dtmax we stop.
showDice(ledState);
slowDown(); delay(dt);
Btn = digitalRead(btnPin);
}
}
Tidak ada komentar:
Posting Komentar