File: LED5.C
****************************************************************************/
#define Switch PORTB.F0
#define Pressed 0
//
// This function generates a pseudo random integer number
// between 1 and Lim
//
unsigned char Number(int Lim, int Y) {
unsigned char Result;
static unsigned int Y;
Y = (Y * 32719 + 3) % 32749;
Result = ((Y % Lim) + 1);
return Result;
}
//
// Start of MAIN program
//
void main() {
unsigned char J,L,U,R,Seed = 1;
unsigned char DICE[] = {0,0x08,0x01,0x09,0x06,0x0E,0x07};
TRISC = 0; // PORTC are outputs
TRISB = 1; // RB0 input
PORTC = 0; // Turn OFF all LEDs
for(;;) // Endless loop
{
if (Switch == Pressed) // Is switch pressed ?
{
J = Number(6,seed); // Generate first dice number
L = DICE[J]; // Get LED pattern
J = Number(6,seed); // Generate second dice number
U = DICE[J]; // Get LED pattern
R = 16*U + L; // Bit pattern to send to PORTC
PORTC = R; // Turn on LEDs for both dice
Delay_ms(3000); // Delay 3 seconds
PORTC = 0; // Turn OFF all LEDs
}
}
}
Figure 6.18: Program listing
Modifying the Program
The program given in Figure 6.18 can made more efficient by combining the two dice nibbles into a single table value as described here.
There are thirty-six possible combinations of the two dice values. Referring to Table 6.4, Table 6.5, and Figure 6.16, we can create Table 6.6 to show all the possible two-dice values and the corresponding numbers to be sent to PORTC.
Table 6.6: Two-dice combinations and the number to be sent to PORTC
| Dice numbers | PORTC value | Dice numbers | PORTC value |
|---|---|---|---|
| 1,1 | 0x88 | 4,1 | 0x86 |
| 1,2 | 0x18 | 4,2 | 0x16 |
| 1,3 | 0x98 | 4,3 | 0x96 |
| 1,4 | 0x68 | 4,4 | 0x66 |
| 1,5 | 0xE8 | 4,5 | 0xE6 |
| 1,6 | 0x78 | 4,6 | 0x76 |
| 2,1 | 0x81 | 5,1 | 0x8E |
| 2,2 | 0x11 | 5,2 | 0x1E |
| 2,3 | 0x91 | 5,3 | 0x9E |
| 2,4 | 0x61 | 5,4 | 0x6E |
| 2,5 | 0xE1 | 5,5 | 0xEE |
| 2,6 | 0x71 | 5,6 | 0x7E |
| 3,1 | 0x89 | 6,1 | 0x87 |
| 3,2 | 0x19 | 6,2 | 0x17 |
| 3,3 | 0x99 | 6,3 | 0x97 |
| 3,4 | 0x69 | 6,4 | 0x67 |
| 3,5 | 0xE9 | 6,5 | 0xE7 |
| 3,6 | 0x79 | 6,6 | 0x77 |
The modified program (program name LED6.C) is given in Figure 6.19. In this program array DICE contains the thirty-six possible dice values. The program enters an endless for loop, and inside this loop the state of the push-button switch is checked. Also, a variable is incremented from 1 to 36. When the button is pressed, the value of this variable is used as an index to array DICE to determine the bit pattern to be sent to PORTC. As before, the program displays the dice numbers for 3 seconds and then turns OFF all LEDs to indicate that it is ready.
/*****************************************************************************
TWO DICE - USING FEWER I/O PINS
=============================