Firstly, we need to know about Random Number Generation.
The Arduino library includes a function for creating random numbers. There are two flavors of the function random. It can either take two arguments (minimum and maximum) or one argument (maximum), in which case the minimum is assumed to be 0. Beware, though, because the maximum argument is misleading as the highest number you can actually get back is the maximum minus one, e.g. calculation a random number between 1 to 7 will give output between 1 to 6.
This project uses what we have just learned about random numbers to create electronic dice with six LEDs and a button. Every time you press the button, the LEDs “roll” for a while before settling on a value and then flashing it.
The schematic diagram for it is given. Each LED is driven by a separate digital output via a current-limiting resistor. The only other components are the switch and its associated pull-down resistor. Even though a die can only have a maximum of six dots, we still need seven LEDs to have the normal arrangement of a dot in the middle for odd numbered rolls.
Steps1) Connect the LEDs as shown in schematic. The pins for LEDs are {2,3,4,5,6,7,8}. The Button (SwitchPin) is connected to pin 8. Since all LEDs look alike, I've changed the wire color to show the difference. Red color shows +Vcc. Black shows GND. Orange, yellow ,green, and blue show respective LEDs.
2) Software: This sketch is fairly straightforward; there are a few nice touches that make the dice behave in a similar way to real dice. For example, as the dice rolls, the number changes but gradually slows. The length of time that the dice rolls is also random.
3) We now have seven LEDs to initialize in the setup method, so it is worth putting them in an array and looping over the array to initialize each pin. We also have a call to randomSeed
in the setup method. If this was not there, every time we reset the board, we would end up with the same sequence of dice throws.
4) The dicePatterns
array determines which LEDs should be on or off for any particular throw. So each throw element of the array is actually itself an array of seven elements, each one being either HIGH or LOW (1 or 0). When we come to display a particular result of throwing the dice, we can just loop over the array for the throw setting each LED accordingly.
5) Load the sketch in the Board from the IDE. Pressing the button will start rolling the dice.
Comments