The complete dice kit is available from the Elektor Store. Included in the kit is a pre-programmed microcontroller. The microcontroller’s internal R/C oscillator generates an 8-MHz clock signal. The internal 1:8 divider is used to produce the 1-MHz controller clock frequency. Accurate timing is not essential in this application so an external crystal is not necessary. R9 is used as a pull-up resistor to tie the high-impedance Reset input up to a logic High (i.e. to disable it).

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.