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


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.


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
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:
Overcharge Protection (Battery):8.3V
Input Undervoltage Protection:
Input Overvoltage Protection:
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:


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:


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

Robot Hat V4Raspberry Pi

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.



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:



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).



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


The PIN mapping table follows:

Robot Hat V4Raspberry Pi
3V33.3V Power


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


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:


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:

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:


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

Robot HAT Speaker

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


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

I2SRaspberry Pi

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
(SPI)BSYGPIO6Board Identifier 2GPIO12
Board Identifier 1GPIO13GNDGND

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).


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


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:


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)

  while True:

except KeyboardInterrupt:
  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:


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:
        time.sleep(0.1)  # Wait for servos to reach the initial position

# Initialize servos to their initial position

# Control servos

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
    text_to_say = "Hello peppe8o"  # Default text if no arguments are provided

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

# Read the text

# Display all supported languages

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!


How useful was this post?

Click on a star to rate it anonymously!

Average rating 4.5 / 5. Vote count: 2

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?