Use Sensors from Python

There is a large range of sensors that work with the Build HAT.

Work with Sensors

Connect a Colour sensor to port B on the Build HAT, and a Force sensor to port C.

If you’re not intending to drive a motor, then you don’t need an external power supply and you can use a standard USB power supply for your Raspberry Pi.

Create another new program:

from signal import pause
from buildhat import ForceSensor, ColorSensor

button = ForceSensor('C')
cs = ColorSensor('B')

def handle_pressed(force):
    cs.on()
    print(cs.get_color())

def handle_released(force):
    cs.off()

button.when_pressed = handle_pressed
button.when_released = handle_released
pause()

Run it and hold a coloured object (LEGO® elements are ideal) in front of the colour sensor and press the Force sensor plunger. The sensor’s LED switches on and the Thonny REPL displays the name of the closest colour.