Swordfish Module - RandGen2 (longword var)


The module implements a simple modulo-based PSEUDO Random Number Generator for Swordfish Basic, though should not be confused with the other User Module "RandGen.bas".

DiskIcon Download: RandGen2.bas

This RandGen2 Module uses LongWord variables instead of the Byte variables on the old RandGen module. The module uses RndMax property which can be set in the Initialize subroutine. By doing so, the interval in which generated values are constrained (normalized). By default, RandMax is set to 255 (max value for a byte).

Furthermore, it uses two magic constants that makes generated values really fine (seems truly random).

If you really need a nice number generator for PIC, use this one (and keep RandMax limited to 255 so that you can assign the result of Rand() function directly to any byte variable.

Example using this Code below would give you a random number between 0 - 5.


Example Code of Using the RandGen2 (Longword) Module with the Random module code above set to give us a number between 0 and 5.

// Device and Clock 
Device = 18F452                // Tell the compiler what chip we are using 
Clock = 20                     // Tell the compiler what we will be setting the clock to (Mhz)            
// LCD optional settings 
#option LCD_DATA = PORTC.4          // LCD setup data port (sets it to 4 data lines only)
#option LCD_RS = PORTE.0          
#option LCD_EN = PORTE.1
// Modules 
Include "LCD.bas"                   // include LCD module
Include "convert.bas"               // include convert to convert dec, binary to string etc.
Include "randgen2.bas" 
// Variable Declarations
Dim RandomVal As LongWord       // used to store the random number
Dim myvalue As Byte             // used to store random number seed
// Set Ports             
ADCON1 = $07        // Make all pins digital I/O's - check datasheet 
TRISA = %111111     // Make PORTA all inputs  
TRISB = %11111111   // Make PORTB all inputs 
TRISC = %00000000   // Make PORTC all outputs          
TRISD = %00000000   // Make PORTD all outputs 
TRISE = %000        // Make PORTE all outputs
// Delay for LCD and Ports setup
DelayMS(200)                  // Allow LCD to warm up  
LCD.Cls                       // Clear the LCD screen
// Initialize Variables  
myvalue = 2
RandGen2.Initialize (myvalue)        // Initialize the Random Number generator. 
RandGen2.SetRndMax(6)                // Set random MAX number
// Main Program 
While True                 
        RandomVal = RandGen2.rand ()   // Grab a random number
        LCD.WriteAt(1,1,"Rand Value = ",Convert.DecToStr(RandomVal,1))    // Send text to the LCD screen

Forum Activity

Member Access