Книга: Advanced PIC Microcontroller Projects in C

Using a Pseudorandom Number Generator

Using a Pseudorandom Number Generator

In the preceding project the value of variable J changes very fast among the numbers between 1 and 6, so we can say that the numbers generated are random (i.e., new numbers do not depend on the previous numbers).

A pseudorandom number generator function can also be used to generate the dice numbers. The modified program listing is shown in Figure 6.11. In this program a function called Number generates the dice numbers. The function receives the upper limit of the numbers to be generated (6 in this example) and also a seed value which defines the number set to be generated. In this example, the seed is set to 1. Every time the function is called, a number between 1 and 6 is generated.

/*********************************************************************
                            SIMPLE DICE
                            ===========
In this project 7 LEDs are connected to PORTC of a PIC18F452 microcontroller
and the microcontroller is operated from a 4MHz resonator. The LEDs are
organized as the faces of a real dice. When a push-button switch connected
to RB0 is pressed a dice pattern is displayed on the LEDs. The display
remains in this state for 3 seconds and after this period the LEDs all turn
OFF to indicate that the system is ready for the button to be pressed again.
In this program a pseudorandom number generator function is
used to generate the dice numbers between 1 and 6.
Author: Dogan Ibrahim
Date:   July 2007
File:   LED3.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,Pattern,Seed = 1;
 unsigned char DICE[] = {0,0x08,0x22,0x2A,0x55,0x5D,0x77};
 TRISC = 0;             // PORTC 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 a number between 1 and 6
   Pattern = DICE[J];   // Get LED pattern
   PORTC = Pattern;     // Turn on LEDs
   Delay_ms(3000);      // Delay 3 second
   PORTC = 0;           // Turn OFF all LEDs
  }
 }
}


Figure 6.11: Dice program using a pseudorandom number generator

The operation of the program is basically same as in Figure 6.10. When the push-button switch is pressed, function Number is called to generate a new dice number between 1 and 6, and this number is used as an index in array DICE in order to find the bit pattern to be sent to the LEDs.

Оглавление книги


Генерация: 1.058. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз