Tiny-Dice: Electronic Dice Using an ATtiny2313
The source code
The dice program shown in Listing 1 (see downloadable article below) has been produced using the free WinAVR tool chain. The GCC compiler contained in the tool chain generated the machine code for the ATtiny2313A controller. The basic principle of operation is quite simple; the microcontroller does not have a built-in random number generator so we use an 8-bit timer as a counter which is configured to continually count up to a maximum, overflow to zero and count up again. The counter overflows about fifteen times per second.
Each press of the pushbutton generates two interrupts (one on pressing and one on releasing). At every second interrupt a loop is initiated which shows on the display (with ever increasing delay) numbers from 1 to 6 to simulate a dice rolling to a halt. Once this loop is executed the value of the counter which is running continually in the background is read and a value from 0 to 6 is calculated (the remainder value after dividing by 6, plus 1).
The resulting value is then displayed. Unless you can accurately synchronize your buttoning pushing with the internal counter clock, each number from one to six has an equal probability of being displayed and can be considered random.
The displayed LED segments for the numbers are represented in the code (0 to 9, only 1 to 6 are used). The program can of course be changed to show other numbers or even letters on the display.

Discussion (0 comments)