41. SPI Dice Roll

 For this task, two microcontrollers are used to communicate via SPI

  • Master Microcontroller: Initiates SPI communication and reads random numbers when a button is pressed.
  • Slave Microcontroller: Acts as a dice roller, generating a random number between 1 and 6 when requested by the master.

 In the given example code, the Slave device is configured in SPI Mode 2, where CPOL = 1 and CPHA = 0.

SPI Communication Modes

SPI communication mode is defined by two parameters

  • CPOL (Clock Polarity): Defines the idle state of the clock.
  • CPHA (Clock Phase): Defines when data is captured and propagated.
ModeCPOLCPHAOutput EdgeData Capture
SPI_MODE000FallingRising
SPI_MODE101RisingFalling
SPI_MODE210RisingFalling
SPI_MODE311FallingRising

Slave SPI Configuration (Dice Roller)

  • Mode: SPI Mode 2 → CPOL = 1, CPHA = 0
  • Clock: SCK is idle high.
  • Data Timing: Captured on the falling edge, changed on the rising edge.
  • Frame Format: 8-bit, MSB first.
  • Operation: Generates a random number (1–6) on each master request and sends it over SPI.

This configuration ensures that the master and slave remain synchronised in data exchange.

Master SPI Configuration

  • Mode: SPI Mode 2 (CPOL = 1, CPHA = 0).
  • Data Size: 8-bit, MSB first.
  • SS/CS: Software-controlled GPIO (active-low).
  • Clock Speed: Prescaler adjusted to achieve ~100 kHz SCK frequency.
  • Pin Configuration:
    • MOSI, MISO, SCK → Push-pull mode (default for most MCUs).
    • MISO → Configured as input.

Hardware Connections

Master PinSlave PinDescription
MOSIMOSIMaster Out --> Slave In
MISOMISOMaster In <-- Slave Out
SCKSCKShared SPI Clock
CS/SSCS/SSSlave Select - active low
GNDGNDCommon Ground Reference

Button

  • Connected to Master GPIO with internal pull-up (active-low).
  • Button press → Logic LOW input to trigger SPI read.

Button Handling & Debouncing

  • Debounce Method
    • Simple delay: 20–50 ms, or
    • Timer-based debounce for stable detection.

       
  • Each debounced press triggers a single SPI transaction where the master reads the dice value from the slave.

By connecting the push-button to the master and configuring SPI in Mode 2 (matching the slave configuration), stable and synchronized communication is achieved.
When the button is pressed, the master requests a random number (1–6) from the slave and displays or uses the value accordingly.

Below are the solutions to the given task using different microcontrollers

  1. STM32 as master
  2. ESP32 as master
  3. Arduino UNO 

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!