Please have look at my code below and tell what is wrong.
Code description - An infinite loop which turns a 180 degree servo all the way to the left, and then back 180 degrees all the way to the right. Left to right, forever, but with some additional randomization. What I want it to do is turn at a 'random' speed (from a list of 5) for each new loop of my while-loop - the sleep(delay) controls this - but what actually happens is that the random function gets called only once at the start, and that same value gets used over and over again. Is it possible, in micropython, to re-trigger a randomization from within a while-loop so that my servo changes speed while the loop is running? If not then how do I go about achieving this.
Thanks.
Code: Select all
from microbit import *
import random
pin0.set_analog_period(10)
step_delay_times = [5, 20, 40, 60, 80]
x = random.choice(step_delay_times)
while True:
for position in range(50, 250, 1):
pin0.write_analog(position)
sleep(x) # time in milliseconds between each 1 degree step
sleep(500) # a half-second pause between direction changes
for position in range(250, 50, -1):
pin0.write_analog(position)
sleep(x) # time in milliseconds between each 1 degree step
sleep(500) # a half-second pause between direction changes