Raspberry PI Robot HAT (by SunFounder): Control Sensors and Motors for DIY Robots

4.8
(4)

Last Updated on 27th January 2024 by peppe8o

This post will show you how to use the Raspberry PI Robot HAT by SunFounder.

This board allows you to simplify how your Raspberry PI computer board controls your DIY robot project, by adding a layer able to control sensors and motors.

raspberry-pi-robot-hat-sunfounder

The SunFounder uses it, for example, in their PiDog, a Raspberry PI Robot Dog.

Please note that, at the date of this post, the Raspberry PI Robot HAT by SunFounder doesn’t support Raspberry PI OS Bookworm. So, also the Raspberry PI 5 is not supported. Considering that robot projects don’t require so much computing power, you can use it with an older Raspberry PI computer board, up to RPI 4 model B.

About the SunFounder Robot HAT for Raspberry PI

Robot HAT Specs

The SunFounder robot HAT comes in a package including a battery module, made of 2x 18650 batteries, standoffs and 2 cables for DC motors. There are also spare standoffs so that, if you lose or break one of them, you don’t need to be worried about ordering again a tiny plastic part. The main features of the robot HAT follows in the list below:

  • Power Input: USB Type-C, 5V/2A
  • Charging Power: 5V/2A 10W
  • Output Power: 5V/3A
  • Included Batteries: 2 x 3.7V 18650 Lithium-ion Batteries, XH2.0 3P Interface
  • Battery Protection: Reverse polarity protection
  • Charging Protection: Input undervoltage protection, input overvoltage protection, charging balance, overheat protection
  • Onboard Charging / Power Indicators
  • Onboard Battery Level Indicators
  • Motor Driver: 5V/1.8A x 2
  • 4-channel 12-bit ADC
  • 12-channel PWM
  • 4-channel digital signals
  • Onboard SPI interface, UART interface, I2C interface
  • Mono Speaker: 8Ω1W
raspberry-pi-robot-hat-internal-parts
ref. https://docs.sunfounder.com/projects/robot-hat-v4/en/latest/hardware_introduction.html

Moreover, please find below the main electrical values:

Parameters:Minimum ValueTypical ValueMaximum ValueUnit
Input Voltage:4.2558.4V
Battery Input Voltage:6.07.48.4V
Overcharge Protection (Battery):8.3V
Input Undervoltage Protection:4.154.254.35V
Input Overvoltage Protection:8.38.48.5V
Charging Current (5V):2.0A
Output Current (5V):3.0A
Output Voltage:5.1665.2465.327V
Charging Overheat Protection:125135145°C
DC-DC Overheat Protection:707580°C
Motor Output Current:1.8A
ref. https://docs.sunfounder.com/projects/robot-hat-v4/en/latest/features.html

Robot HAT Ports

The robot HAT has its own PINs to connect external devices via PWM, Analogic, Digital, and serial ports, besides 2 ports specifically designed for. It also includes power ports to input current both from the battery pack and from an external power source.

Power Ports

You can use the USB-C port to connect an external power source. In this way, your robot HAT will take power from the external source and recharge the battery pack. The device also includes electronics to keep safe the current coming from the external source and avoid problems while charging the battery:

robot-hat-power-ports

The switch near the battery pack port will allow you to enable the Robot HAT and power the Raspberry PI, without the need to use a second power supply to power the computer board.

Digital PINs

There are 4 digital PINs in the Robot HAT:

robot-hat-digital-pins

These PINs are mapped directly to 4 Raspberry PI PINs, according to the following table:

Robot Hat V4Raspberry Pi
D0GPIO17
D1GPIO4
D2GPIO27
D3GPIO22

So, you can manage these PINs as you would do without the HAT, keeping in consideration the matching table above.

Analog PINs

The missing of analog PINs has been a great limitation for all of the Raspberry PI computer boards over the years. The robot HAT allows you to get 4 analog PINs (from channel 0 to channel 3), controlled by the on-board AT32F415CBT7 microcontroller from Artery. They provide a 12-bit precision (from 0 to 4095) which samples the 3.3V operating range. Tip of this board, the charge level of the battery pack can be measured with a “hidden” analogic channel 4.

robot-hat-analog-pins

PWM PINs

Robots usually make large use of servo motors (like the SG90) or DC motors whose speed can be controlled via Pulse Witdh Modulation signals. The robot HAT takes care of this need by providing 12x PWM PINs:

robot-hat-pwm-pins

I2C PINs

There are 2x I2C interfaces. The first one comes with classic wiring PINs (4-PINs) and the other one comes with an SH1.0 interface. The second one is useful for devices coming with QWIIC and STEMMA QT connectors.

