PROJECT: Dice Roll
Step 1 - Build the Project

To create a rolling die with a button and a single LED, you need to trigger a random event with your input and then show the outcome with your output. The die can have 6 possible positions, so using blinks on the one LED can show the outcome of the ‘roll’.

Step 2 - Upload the Code

/* * Press a button to 'roll a die' and get the outcome in blinks */ void setup() { pinMode(11,OUTPUT);//LED pinMode(A5,INPUT_PULLUP);//button } void loop() { //When button pressed, create a flashing effect 10 times on pin 1 if(digitalRead(A5) == LOW){ for(byte i = 0; i<30; i++){ digitalWrite(11,HIGH); delay(50); digitalWrite(11,LOW); delay(50); } delay(500); //pause after 'roll' has completed //choose a random number 1-6 and blink the LED that number of times for(byte i = 0; i<= random(1,7); i++){ digitalWrite(11,HIGH); delay(300); digitalWrite(11,LOW); delay(300); } } } // Try to add a speaker and that plays a rising tone while the dice rolls // (c) 2017 Let's Start Coding. License:

Step 3 - Read the Walkthrough

Within the setup() of the code, you need to have the button as an INPUT_PULLUP and the LED as an OUTPUT(). The real decision making within the code comes from the built in random() function in Arduino.

The loop doesn’t execute any code until the digitalRead of A5 is LOW, meaning the button is pressed. Immediately after that, the ‘for’ loop begins, which basically says “We’re creating a variable called ‘i’ that is equal to 0. Until ‘i’ is equal to 30, increase it by 1 for every loop of the ‘for’ loop.”. The contents of the ‘for’ loop are the flashing of the LED output on and off for 30 loops.

Once the flashes have completed, the next ‘for’ loop has to decide a random number for the outcome of the dice roll. The random() function will pick a number between 1 and 7, so 7 is not included in the possibilities.

The ‘for’ loop will blink through the ‘dice’ number, then the ‘for’ loop will exit and the loop will start over, waiting for another button press.