LED 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
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!