Guide no. 45
Display, button and random numbers: press it and the dice rolls on the screen, slows down and stops. A project that brings the previous guides together.
By Ada Intelisano · informaticait.it technical team
- The display from guide no. 44 plus a button on pin 2.
random(1, 7)gives a number from 1 to 6.randomSeed(analogRead(A0)): different rolls at every power-up.- A
forloop with longer and longer pauses makes the dice slow down.
Your first project to actually use: a dice for board games. Press the button, the numbers spin fast, slow down and stop on one from 1 to 6. We put together the button from guide no. 35 and the display from no. 44.
1Get the parts ready
- the 16×2 LCD display with I²C module from guide no. 44, already working
- a pushbutton, the breadboard and four more jumper wires
2Build the circuit
The display has the same wires as in guide no. 44, with one difference: now GND has two jobs. Take the board's GND to the − rail of the breadboard, and from there run one wire to the display GND and a short jumper to one leg of the button. The other leg of the button goes to pin 2 (green wire).
3Write and upload the sketch
// Electronic dice: press the button, the numbers spin and stop on one from 1 to 6. #include <Wire.h> #include <hd44780.h> #include <hd44780ioClass/hd44780_I2Cexp.h> hd44780_I2Cexp lcd; const int BUTTON = 2; // with the ESP32 write 27 void setup() { pinMode(BUTTON, INPUT_PULLUP); randomSeed(analogRead(A0)); // A0 left free: a different "noise" at every power-up lcd.begin(16, 2); lcd.print("Electronic dice"); lcd.setCursor(0, 1); lcd.print("Press the button"); } void loop() { if (digitalRead(BUTTON) == LOW) { // you pressed it int number = 1; for (int roll = 0; roll < 15; roll++) { // 15 numbers, slower and slower number = random(1, 7); // from 1 to 6 (7 is excluded) lcd.setCursor(0, 1); lcd.print("Roll: "); lcd.print(number); lcd.print(" "); delay(40 + roll * 15); } while (digitalRead(BUTTON) == LOW) {} // wait until you let go of the button } }
random(1, 7) picks a random number from 1 to 6: the second number is excluded, which is why you write 7.randomSeed(analogRead(A0)) makes it start from a different point by reading a free pin where the value changes by itself.4How the dice rolls
The for loop repeats 15 times: it picks a number, writes it, waits. The wait is
40 + roll * 15 thousandths of a second: 40 on the first pass, 250 on the last. That is why the numbers slow down like a real dice coming to a stop.
The last number written is the result.
for (int roll = 0; roll < 15; roll++): start from 0 and add 1 at each pass as long as roll is less than 15. The lines between the curly braces run 15 times.- Blank display: guide no. 44, step 4 (contrast and connections).
- Nothing happens: is the green wire on pin 2? Does the button straddle the center groove?
- It keeps rolling by itself: the button is turned the wrong way. Rotate it a quarter turn.
5Challenge yourself
- Two dice: write two numbers on the same row, and their sum too.
- Add the buzzer from guide no. 38: a “tick” for every number that spins by.
- Count how many times you get a 6: out of 60 rolls, about 10?
random(min, max)picks a number, with the maximum excluded;randomSeedstops the rolls from repeating the same way at every power-up;forrepeats a piece of the sketch an exact number of times.
With the ESP32 (button on GPIO 27) the 5 V display needs a level shifter: guide no. 44.
Useful products
Other guides
- Resistor colour code and tolerances
- N-channel and P-channel MOSFETs
- Bipolar transistor (BJT) or MOSFET?
- Relays: how to drive them and how much current they draw
- THT and SMD/SMT components
- XIAO board pinouts
- LEDs: forward voltage and series resistor
- The multimeter: measuring voltage and current
- Wemos D1 mini: first steps
- MOSFET module with Arduino and ESP32
- Relay module with Arduino and ESP32
- 3D printing filaments: PLA, PETG and fibre-filled versions
- Analog and digital: the differences
- ADS1115: 16-bit converter with Arduino and ESP32
- From bits to real values: converting sensor readings
- DS3231 RTC clock with Arduino and ESP32
- Linear or switching regulator: which one to choose
- Step-down, step-up and buck-boost: choosing the right module
- Voltage divider: reading voltages higher than 5 V or 3.3 V
- Pull-up, pull-down and bounce: wiring a button properly
- 3.3 V and 5 V logic levels: getting an ESP32 and an Arduino to talk
- The I²C bus: addresses, pull-ups and the scanner
- Lithium batteries: voltages, charging and protection
- ESP32 power consumption and deep sleep: how long the battery lasts
- Temperature sensors compared
- ESP32: which pins to use and which to avoid
- Getting started with the ESP32 in Arduino IDE 2 and PlatformIO
- SSD1306 OLED display and 16×2 I²C LCD with Arduino and ESP32
- PIR motion sensor and HC-SR04 ultrasonic sensor
- Date and time from the Internet with the ESP32: NTP, Italian time zone and daylight saving time
- MicroSD data logger: saving measurements to CSV
- Solar-powered ESP32: panel, charger and the numbers for Italy
- Web server on the ESP32: control a relay from your phone
- Your first LED: wire it up and make it blink
- The button: let Arduino decide
- The potentiometer: turn a knob and read its value
- Soft light: adjusting the brightness of an LED
- The buzzer: playing notes and melodies
- The traffic light: three LEDs in sequence
- The thermometer: reading the temperature with the TMP36
- The servo motor: moving an arm with Arduino
- The night light: the photoresistor and your first decision
- The relay: switching on a light bulb with Arduino
- The LCD display: making Arduino write
- The RGB LED: every color from three lights
- The joystick: two-axis control with a shield
- The LED ring: twelve colors from a single pin
- The DC motor: driving it with a MOSFET
- Soil moisture: the plant that asks for water
- The stepper motor: turn exactly as far as you want
- The parking sensor: faster and faster beeps
- The 7-segment display: big, bright numbers
- Automatic watering: the plant that waters itself
- The keypad: a lock with a secret code
- Networked weather station: values and chart on your phone
- A Telegram bot on the ESP32: your home from your phone
- MQTT with the ESP32: the language of connected devices
- Updating the ESP32 over Wi-Fi (OTA)
- ESP-NOW: two ESP32 boards talking without a router
- WebSocket with the ESP32: the LED that follows the slider
- Readings on a Google sheet, with deep sleep
- WiFiManager: choose the Wi-Fi from your phone
- Bluetooth LE with the ESP32: the phone without a network
- The camera in your browser with the ESP32-S3
- A portable Bluetooth speaker you build yourself
- Bluetooth desktop speakers, 2 × 20 W
- Stereo MP3 player with two buttons
- The shelf that plays music: a Visaton exciter
- How to solder well
- How much does it draw? Current and power with the INA219
- Load-cell scale with the HX711
- CO2 traffic light: when to open the windows
- RFID card door opener
- GPS: track logger on microSD
- LoRa: how far does it go? A range test with two boards
- Battery weather sign with an e-paper display
- Web radio with an ESP32 and an I2S amplifier
- Getting started with the Raspberry Pi Pico 2 in MicroPython
- Your first amplifier: the LM386 and a speaker
- Talking Arduino: the DFR0760 speech synthesis module
- The spectrum of your music on an LED matrix
- Drawing with 64 LEDs: the 8×8 matrix with the MAX7219
- A real voltage: the 12-bit MCP4725 DAC
- The heartbeat on Arduino: an ECG with the AD8232