PROJECT: Coin Toss
Step 1 - Build the Project

To create the feeling of a coin toss using code and lights, you need two things: a random outcome from 2 choices and a flicker that reminds you of a coin flipping through the air.

Step 2 - Upload the Code

/* * Press a button to 'flip a coin' between two LED lights on pins 2 and 3 */ void setup() { pinMode(2,OUTPUT);//LEDs pinMode(3,OUTPUT); pinMode(A5,INPUT_PULLUP);//button } void loop() { //When button pressed, create a flashing effect 30 times if(digitalRead(A5) == LOW){ for(int i = 0; i< 30; i++){ digitalWrite(2,HIGH); digitalWrite(3,LOW); delay(50); digitalWrite(3,HIGH); digitalWrite(2,LOW); delay(50); digitalWrite(3,LOW); } //Randomly decide a winner between 2 and 4 (2 or 3) and light it. digitalWrite(random(2,4),HIGH); delay(1500); digitalWrite(2,LOW); digitalWrite(3,LOW); } } // Make the number of times the 'for' loop runs a random value so you have // different lengths of time the coin is flipping. // (c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Step 3 - Read the Walkthrough

The output LEDs in this code act as a pair and you only need one input (the ‘flip’ button) to control them. First, set up your button as an INPUT_PULLUP and the LEDs as OUTPUTs. The loop is designed to wait for the button to be pressed, then enter into a flipping routine. So if the digitalRead(A5) is LOW, the code immediately drops into the ‘for’ loop, where you create a counting variable ‘i’ just for using with the ‘for’ loop.

The ‘for’ loop essentially says ‘there is an integer called ‘i’ and it is equal to 0. Until it is equal to 30, increase it by 1 every time this ‘for’ loop happens. The digitalWrite() of pins 2 and 3 with a short delay will occur 30 times before the code passes through the ‘for’ loop. The ‘for’ is what creates the ‘flipping’ effect.

After the flipping effect, the random() function decides a winner. To use random() this way, plug in the minimum and maximum values that the random number can be between. In this case, the number can be a whole number between 1 and 3, so it will never be 3. The vocabulary for this is that the random function is inclusive of the lower number and exclusive of the higher number.

After the random() function has determined which pin will come on, that pin is HIGH for one and a half seconds, then all lights are off and the loop waits for another button press to trigger a flip.

Tip: Using random will only work well with consecutive numbers. If you have LEDs on pins 12 and 2, the random number will most often land in between them, not illuminating either light!