How the Receiver Works
The radio_tilt_bot_fb_lr_with_stop_range script is just another development step from the previous activity. Here are the changes that were made to radio_tilt_bot_fb_with_stop_range to add the left/right control.
Remember how the script sets fb to y /10 to reduce the range of values from -1024…1024 to -102 to 102? Well, since the x-axis measurements also come in a range of -1024 to 1024, the script can also divide those by 10. That’s what lr = x / 10 does, and lr is shorthand for left/right.
fb = y / 10 lr = x / 10 # <- added if abs(fb) > 8: display.show(Image.ALL_CLOCKS[needle]) vL = fb vR = -fb
After setting up vL and Vr with fb and -fb, the lr component can be added in to cause turns. The statement if(fb < 0): lr = -lr changes the sign of the lr variable if you are tipping the tilt transmitter toward you. That’s because the rules for wheel rotation directions for turning reverse when the robot is backing up.
if(fb < 0): lr = -lr # <- added vL = vL - lr # <- added vR = vR - lr # <- added
Let’s try an exercise called variable tracing. Variable tracing is the process of stepping through each line after setting variable values and checking what each statement does with those values. Some software development environments offer an automated version of this, but here, it is a mental exercise to help better understand how the statements correctly control the wheel speeds. The variable values are calculated in comments to the right of the statements.
Example: Tilt the micro:bit away from you and to the left.
Assume the y variable is 400, and the x variable is 200.
x = dictionary.get('x') # x = 400 y = dictionary.get('y') # y = 200 fb = y / 10 # fb = 400 / 10 = 40 lr = x / 10 # lr = 200 / 10 = 20 if abs(fb) > 8: # absolute value fb is greater than 8 vL = fb # vL = 40 vR = -fb # vR = -40 if(fb < 0): lr = -lr # fb is positive so lr stays at 20 vL = vL - lr # vL = 40 – 20 = 20 vR = vR - lr # vR = -40 – 20 = -60 bot(18).servo_speed(vL)# vL = 20 left wheel forward slowly bot(19).servo_speed(vR)# vR = -60 right wheel forward faster # result: cyber:bot rolls forward and to the left.
Example: Tilt the micro:bit toward you and to the right.
Assume the y variable is -400, and the x variable is -200.
x = dictionary.get('x') # x = -400 y = dictionary.get('y') # y = -200 fb = y / 10 # fb = -400 / 10 = -40 lr = x / 10 # lr = -200 / 10 = -20 if abs(fb) > 8: # absolute value fb is greater than 8 vL = fb # vL = -40 vR = -fb # vR = 40 if(fb < 0): lr = -lr # fb is negative so lr set to +20 vL = vL - lr # vL = -40 – 20 = -60 vR = vR - lr # vR = 40 – 20 = 20 bot(18).servo_speed(vL)# vL = -60 left wheel backward faster bot(19).servo_speed(vR)# vR = 20 right wheel backward slower # result: cyber:bot rolls backward and to the right.