In the last lesson, you learned to use the Hummingbird light sensor. You will learn to use the distance sensor in this lesson. Any sensor can be connected to any of the three “SENSORS” ports on the Hummingbird Bit. Connect the distance sensor to port 1 and a tri-color LED to port 1.
Lesson 8 – Distance Sensor
1 Tri-Color LED, 1 Distance Sensor, 1 Position Servo, 1 Light Sensor
Use the getDistance() method to find the value of the distance sensor; it requires one parameter, the port to which the sensor is connected (1-3). The getDistance() method returns the distance to the closest object in centimeters. The range of the Hummingbird distance sensors is approximately 2-200 cm. The distance sensor cannot measure an object that is pressed directly against it; make sure the object is at least 1 cm away.
Write a program that prints “FAR” on the screen of the micro:bit if you are more than 30 cm from the distance sensor. Otherwise, it should print “NEAR” on the micro:bit.
You can also use a sensor to control a loop in Python. The for loop that you have already used repeats the statements inside it a specific number of times. A while loop, on the other hand, repeats the statements inside it as long as a Boolean expression is true. For example, this code will make a tri-color LED red for as long as the value of the distance sensor is less than the threshold. The keyword while is followed by a Boolean expression, bird.getDistance(1) < threshold. If this expression is true, the program runs the statement inside the loop and turns the tri-color LED red. Then it checks the Boolean expression again. If it is still true, the program turns the tri-color LED red again, so you will see it stay red. The loop continues repeating the statement inside it until it checks the Boolean expression and finds that it is false. Then the program skips the indented statement inside the loop and moves on to the next unindented line of code. In this case, the program turns the tri-color LED green.
Write a program to make the tri-color LED green as long as you are far from the distance sensor. When you move close to the sensor, the tri-color LED should turn red and the Bit should buzz.
Write a program to make position servo move back and forth as long as you are close to the distance sensor.
Try building a rover and using the distance sensor to program it to avoid obstacles! Note that the two rotation servos on the rover point in opposite directions. This means that to move the rover forward, the two servos must move in opposite directions.