from random import randint
import array
from uctypes import addressof
from micropython import const
from time import ticks_us, ticks_diff
from sys import exit

trees=array.array('I',(0,0,0,0,0,0,0,0,0,0))
control=array.array('i',(1,240,addressof(trees)))

SEED      = const(0)
RAND_MAX  = const(4) # maximum random number generated
RAND_BITS = const(8) # number of bits in first pass 

@micropython.asm_thumb
def rand_asm(r0):        
  label(RANDOM)          # uses r1-r5, output r2
  ldr(r1,[r0,SEED])      # seed
  ldr(r4,[r0,RAND_MAX])  # r4 = max random number
  mov(r5,33)              
  mov(r2,r4)
  label(HIGHBITS)        # counts bits required 
  sub(r5,r5,1)          
  lsl(r2,r2,1)
  bcc(HIGHBITS)          # r5 = max bits
  label(RANDOM_LOOP)
  add(r1,13)            # scramble seed
  mov(r2,r1)            #
  mov(r3,9)
  ror(r2,r3)
  eor(r1,r2)            # end scramble
  mov(r2,r1)            # r2 = random 32 bit number
  mov(r3,32)
  sub(r3,r3,r5)
  asr(r2,r3)            # scale down to max random
  mov(r3,1)
  sub(r5,1)
  lsl(r3,r5)            # shift 17 bits to get offse
  add(r2,r2,r3)         # add offset for positive
  #bmi(RANDOM_LOOP)     # sometimes get negative?
  cmp(r2,r4)            # get another if too high
  bgt(RANDOM_LOOP)
  label(EXIT)
  str(r1,[r0,0])
  mov(r0,r2)
  label(BYPASS)

t=ticks_us()
#r=randint(0,70000)
r=rand_asm(control)
diff=ticks_diff(ticks_us(),t)
print(r,diff)

#print(rand_asm(control))
#exit()

mx=0
mn=9999
for i in range(20):

  rand=rand_asm(control)
  if rand>mx:
    mx=rand
  if rand<mn:
    mn=rand
  print(rand)
print(mn,mx)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT