41. SPI Dice Roll

Build an SPI Master using any microcontroller to establish communication with an SPI Slave.

Task Description:

  • The SPI Slave acts as a digital dice roller, generating a random number between 1 and 6 whenever it receives a request from the master.
  • push-button switch is connected to the master. When the button is pressed, the master sends a request to the slave via SPI communication.
  • The slave responds with the generated random dice value.
  • The master then prints the received dice value on a serial terminal (e.g., PuTTY or the Arduino IDE Serial Monitor).

Note:
 The SPI Slave (dice roller) must operate in SPI Mode 2.
 Only the Master code needs to be developed for this task.

 

Example Slave Code for demonstration (Arduino UNO Dice Roller)

The following example demonstrates an Arduino-based SPI Slave configured in SPI Mode 2.

#include <SPI.h>

void setup() {
  pinMode(MISO, OUTPUT);  // Set MISO as OUTPUT to send data to the master

  // Enable SPI in slave mode
  SPCR |= _BV(SPE);

  // Send SPI data in mode 2
  SPI.setDataMode(SPI_MODE2);

  // Attach SPI interrupt
  SPI.attachInterrupt();

  // Generate a random number and store it to transmit during SPI communication.
  SPDR = random(1, 7);
}

ISR(SPI_STC_vect) {
  // Generate a random number and send it.
  SPDR = random(1, 7);
}

void loop() {
}

 

Example Serial monitor output:

 

 

Submit Your Solution

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