Both of them are connected to the Raspberry PI GPIO2 (SDA) and GPIO3 (SCL).

robot-hat-i2c-pins

SPI PINs

Also, SPI PINs are provided by the robot HAT, with a 7-PIN interface:

robot-hat-spi-pins

The PIN mapping table follows:

Robot Hat V4Raspberry Pi
BSYGPIO6
CSCE0(GPIO8)
SCKSCLK(GPIO11)
MIMISO(GPIO9)
MOMOSI(GPIO10)
3V33.3V Power
GNDGround

UART PINs

The same method is for the UART interface (4-pin), even if the UART connection is becoming less used compared to the other ports.

robot-hat-uart-pins

It connects to the Raspberry Pi’s GPIO14 (TXD) and GPIO15 (RXD) pins.

Motor Ports

With the Raspberry PI Robot HAT, there are 2 ports which are explicitly deputed to manage motors:

robot-hat-motor-ports

The speed and direction of motors can be managed by using 2 Raspberry PI GPIO PINs (for the direction) and 2 “hidden” PWM channels from the Robot HAT:

MotorIO
Motor1 DirGPIO23
Motor1 PowerPWM13
Motor2 DirGPIO24
Motor2 PowerPWM12

However, the SunFounder Python libraries will make the use of the motors simpler.

Robot HAT Buttons

There are 2 buttons available from the top of the board. The USR button can be customized according to your needs, while the RST button is available for customization only when not using the SunFounder Ezblock app:

robot-hat-buttons

There is also an LED near the USR button. You can manage it from the Raspberry PI GPIO26. The table of button mapping follows:

Robot Hat V4Raspberry PI
LEDGPIO26
USRGPIO25
RSTGPIO16

Robot HAT Speaker

Finally, there is also a 2030 audio chamber speaker in the backplane of the board:

robot-hat-speaker

This can produce audio outputs via an I2S connection using the following PINs:

I2SRaspberry Pi
LRCLKGPIO19
BCLKGPIO18
SDATAGPIO21

Robot HAT PIN mapping

The following table summarizes the mapping between the Raspberry PI and Robot HAT PINs:

 Robot Hat V4Raspberry PIRobot Hat V4Raspberry PI
NC3V35V5V
SDASDA5V5V
SCLSCLGNDGND
D1GPIO4TXDTXD
GNDGNDRXDRXD
D0GPIO17I2S BCLKGPIO18
D2GPIO27GNDGND
D3GPIO22MOTOR 1 DIRGPIO23
NC3V3MOTOR 2 DIRGPIO24
SPI MOSIMOSIGNDGND
SPI MISOMISOUSR BUTTONGPIO25
SPI SCLKSCLKSPI CE0CE0
GNDGNDNCCE1
NCID_SDNCID_SC
MCU ResetGPIO5GNDGND
(SPI)BSYGPIO6Board Identifier 2GPIO12
Board Identifier 1GPIO13GNDGND
I2S LRCLKGPIO19RST BUTTONGPIO16
USER LEDGPIO26NCGPIO20
GNDGNDI2S SDATAGPIO21

Mounting the Raspberry PI Robot HAT

The Robot HAT board matches the Raspberry PI computer board heading to be placed directly on top of it. So, you don’t have to use cabling and check complicated pinout mapping to connect the robot HAT: its female heading under the board will perfectly match your Raspberry PI computer board heading (only for Raspberry PI models with 40-pin heading, which means all the Raspberry PI models from 2 onward).

raspberry-pi-robot-hat-sunfounder-heading

There’s no risk of mounting it on the wrong side, once you see the board mounted as in the following picture:

raspberry-pi-robot-hat-sunfounder-mounted

As you can see, it is highly compact and easy to manage. The board also comes with standoffs (not shown in the previous picture), so it will be fixed when connecting cables from your sensors and motors.

What We Need

To use the Robot HAT, we need a few pieces:

Raspberry PI 4 model B 8GB

Test the Robot HAT

For my tests, I’m going to use a Raspberry PI 3 model A+. I love this board because it’s a great compromise between the computing power of a Raspberry PI model B, the low power consumption of a Raspberry PI Zero W, and the price near to the RPI Zero W one! Moreover, it fits greatly with the robot HAT:

robot-hat-raspberry-pi-3-model-a

Anyway, the following test will work also with the newer Raspberry PI computer boards.

Prepare the Operating System

Start preparing your Operating System. You can install the fast Raspberry PI OS Lite (without a Desktop environment, but faster) or opt for Raspberry PI OS Desktop, using its internal terminal. You can find the differences in my Raspberry PI OS Lite vs Desktop: comparison between the 2 distributions.

