Worksheet 5

Stopping when the sensor sees a line


This means letting a sensor control the motors.

We shall get the robot to move forward until it sees a line using its stop sensor. 
You can use the Button to start the robot moving.


1 Other software that you need:

Import the hardware pins, and the means of outputting and inputting analogue values.

    from machine import Pin, PWM, ADC


Use the UKMARS import to set up Motor objects

    from UKMARS_New import Motor


Set up two Motor objects that can set the motor speeds:

     L = Motor("L")
     R= Motor(“R”)


2 Next we need to be sure how to control the motors.
  • To set both going forwards at the same speed.
  • To stop both motors 
  • Use the .speed() motor method to output a voltage to the motor.

    L.speed(nnn)
    R.speed(mmm)

3 Then we need to be able to read the stop sensor. 

So we set up an object (stopsense)
Unlike a switch or a button, this doesn't just give a value of 0 or 1 for on or off.

You can get a reading of the voltage coming from the sensor.
    stopsense = ADC(Pin(28)) # side stop sensor

This uses the ADC(Pin) class to set up an analogue input that gives a number for the sensor voltage. 
ADC stands for Analogue to Digital Converor

4 Now check the numerical readings we get from the black baseboard 
use Thonny print() function to display the light values

See the reading we get from a white line

    light=stopsense.read_u16()
    print (light)

  • This uses .read_u16() to read the voltage, and display it on the Thonny screen 
  • Does it increase for white or black?
5 Now decide at what sensor reading we will take action
  • Choose a number that is half way between black and white.
6 Understand how loops work, and when they stop looping.

The following loops forever:
    while True:

The following loops until x  equals 7:
    while (x!=7):

The following loops until x  is greater than a certain amount
    while (x<156):

7 Make the loop stop when the sensor sees white.

(the numbers may be wrong below)

    stopsense = ADC(Pin(28)) # side stop sensor
    while (stopsense <30000):   #  # use the number you chose at step 5
          stopsense = ADC(Pin(28)) # side stop sensor

8 Start the motors, run the loop, stop the motors.


© Copyright St Albans Robots