Take a look at the image below. It illustrates how shade over one of the photoresistors affects the cyber:bot wheels' speeds.
Let's take a closer look. The navigation code is in an infinite while True loop. At the beginning of each loop, the familiar rc_time function takes a reading from each phototransistor circuit. The P8 circuit measurement is stored in at_left and the P6 circuit measurement is stored in qt_right.
from cyberbot import * while True: bot(8).write_digital(1) qt_left = bot(8).rc_time(1) bot(6).write_digital(1) qt_right = bot(6).rc_time(1)
Then, the values of qt_right and qt_left are used in an equation to get an integer value representing which side of the cyber:bot is in brighter light. The value is stored in the norm_diff_shade variable.
norm_diff_shade = (200 * qt_right) / (qt_right + qt_left + 1) - 100
Now take another look at the illustration above. Light is hitting the left photoresistor but shade is over the right one. If the light is hitting the left side, then we want to slow down the left servo down so the cyber:bot moves more towards the left. This was done with the following statement:
if norm_diff_shade > 0: left_speed = 75 - norm_diff_shade right_speed = -75
Since light is hitting the left side, the variable norm_diff_shade will be greater than 0, and the if statement will run. The variable right_speed will stay at -75 (full speed clockwise to go forward) while the variable left_speed will subtract the value of norm_diff_shade from 75. The brighter the light on the left side, the larger the value subtracted.
If it light were hitting the right side of the cyber:bot and instead norm_diff_shade was less than or equal to 0, the c else: condition code would execute instead. It works the same way, to slow down right_speed by subtracting norm_diff_shade, but keeps the variable left_speed at 75 (full speed counterclockwise to go forward).
else: left_speed = 75 right_speed = -75 - norm_diff_shade
Then, the following script uses the updated left_speed and right_speed values to control each servo's speed:
bot(18).servo_speed(left_speed) bot(19).servo_speed(right_speed)
These lines simply run the servos at the speeds from the if statement. And, that is all it takes!