IMPORTANT NOTE: as already mentioned, at the date of this post the SunFounder Robot HAT is supported only with Debian Bullseye. So, you must use the “Legacy” Bullseye OS. I also suggest the 64-bit version.

Make sure your OS is up to date with the following commands:

sudo apt update -y && sudo apt upgrade -y

We also need to install some required packages:

sudo apt install git python3-setuptools python3-smbus python3-pip -y

Finally, we can download the SunFounedr robot HAT libraries and install them:

git clone https://github.com/sunfounder/robot-hat.git -b v2.0
cd robot-hat
sudo python3 setup.py install

I also suggest installing the gpiozero package (if not still installed), as it will help in some of the following tests and, generally, for your projects:

sudo apt install python3-gpiozero

The last installation step regards the i2s amplifier package, still coming inside the robot-hat folder:

sudo bash i2samp.sh

Testing the LED

In this test, we’ll make blinking the robot HAT on-board LED. We’ll control it directly from the Raspberry PI PINs, as the LED is connected to the GPIO26 as before explained.

Let’s create a new file from the Raspberry PI terminal:

nano led_test.py

Paste the following code, which will simply turn on and off the LED every 1 second:

from gpiozero import LED
from time import sleep

led = LED(26)

try:
  while True:
    led.on()
    sleep(1)
    led.off()
    sleep(1)

except KeyboardInterrupt:
  led.off()
  print("Ending program")

Close and save (CTRL + X). Run the test with the following terminal command:

python3 led_test.py

The LED will start blinking. You can stop the test at any time, with the CTRL+D.

Testing an SG90 Servo Motor

SG90 servo motors usually come with a 3-wire connector bringing GND, VCC and signal. They work with a PWM signal and should perfectly fit the PWM connectors. In my test, I will connect my PWM 0 channel:

robot-hat-raspberry-pi-3-model-a-sg90-servo

Let’s create a new test file. From terminal:

nano sg90test.py

Paste the following code. As you can see below, the code is really simple as, after initializing the servo ports, you can control a specific servo motor angle with the command “servos[<<ch_number>>].angle()”:

from robot_hat import Servo
import time

# Create objects for 12 servos
servos = [Servo(f"P{i}") for i in range(12)]

def initialize_servos():
    """Set initial angle of all servos to 0."""
    for servo in servos:
        servo.angle(-90)
        time.sleep(0.1)  # Wait for servos to reach the initial position
    time.sleep(1)

# Initialize servos to their initial position
initialize_servos()

# Control servos
servos[0].angle(0)
time.sleep(0.5)
servos[0].angle(90)
time.sleep(0.5)
servos[0].angle(-90)
time.sleep(0.5)

Save and close this file (CTRL+X). You can run it with the following command:

python3 sg90test.py

It will initialize the servo motor to the -90 angle. Then it will move into 3 different positions with a pause of 0.5 seconds between each move.

Testing the Speaker

The Speaker test can be the funniest for kids. The SunFounder library comes with a text-to-speech function which enables you to let your robot speak. Please create a robot_tts.py file:

nano robot_tts.py

Paste the following code. You can see there that, after initializing the tts language (en-US in the test), you can directly pass your sentence to the tts.say() method. Moreover, this test will close by printing all the supported languages:

import sys
from robot_hat import TTS

# Check if there are enough command line arguments
if len(sys.argv) > 1:
    text_to_say = sys.argv[1]  # Get the first argument passed from the command line
else:
    text_to_say = "Hello peppe8o"  # Default text if no arguments are provided

# Initialize the TTS class
tts = TTS(lang='en-US')

# Read the text
tts.say(text_to_say)

# Display all supported languages
print(tts.supported_lang())

Close and save.

When running this test, you can pass the sentence via the terminal command, inside brackets:

python3 robot_tts.py "hello!"

If nothing is specified, it will produce the default test available in the code. As said, the test will end also showing the supported languages:

pi@raspberrypi:~ $ python3 robot_tts.py "hello!"
['en-US', 'en-GB', 'de-DE', 'es-ES', 'fr-FR', 'it-IT']

SunFounder Robot HAT Docs

The full documentation about the robot HAT is available at the SunFounder official docs page.

What’s Next

Interested in more cool ways to use your Raspberry PI computer board? Take a look at peppe8o Raspberry PI computer tutorials!

Enjoy!

How useful was this post?

Click on a star to rate it anonymously!

Average rating 4.8 / 5. Vote count: 4

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?