This guide is a follow up on my previous post of enabling the Raspberry Camera on the RPi 4. The rest of the guide assumes that you have logged on the RPi through ssh and that you have enabled the use of virtual environments. The Motor HAT that I have is from Adafruit.

This is the plan of attack:
- Enable i2c
- Install motor HAT driver and dependencies
- Test
Step 1. Enable i2c
By default the user has no access to the i2c device. We need to change that. Firstly check that i2c is working properly.
$ sudo apt install i2c-tools
$ sudo i2cdetect -y 1
You should see an output similiar to the following
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: 60 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: 70 -- -- -- -- -- -- --
Great. Now we need to check out who has access to /dev/i2c-1 and update our privileges as necessary.
$ ls /dev/i2c-1
should show that it belongs to the i2c
group which can read and write it. Check whether you’re a member of the i2c
group by typing $ groups ubuntu
. If not then add ubuntu to the i2c
group by typing $ sudo usermod -aG i2c ubuntu
. You may have to log off and log back in for this change to take effect.
Step 2. Install motor HAT driver and dependencies
From here I’ve closely followed the instructions by the motor HAT provider, in my case Adafruit.
$ sudo apt-get install python3-dev
ONLY FOR 64bit $ sudo apt install gcc-aarch64-linux-gnu
As for the following we’ll be using pip, activate the virtual environment by typing $ src_testenv
(see here Step 3. Enable virtual environment and check dependencies about how I set that command up).
(testenv) $ pip3 install RPi.GPIO
(testenv) $ pip3 install adafruit-circuitpython-motorkit
Create a python file to test $ nano ~/environments/testenv/sandbox/motortest.py
. In the script add the following (taken from this Adafruit MotorHAT page):
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""Simple test for using adafruit_motorkit with a DC motor"""
import time
import board
from adafruit_motorkit import MotorKit
kit = MotorKit(i2c=board.I2C())
kit.motor1.throttle = 1.0
time.sleep(0.5)
kit.motor1.throttle = 0
Step 3. Test
Test the script by running (assuming you are in the same folder the motortest.py file is in) (testenv) $ python3 motortest.py
. If everything went well you should see the first motor rotate.