Learnearn.uk » Microbit Unit Home » Microbit Line Following Robot Code 2 Servos using A/B calibration

# Microbit Line Following Robot Code 2 Servos using A/B calibration

## Introduction

### Introduction

One of the problems with the simple version of the robot control code is that if the ambient light changes from one day to the next then the values for the high (when the LDR is over white) and low(when the LDR is over black) then you will have to change your program code to make it work with the new light values.

A simple solution to this is to create calibration code that allows you to set the high and low values when the program first starts.

This algorithm works by:

1. Put both sensors over a white area and then press the A button. This records the high value for the 0 and 1 pins
2. Put both sensors over the black and then press the B button. This records the low values.
3. Calculate the half-way point between the high and low values for each sensor and save them in a middle value variable
4. Start the main loop by calling the ‘Go’ function.
5. If Pin1 is less than pin1 middle value, turn left
6. Else if Pin0 is less than pin1 middle value, turn right
7. Else move forward.

## Python Code

### Python Code

```pin0high = 0
pin1high = 0
pin0low = 0
pin1low = 0
middle0 = 0
middle1 = 0

def on_button_pressed_a():
global pin0high, pin1high
input.on_button_pressed(Button.A, on_button_pressed_a)

def on_button_pressed_b():
global pin0low, pin1low, middle0, middle1
middle0 = (pin0high - pin0low) / 2 + pin0low
middle1 = (pin1high - pin1low) / 2 + pin1low
go()
input.on_button_pressed(Button.B, on_button_pressed_b)

def go():
while True: