Menu
CoddyTech

Dice Roller

Part of the Displays and Sensors section of Coddy's Arduino journey. Lesson 5 of 24.

random(1, 7) picks a whole number from 1 to 6. The first number is the lowest you can get; the second is one more than the highest.

The board has no real chance inside. random() works out each number from the one before, starting from a number called the seed. With the same seed it gives the same numbers on every run: your dice would roll 2, 2, 6, 3 each time you power it on.

randomSeed() sets the seed. Give it something that changes from run to run, like the time of the first button press. micros() counts in millionths of a second, and nobody presses at the same microsecond twice:

if (!seeded) {
  randomSeed(micros());
  seeded = true;
}
int roll = random(1, 7);

Seeding in setup() does not help: setup() runs at the same microsecond after every power on.

challenge icon

Challenge

Medium

The button is on pin 10 and the starter already notices the moment it goes down. Make a dice:

  • on each press, pick random(1, 7) and show it with showDigit()
  • at the first press only, call randomSeed(micros()) so the rolls differ from run to run

Press Run and press the button a few times, then Check.

Try it yourself

const int segmentPins[7] = {2, 3, 4, 5, 6, 7, 8};  // a, b, c, d, e, f, g

// One pattern a digit, read from the right: the last bit is segment a.
//                     gfedcba
const byte digits[10] = {
  0b0111111,  // 0
  0b0000110,  // 1
  0b1011011,  // 2
  0b1001111,  // 3
  0b1100110,  // 4
  0b1101101,  // 5
  0b1111101,  // 6
  0b0000111,  // 7
  0b1111111,  // 8
  0b1101111   // 9
};

void showDigit(int n) {
  for (int i = 0; i < 7; i++) {
    if (bitRead(digits[n], i) == 1) {
      digitalWrite(segmentPins[i], LOW);   // lit
    } else {
      digitalWrite(segmentPins[i], HIGH);  // off
    }
  }
}

const int buttonPin = 10;
bool wasPressed = false;
bool seeded = false;

void setup() {
  for (int i = 0; i < 7; i++) {
    pinMode(segmentPins[i], OUTPUT);
  }
  pinMode(buttonPin, INPUT_PULLUP);
  showDigit(0);
}

void loop() {
  bool pressed = digitalRead(buttonPin) == LOW;
  if (pressed != wasPressed) {
    if (pressed) {
      // the button was just pressed: roll a number from 1 to 6 and show it
    }
    delay(50);  // let the button settle
  }
  wasPressed = pressed;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Displays and Sensors

Practice on your own: Arduino playground