[Tutor] A question about None
Dennis Lee Bieber
wlfraed at ix.netcom.com
Sun Aug 22 13:46:33 EDT 2021
On Sun, 22 Aug 2021 17:25:10 +1000, Phil <phillor9 at gmail.com> declaimed the
following:
>The distance sensor outputs "None" if the distance is greater than can
>be measured and "None", of course cannot be compared. So I came up with
>the following which is not quite correct:
>
>while True
> if distance_sensor.get_distance_cm() is not None:
> if distance_sensor.get_distance_cm() > 20:
Note that you have a race condition... Between the test for None and
the test for >20 you have TWO "reads" of distance -- the distance could
have changed enough between those reads that the second could return None!
> motor_pair.set_default_speed(20)
> motor_pair.start()
> else:
> continue
>
> elif distance_sensor.get_distance_cm() is not None:
You will only get here is the first read returns None! And the continue
statements are unneeded.
> if distance_sensor.get_distance_cm() < 20:
> motor_pair.set_default_speed(-20)
> motor_pair.start()
> else:
> continue
>
You perform FOUR reads of distance for a loop that should only require
ONE read. Also, what happens if distance is exactly "20".
>The idea is that if "None" returned from the sensor then nothing will
>happen and the loop will continue until "None" is not returned. Can
>anyone see the error of my ways?
Uhm... "lots" <G>
Consider...
speed = 0
While True:
speed_change = True
distance = distance_sensor.get_distance_cm()
if distance is not None: #assumes distance of 0 is a valid result
#otherwise, just use
# if distance:
if distance >= 20 and speed <> 20:
speed = 20
elif distance < 20 and speed <> -20:
speed = -20
else:
speed_change = False
if speed_change:
#no sense setting speed and starting motors if they
#are already configured
#NOTE: should there be a motor_pair.stop() before
#reversing speed value?
motor_pair.set_default_speed(speed)
motor_pair.start()
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/
More information about the Tutor
mailing list