Skip to content

Instantly share code, notes, and snippets.

@aeris
Last active February 18, 2018 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aeris/92a5c0015de7cf84039f33183f88a58c to your computer and use it in GitHub Desktop.
Save aeris/92a5c0015de7cf84039f33183f88a58c to your computer and use it in GitHub Desktop.
Arduino dice (based on HelioxLab work : https://www.youtube.com/watch?v=S-oBujsoe-Q)
// Pour les LED
#define LED_PIN_1 2
#define LED_PIN_2 3
#define LED_PIN_3 4
#define LED_PIN_4 5
// Pour le capteur d’inclinaison
#define BUTTON_PIN 6
#define BUTTON_ACTIVE_LEVEL LOW
// Temps que le dé reste affiché 1000ms = 1 seconde
#define TIME 7000
class Dice {
public:
Dice(const int pin_1, const int pin_2, const int pin_3, const int pin_4) :
pins{pin_1, pin_2, pin_3, pin_4} {
// LEDs are outputs
for (int i = 0; i < 4; ++i) {
pinMode(this->pins[i], OUTPUT);
}
this->off();
};
void display(const int n, const int duration = 0) const {
if (n < 0 || n > 6) {
return;
}
const int *states = STATES[n];
this->set(states);
if (duration > 0) {
delay(duration);
this->off();
}
}
void off() const {
this->display(0);
};
void test(const int duration = 250) const {
for (int n = 1; n <= 6; ++n) {
this->display(n, duration);
}
}
private:
const int pins[4];
static const int STATES[7][4];
void set(const int pin, const int level) const {
digitalWrite(this->pins[pin], level);
}
void set(const int *levels) const {
for (int pin = 0; pin < 4; ++pin) {
const int level = levels[pin];
this->set(pin, level);
}
}
};
const int Dice::STATES[7][4] = {
{LOW, LOW, LOW, LOW}, // 0
{LOW, LOW, LOW, HIGH}, // 1
{HIGH, LOW, LOW, LOW}, // 2
{LOW, LOW, HIGH, HIGH}, // 3
{HIGH, LOW, HIGH, LOW}, // 4
{HIGH, LOW, HIGH, HIGH}, // 5
{HIGH, HIGH, HIGH, LOW}, // 6
};
Dice dice(LED_PIN_1, LED_PIN_2, LED_PIN_3, LED_PIN_4);
void setup() {
// On indique que le detecteur d'inclinaison est une entrée
pinMode(BUTTON_PIN, INPUT_PULLUP);
// On initialise le fait de pouvoir lancer des randoms
randomSeed(analogRead(0));
dice.test();
Serial.begin(9600);
}
void loop() {
const int buttonState = digitalRead(BUTTON_PIN);
Serial.println(buttonState);
if (buttonState == BUTTON_ACTIVE_LEVEL) { // Si on bouge le dé
long last = -1;
// Animation pour 8 affichages de dé avec 200 ms entre chaque
for (int i=0; i < 8; ++i) {
int ranim = last;
// On verifie que deux affichages consécutifs ne sont pas les mêmes
while (ranim == last) {
ranim = random(1, 7);
}
// On stock le chiffre pour éviter d'afficher les 2 mêmes valeurs de dé pendant l'animation
last = ranim;
dice.display(ranim, 200);
}
const int ran = random(1, 7);
dice.display(ran, TIME);
}
dice.off();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment