Use Motors from Python
There are a number of motors that work with the Build HAT.
Connect a Motor
Connect a motor to port A on the Build HAT. The LPF2 connectors need to be inserted the correct way up. If the connector doesn’t slide in easily, rotate by 180 degrees and try again.
Work with Motors
Start the Thonny IDE. Add the program code below:
from buildhat import Motor
motor_a = Motor('A')
motor_a.run_for_seconds(5)
Run the program by clicking the play/run button. If this is the first time you’re running a Build HAT program since the Raspberry Pi has booted, there is a few seconds pause while the firmware is copied across to the board. The red LED extinguishes and the green LED illuminates. Subsequent executions of a Python program don’t require this pause.
Your motor turns clockwise for 5 seconds.
Change the final line of your program and re-run.
motor_a.run_for_seconds(5, speed=50)
The motor now turns faster. Make another change:
motor_a.run_for_seconds(5, speed=-50)
The motor turns in the opposite (anti-clockwise) direction
Create a new program by clicking on the plus button in Thonny. Add the code below:
from buildhat import Motor
motor_a = Motor('A')
while True:
print("Position: ", motor_a.get_aposition())
Run the program. Grab the motor and turn the shaft. The numbers printed in the Thonny REPL change.