Force Sensor¶
Pybrick Documentation
To explore all Pybricks’ features check the Pybricks documentaion. This can also be seen in the right-hand panel of the Pybricks IDE.
The force sensor is like a more complicated button. Not only can it detect if it has been pressed, it can also measure how hard it has been pressed, or, in other words, the force applied to it. The measuring element is the black ‘button’ on the front of the sensor.
To initialise the force sensor you must call the ForceSensor()
class and nominate it’s port. For example, with the robot you would use:
force_sensor = ForceSensor(Port.A)
Force Sensor Functions¶
Pybrick provides four functions to interact with the force sensor:
force()→ float: N
→ Measures the force (N) exerted on the sensor.distance()→ float: mm
→ Measures by how much (mm) the sensor button has moved.pressed(force=3)→ bool
→ Checks if the sensor button is pressed. Has a minimum force to be considered pressed.touched()→ bool
→ Checks if the sensor is touched. Detects slight movements of the button
Force Sensor Example¶
Check how to use each of these functions by using the following code.
Create a new file called
force_sensor.py
Type the code below into the file
Predict what you think will happen.
Run your code
1# force_sensor.py
2
3from pybricks.hubs import PrimeHub
4from pybricks.pupdevices import Motor, ColorSensor, UltrasonicSensor, ForceSensor
5from pybricks.parameters import Button, Color, Direction, Port, Side, Stop
6from pybricks.robotics import DriveBase
7from pybricks.tools import wait, StopWatch
8
9# --- SETUP
10hub = PrimeHub()
11force_sensor = ForceSensor(Port.F)
12
13# --- MAIN LOOP
14while True:
15 force_reading = round(force_sensor.force(), 1)
16 distance_reading = round(force_sensor.distance(), 1)
17 is_pressed = force_sensor.pressed(3)
18 is_touched = force_sensor.touched()
19
20 print(
21 "Force:", force_reading,
22 "\tDistance:", distance_reading,
23 "\tForce > 3:", is_pressed,
24 "\tTouched:", is_touched
25 )
Investigate
lines 3 - 7 → imports all the Pybricks command for use with your robot
line 10 → initialises the hub
line 11 → initialises the force sensor
line 14 → creates an infinite loop
line 15 → takes the force reading, rounds it to one decimal place and then stores it in
force_reading
line 16 → takes the distance reading, rounds it to one decimal place and then stores it in
distance_reading
line 17 → checks if the sensor is experiencing more than 3N of force and stores result in
is_pressed
line 18 → checks if the sensor has been touched and stores the result in
is_touched
lines 20 - 25 → prints the values that have been stored
this is actually one print statement split over multiple line to make it easier to read
Modify
what happens if you change the
pressed
threshold to11
?what happens if you change the
pressed
threshold to0
?