If you are using one of the Fx series PLCs, TBASIC has RND() function to return a random number as a float.
If you are using an FMD or Nano-10 PLC, TBASIC doesn't have a random number function.
There are many published algorithms for generating random numbers that could be implemented in TBASIC.
I use a "pseudo random number generator" that is based on CRC algorithms. These generators will return an integer between 0 and 65,535. The sequence of values will repeat after 65,536 calls to the functions. It isn't 100% random, just "Pseudo random".
I will give you 2 different CRC based algorithms. Each of these algorithms, use the value in "C" and will replace "C" with a pseudo random value. I have used them both for purposes similar to what you described.
- This version implements a CRC using shift and XOR
' This generator is based on a common 16 bit CRC algorithm.
'
if C = 0
C = &Hffff ' Reseed CRC if output goes to 0
endif
IF C & &h8000
LSHIFT C,1
C = C ^ &H1021
ELSE
LSHIFT C,1
ENDIF
C = C & &Hffff ' Limit output to 16 bit integer
[/font][/color]
- This is another variation that uses TBASIC CRC16() function.
' Random number generator using the TBASIC CRC16 function
'
DM[1] = C & &hff : DM[2] = (C / 256) & &hff ' Copy the seed value from C to DM
C = CRC16(DM[1],2) ' Compute next pseudo random number in C
[/font][/color]
[/list]
Gary D*ickinson