# Adafruit BrainCraft HAT - Easy Machine Learning for Raspberry Pi

## Overview

![](https://cdn-learn.adafruit.com/assets/assets/000/094/756/medium800thumb/adafruit_products_4374.jpg?1600286352)

The idea behind the **Adafruit BrainCraft HAT** is that you’d be able to “craft brains” for Machine Learning on the EDGE, with Microcontrollers & Microcomputers. On ASK AN ENGINEER, our founder & engineer chatted with Pete Warden, the technical lead of the mobile, embedded TensorFlow Group on Google’s Brain team about what would be ideal for a board like this.

![](https://cdn-learn.adafruit.com/assets/assets/000/094/757/medium800/adafruit_products_4374_top_02_ORIG_2020_09_2.jpg?1600286374)

And here’s what we designed! The BrainCraft HAT has a 240×240 TFT IPS display for inference output, slots for a camera connector cable for imaging projects, a 5 way joystick and button for UI input, left and right microphones, stereo headphone out, a stereo 1 Watt speaker out, three RGB DotStar LEDs, two 3 pin STEMMA connectors on PWM pins so they can drive NeoPixels or servos, and Grove/STEMMA/Qwiic I2C port. This will let people build a wide range of audio/video AI projects while also allowing easy plug-in of sensors and robotics!

![](https://cdn-learn.adafruit.com/assets/assets/000/094/758/medium800/adafruit_products_4374_quarter_ORIG_2020_09.jpg?1600286399)

A controllable mini fan attaches to the bottom, and can be used to keep your Pi cool while doing intense AI inference calculations. **Most importantly, there’s an On/Off switch that will completely disable the audio codec, so that when it's off, there’s no way it's listening to you.**

![](https://cdn-learn.adafruit.com/assets/assets/000/094/754/medium800/adafruit_products_4374_kit_ORIG_2020_09.jpg?1600286340)

 **Features:**

- **1.54" IPS TFT** display with 240x240 resolution that can show text or video
- **Stereo speaker ports for audio playback** - either text-to-speech, alerts or for creating a voice assistant.
- **Stereo headphone out** for audio playback through a stereo system, headphones, or powered speakers.
- **Stereo microphone input -** perfect for making your very own smart home assistants
- **Two 3-pin JST STEMMA connectors** that can be used to [connect more buttons](https://www.adafruit.com/product/4431), [a relay](https://www.adafruit.com/product/4409), or [even some NeoPixels!](https://www.adafruit.com/product/3919)
- [**STEMMA QT plug-and-play I2C por** t](https://learn.adafruit.com/introducing-adafruit-stemma-qt), can be used with [any of our 50+ I2C STEMMA QT boards](https://www.adafruit.com/category/620), or can be used to [connect to Grove I2C devices with an adapter cable](https://www.adafruit.com/product/4528).
- **5-Way Joystick + Button** for user interface and control.
- **Three RGB DotStar LEDs** for colorful LED feedback.

![](https://cdn-learn.adafruit.com/assets/assets/000/094/755/medium800/adafruit_products_4374_side_03_ORIG_2020_09.jpg?1600286351)

The STEMMA QT port means you can attach heat image sensors like the [Panasonic Grid-EYE](https://www.adafruit.com/product/3538) or [MLX90640](https://www.adafruit.com/?q=mlx90640&sort=BestMatch). Heat-Sensitive cameras can be used as a person detector, even in the dark! An external accelerometer can be attached for gesture or vibration sensing such as machinery/industrial predictive maintenance projects

# Adafruit BrainCraft HAT - Easy Machine Learning for Raspberry Pi

## Pinouts

![](https://cdn-learn.adafruit.com/assets/assets/000/096/494/medium800/adafruit_products_Braincraft_HAT_pinouts.jpg?1603823660)

![](https://cdn-learn.adafruit.com/assets/assets/000/096/495/medium800/adafruit_products_Braincraft_HAT_pinouts_back.jpg?1603823670)

![](https://cdn-learn.adafruit.com/assets/assets/000/096/496/medium800/adafruit_products_Braincraft_HAT_RasPi_pinouts_schematic.png?1603823680)

## Power

- **5.0V** - Connected to the display backlight
- **3.3V** - Connected to the display power and also the STEMMA QT / Qwiic connector
- **GND** - Ground for everything

## Display
The display is a 1.54" wide-angle TFT LCD.

- **MOSI, SCK, GPIO #25, CE0** - These are the display control pins. Note that MISO is not connected, even though it is an SPI pin, because you cannot read back from the display.
- **GPIO #26** - This is the display backlight pin. Used to turn on and off the backlight.

![adafruit_products_Braincraft_HAT_pinouts_display.jpg](https://cdn-learn.adafruit.com/assets/assets/000/096/522/medium640/adafruit_products_Braincraft_HAT_pinouts_display.jpg?1603831284)

## Buttons and Joystick
These pins have a 10K pullup to 3.3V so when the button is pressed or the joystick is moved/pressed, you will read a LOW voltage on these pins.

- **GPIO#17** - Button
- **GPIO #16** - Joystick select
- **GPIO #22** - Joystick left
- **GPIO #23** - Joystick up
- **GPIO #24** - Joystick right
- **GPIO #27** - Joystick down

![adafruit_products_Braincraft_HAT_pinouts_button_joystick.jpg](https://cdn-learn.adafruit.com/assets/assets/000/096/523/medium640/adafruit_products_Braincraft_HAT_pinouts_button_joystick.jpg?1603831369)

## Sound
- **GPIO #18, GPIO#19, GPIO #20, GPIO #21 -** I2S Digital Audio.
- **Speakers** - The two speaker connectors are located on the bottom in the middle, labeled Right and Left. [Plug in an enclosed speaker](https://www.adafruit.com/product/3351) or&nbsp; [use a JST 2PH cable to attach custom speakers](https://www.adafruit.com/product/261).
- **Microphones** - The two mics are in the middle of each side, labeled Left Mic and Right Mic.
- **Headphones** - A headphone jack is located on the bottom right. Use any headphones or Line-Out to another audio system.
- **On/Off Switch** - Located on the left, towards the top, switches audio on and off.

![adafruit_products_Braincraft_HAT_pinouts_sound.jpg](https://cdn-learn.adafruit.com/assets/assets/000/096/524/medium640/adafruit_products_Braincraft_HAT_pinouts_sound.jpg?1603831424)

## STEMMA QT Connector
- **SCL, SDA** - I2C data for the STEMMA QT / Qwiic connector. Not used by buttons or display. Can also [use with Grove sensors with an adapter cable](https://www.adafruit.com/product/4528). Great for quickly adding sensors or accessories with plug-and-play.

![adafruit_products_Braincraft_HAT_pinouts_STEMMA_QT.jpg](https://cdn-learn.adafruit.com/assets/assets/000/096/525/medium640/adafruit_products_Braincraft_HAT_pinouts_STEMMA_QT.jpg?1603831484)

## Digital/Analog Connectors
- **GPIO#12 and GPIO #13** - 3-pin JST digital or analog connectors. Easily connect things like [NeoPixels](https://www.adafruit.com/product/3919) or [servos](https://www.adafruit.com/product/4326) using this 2mm connector. [You can also use a generic JST cable to connect to a breadboard.](https://www.adafruit.com/product/3893)

![adafruit_products_Braincraft_HAT_pinouts_DAC.jpg](https://cdn-learn.adafruit.com/assets/assets/000/096/526/medium640/adafruit_products_Braincraft_HAT_pinouts_DAC.jpg?1603831685)

## DotStar LEDs
Three fully color RGB addressable LEDs can provide feedback or a light show. Uses DotStar protocol (not NeoPixel) so any microcomputer can easily control the lights.

- **GPIO #5** - DotStar LED data pin.
- **GPIO #6 -** Dotstar LED clock pin.

![adafruit_products_Dotstar_LEDs.jpg](https://cdn-learn.adafruit.com/assets/assets/000/126/960/medium640/adafruit_products_Dotstar_LEDs.jpg?1704828065)

## Fan
- **GPIO #4** - The fan is on this pin.

![adafruit_products_Braincraft_HAT_pinouts_fan.jpg](https://cdn-learn.adafruit.com/assets/assets/000/096/529/medium640/adafruit_products_Braincraft_HAT_pinouts_fan.jpg?1603832045)

# Adafruit BrainCraft HAT - Easy Machine Learning for Raspberry Pi

## Required Parts

Before you start, you'll need some parts to make your BrainCraft HAT run! At a minimum you will need

# Raspberry Pi Computer

**A working Raspberry Pi** (Pi 4+ needed for vision projects, any Pi for audio-only projects)

Featured
### Raspberry Pi 4 Model B - 2 GB RAM

[Raspberry Pi 4 Model B - 2 GB RAM](https://www.adafruit.com/product/4292)
The Raspberry Pi 4 Model B is the newest Raspberry Pi computer made, and the Pi Foundation knows you can always make a good thing _better_! And what could make the Pi 4...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4292)
[Related Guides to the Product](https://learn.adafruit.com/products/4292/guides)
![Angled Shot of the Raspberry Pi 4 Model B - 2 GB RAM](https://cdn-shop.adafruit.com/640x480/4292-13.jpg)

 **Power supply**

Featured
### 5V 2.5A Switching Power Supply with 20AWG MicroUSB Cable

[5V 2.5A Switching Power Supply with 20AWG MicroUSB Cable](https://www.adafruit.com/product/1995)
Our all-in-one 5V 2.5 Amp + MicroUSB cable power adapter is the perfect choice for powering single-board computers like Raspberry Pi, BeagleBone, or anything else that's power-hungry!

This adapter was specifically designed to provide 5.25V, not 5V, but we still call it a 5V USB...

In Stock
[Buy Now](https://www.adafruit.com/product/1995)
[Related Guides to the Product](https://learn.adafruit.com/products/1995/guides)
![MicroUSB power supply with bundled cable and U.S. plugs.](https://cdn-shop.adafruit.com/640x480/1995-02.jpg)

Featured
### Official Raspberry Pi Power Supply 5.1V 3A with USB C

[Official Raspberry Pi Power Supply 5.1V 3A with USB C](https://www.adafruit.com/product/4298)
The official Raspberry Pi USB-C power supply is here! And of course, we have 'em in classic Adafruit black! Superfast with just the right amount of cable length to get your Pi 4 projects up and running!

Best for use with Pi 4 series, [Pi...](https://www.adafruit.com/product/5814)

In Stock
[Buy Now](https://www.adafruit.com/product/4298)
[Related Guides to the Product](https://learn.adafruit.com/products/4298/guides)
![Angled shot of Official Raspberry Pi Power Supply 5.1V 3A with USB C with Power plug facing down. ](https://cdn-shop.adafruit.com/640x480/4298-04.jpg)

 **And an SD card.** It can be blank or come with software on it.

Featured
### SD/MicroSD Memory Card (8 GB SDHC)

[SD/MicroSD Memory Card (8 GB SDHC)](https://www.adafruit.com/product/1294)
Add mega-storage in a jiffy using this 8 GB class 4 micro-SD card. It comes with a SD adapter so you can use it with any of our shields or adapters. Preformatted to FAT so it works out of the box with our projects. Tested and works great with our <a...></a...>

Out of Stock
[Buy Now](https://www.adafruit.com/product/1294)
[Related Guides to the Product](https://learn.adafruit.com/products/1294/guides)
![Hand removing/installing micro SD card from SD adapter](https://cdn-shop.adafruit.com/640x480/1294-03.jpg)

# **For Vision projects**

you'll also want a Raspberry Pi camera, a long cable (optional) and camera case (optional)

Featured
### Raspberry Pi Camera Board v2 - 8 Megapixels

[Raspberry Pi Camera Board v2 - 8 Megapixels](https://www.adafruit.com/product/3099)
Snap, snap! The Camera v2 is the new official camera board released by the Raspberry Pi Foundation!

The **Raspberry Pi Camera Board v2** is a high quality 8 megapixel Sony IMX219 image sensor custom designed add-on board for Raspberry Pi, featuring a fixed focus lens....

Out of Stock
[Buy Now](https://www.adafruit.com/product/3099)
[Related Guides to the Product](https://learn.adafruit.com/products/3099/guides)
![Angled shot of Raspberry Pi Camera Board v2 - 8 Megapixels connected to a flex cable and a Raspberry Pi.](https://cdn-shop.adafruit.com/640x480/3099-02.jpg)

Featured
### Flex Cable for Raspberry Pi Camera or Display - 1 meter

[Flex Cable for Raspberry Pi Camera or Display - 1 meter](https://www.adafruit.com/product/2143)
This cable will let you swap out the stock 150mm long flex cable from a Raspberry Pi Camera (either 'classic' or 'NoIR' type) or Raspberry Pi Display for a different size. Works great, just carefully open the connector on the Pi and slip this one in.

This cable is 1 meter...

In Stock
[Buy Now](https://www.adafruit.com/product/2143)
[Related Guides to the Product](https://learn.adafruit.com/products/2143/guides)
![Angled shot of Flex Cable for Raspberry Pi Camera or Display - 1 meter](https://cdn-shop.adafruit.com/640x480/2143-02.jpg)

Featured
### Adafruit Raspberry Pi Camera Board Case with 1/4" Tripod Mount

[Adafruit Raspberry Pi Camera Board Case with 1/4" Tripod Mount](https://www.adafruit.com/product/3253)
This is a basic, classic **Adafruit Raspberry Pi Camera Board Enclosure** &nbsp;with a black base and a clear top.&nbsp;The case is as minimal as it gets, coming in just two pieces of polycarbonate that snap snugly together. This case will keep your&nbsp;Pi Camera safe and secure...

In Stock
[Buy Now](https://www.adafruit.com/product/3253)
[Related Guides to the Product](https://learn.adafruit.com/products/3253/guides)
![Angled shot of Raspberry Pi camera board case.](https://cdn-shop.adafruit.com/640x480/3253-00.jpg)

# For Audio Projects

You'll want at least a set of headphones or plug-in speakers! 8-ohm speakers work best, but 4-ohm also works.

Featured
### Cell-phone TRRS Headset - Earbud Headphones w/ Microphone

[Cell-phone TRRS Headset - Earbud Headphones w/ Microphone](https://www.adafruit.com/product/1966)
These earbud headphones are the perfect accessory for your FONA - they've been tested to work with our modules - but can be used with any iOS or Android device that uses a TRRS pinout.&nbsp; The buds themselves are&nbsp;16mm in diameter with a nice 40" long. &nbsp;They come with a...

In Stock
[Buy Now](https://www.adafruit.com/product/1966)
[Related Guides to the Product](https://learn.adafruit.com/products/1966/guides)
![Cell-phone TRRS Headset - Earbud Headphones with Microphone](https://cdn-shop.adafruit.com/640x480/1966-03.jpg)

Featured
### Mono Enclosed Speaker - 3W 4 Ohm

[Mono Enclosed Speaker - 3W 4 Ohm](https://www.adafruit.com/product/3351)
Listen up! This 2.8" x 1.2" speaker&nbsp;is&nbsp;a&nbsp;great addition to any audio project where you need 4 ohm impedance and 3W or less of power. We particularly like this&nbsp;speaker&nbsp;as it is&nbsp;small and enclosed for good audio volume and quality. It has a handy JST 2PH...

In Stock
[Buy Now](https://www.adafruit.com/product/3351)
[Related Guides to the Product](https://learn.adafruit.com/products/3351/guides)
![Enclosed Speaker with JST cable](https://cdn-shop.adafruit.com/640x480/3351-01.jpg)

# Adafruit BrainCraft HAT - Easy Machine Learning for Raspberry Pi

## Raspberry Pi Setup

OK now you have all your parts in order, it's time to get your Raspberry Pi computer set up with the HAT or Bonnet.

# Step 1 - Burn SD Card

[Use Etcher or the Raspberry Pi Imager](https://learn.adafruit.com/adafruit-raspberry-pi-lesson-1-preparing-and-sd-card-for-your-raspberry-pi) to burn the latest **Raspbian Lite to an SD card** (you can use full but we won't be using the desktop software and it takes up a bunch of room.

Primary: 

![](https://cdn-learn.adafruit.com/assets/assets/000/094/760/medium800/adafruit_products_image.png?1600287676)

Info: 

# Step 2 - Configure log-in access

You'll need to be able to log into your Pi, [either enable SSH access (and use and Ethernet cable)](https://learn.adafruit.com/adafruits-raspberry-pi-lesson-6-using-ssh), use a USB to serial cable, or connect a monitor and keyboard. Basically get it so you can log in.

[We have a quickstart guide here](https://learn.adafruit.com/raspberry-pi-computer-quick-start) and [here that you can follow](https://learn.adafruit.com/raspberry-pi-zero-creation/install-os-on-to-sd-card), or there's dozens of online guides. it is assumed by the next step you are able to log in and type commands in - **ideally from a desktop computer, so you can copy and paste in some of the very long commands**!

# Step 3 - Log in & Enable Internet

Once you've logged in, [enable WiFi (if you have built in WiFi) with&nbsp; **sudo raspi-config**](https://www.raspberrypi.org/documentation/configuration/wireless/wireless-cli.md) so you can ssh in.

Enable SSH as well if you haven't yet, also via **sudo raspi-config**

![](https://cdn-learn.adafruit.com/assets/assets/000/094/761/medium800/adafruit_products_image.png?1600288310)

![](https://cdn-learn.adafruit.com/assets/assets/000/094/762/medium800/adafruit_products_image.png?1600288323)

After you're done, reboot, and verify you can log into your Pi and that it has internet access by running `ping -c 3 raspberrypi.org` and seeing successful responses.

![](https://cdn-learn.adafruit.com/assets/assets/000/094/763/medium800/adafruit_products_image.png?1600288454)

# Step 4 - Update/Upgrade
Now that you are logged in, perform an update/update:

```terminal
sudo apt update
sudo apt-get -y upgrade
```

and

```terminal
sudo apt install --upgrade python3-setuptools
```

![](https://cdn-learn.adafruit.com/assets/assets/000/094/764/medium800/adafruit_products_image.png?1600288941)

# Step 5 -&nbsp;Setup Virtual Environment
If you are installing on the Bookworm version of Raspberry Pi OS or later, you will need to install your python modules in a virtual environment. You can find more information in the [Python Virtual Environment Usage on Raspberry Pi](https://learn.adafruit.com/python-virtual-environment-usage-on-raspberry-pi) guide. To Install and activate the virtual environment, use the following commands:

```terminal
sudo apt install python3.11-venv
python -m venv env --system-site-packages
```

To activate the virtual environment:

```terminal
source env/bin/activate
```

OK you've now got a nice, clean, connected, and up-to-date Pi!

# Adafruit BrainCraft HAT - Easy Machine Learning for Raspberry Pi

## Blinka Setup

Blinka is our CircuitPython library compatibility layer. It allows many of the libraries that were written for CircuitPython to run on CPython for Linux. To learn more about Blinka, you can check out our [CircuitPython Libraries on Linux and Raspberry Pi](https://learn.adafruit.com/circuitpython-on-raspberrypi-linux) guide.

We put together a script to easily make sure your Pi is correctly configured and install Blinka. It requires just a few commands to run. Most of it is installing the dependencies.

Warning: 

```terminal
cd ~
sudo pip3 install --upgrade adafruit-python-shell
wget https://raw.githubusercontent.com/adafruit/Raspberry-Pi-Installer-Scripts/master/raspi-blinka.py
sudo python3 raspi-blinka.py
```

When it asks you if you want to reboot, choose **yes**.

![](https://cdn-learn.adafruit.com/assets/assets/000/095/295/medium800/adafruit_products_blinka-install.png?1601588820)

Finally, once it reboots, there are just a couple CircuitPython libraries to install for the BrainCraft HAT or Voice Bonnet.

The DotStar library is for controlling the 3 on-board DotStar LEDs and the Motor library is for testing out the GPIO pins.

```terminal
pip3 install --upgrade adafruit-circuitpython-dotstar adafruit-circuitpython-motor adafruit-circuitpython-bmp280
```

![](https://cdn-learn.adafruit.com/assets/assets/000/095/415/medium800/adafruit_products_Additional_Library_Install.png?1602024659)

That's it for Blinka and CircuitPython libraries.

# Adafruit BrainCraft HAT - Easy Machine Learning for Raspberry Pi

## Audio Setup

Warning: 

# Install Voicecard software

Make sure you've got the BrainCraft HAT or Voice Bonnet installed, and I2C support installed as well!

When you run

```terminal
sudo i2cdetect -y 1
```

you should see an entry under **1A** , indicating the hardware sees the audio card. The number may also appear as UU if you already installed software

![](https://cdn-learn.adafruit.com/assets/assets/000/094/765/medium800/adafruit_products_image.png?1600291684)

```terminal
cd ~
sudo apt-get install -y git wget
git clone https://github.com/HinTak/seeed-voicecard
cd seeed-voicecard
git checkout v6.12
sudo ./install.sh
sudo reboot
```

At the end you should see something like this:

![](https://cdn-learn.adafruit.com/assets/assets/000/136/594/medium800/adafruit_products_Screenshot_2025-05-05_at_5.56.09%E2%80%AFPM.png?1746493045)

Reboot with

```terminal
sudo reboot
```

# Checking for the Card

On reboot run

```terminal
sudo aplay -l
```

To list all sound cards, you should see it at the bottom

![](https://cdn-learn.adafruit.com/assets/assets/000/129/315/medium800/adafruit_products_Screenshot_2024-04-10_at_9.21.31_AM.png?1712766241)

Info: On boards such as the Raspberry Pi Zero, 2 or 3, your card number may be Card 2 instead of 3 because it only has a single HDMI port. You'll need to make some changes to some of the commands to reflect this further down.

If your card number differs from the above image, take note of your number.

You can use `alsamixer` to adjust the volume, dont forget to select the card with **F6 or 's' key**

![](https://cdn-learn.adafruit.com/assets/assets/000/094/768/medium800/adafruit_products_image.png?1600292926)

A gain of about **60%** is plenty loud!

![](https://cdn-learn.adafruit.com/assets/assets/000/094/769/medium800/adafruit_products_image.png?1600292971)

# Headphone/Speaker Test

Make sure the **Audio On/Off switch is set to ON!**

With either headphones plugged into the headphone jack or a speaker attached to the speaker port, run

```terminal
speaker-test -c2
```

you will hear white noise coming out of the speakers/headphones! If you don't hear anything, you may need to change the `-c` parameter to match the card number of your device.

Warning: 

![](https://cdn-learn.adafruit.com/assets/assets/000/094/770/medium800/adafruit_products_image.png?1600293333)

# Microphone Test

There are two microphones, and now we can test that they work. **This test is best done with headphones** , not using the speaker port, because it can cause a painful feedback effect if the speakers are next to the mics!

Run:

```terminal
sudo arecord -f cd -Dhw:3 | aplay -Dhw:3
```

If your sound card ID is not #2, then replace the number in both of the `-Dhw:` parameters with your actual number.

Then either gently rub each microphone, or speak to hear yourself echoed!

![](https://cdn-learn.adafruit.com/assets/assets/000/094/771/medium800/adafruit_products_image.png?1600293343)

`Control-C` to quit when done

Your audio subsystem is now completely tested!

## Python Libraries

The Microphone and Voice Card are installed as Linux level devices, so using them in is done as you would with any system level audio device. If you would like to make use of audio in Python, you can use the PyAudio library. To install pyaudio and its dependencies, run the following code:

```terminal
sudo apt-get install libportaudio2 portaudio19-dev
sudo pip3 install pyaudio
```

## Python Usage

Here is a basic test script to enumerate the devices and record for 10 seconds. When prompted, choose the device called **seeed-2mic-voicecard**.

![](https://cdn-learn.adafruit.com/assets/assets/000/106/700/medium800/adafruit_products_Screen_Shot_2021-11-19_at_4.38.16_PM.png?1637368796)

Copy and paste the following code into a file called **audiotest.py**.

```python
import pyaudio
import wave

FORMAT = pyaudio.paInt16
CHANNELS = 1           # Number of channels
BITRATE = 44100        # Audio Bitrate
CHUNK_SIZE = 512       # Chunk size to 
RECORDING_LENGTH = 10  # Recording Length in seconds
WAVE_OUTPUT_FILENAME = "myrecording.wav"
audio = pyaudio.PyAudio()

info = audio.get_host_api_info_by_index(0)
numdevices = info.get('deviceCount')
for i in range(0, numdevices):
    if (audio.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
        print("Input Device id ", i, " - ", audio.get_device_info_by_host_api_device_index(0, i).get('name'))

print("Which Input Device would you like to use?")
device_id = int(input()) # Choose a device
print("Recording using Input Device ID "+str(device_id))

stream = audio.open(
    format=FORMAT,
    channels=CHANNELS,
    rate=BITRATE,
    input=True,
    input_device_index = device_id,
    frames_per_buffer=CHUNK_SIZE
)

recording_frames = []

for i in range(int(BITRATE / CHUNK_SIZE * RECORDING_LENGTH)):
    data = stream.read(CHUNK_SIZE)
    recording_frames.append(data)

stream.stop_stream()
stream.close()
audio.terminate()

waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(BITRATE)
waveFile.writeframes(b''.join(recording_frames))
waveFile.close()
```

Run the code with the following command:

```terminal
sudo python3 audiotest.py
```

When finished, you can test playing back the file with the following command:

```terminal
aplay myrecording.wav
```

# Adafruit BrainCraft HAT - Easy Machine Learning for Raspberry Pi

## Fan Service Setup

Info: 

We have a really simple fan service that will control the onboard fan. The reason we have it set up as a service instead of keeping the fan on all the time is so that it doesn't drain too much power from the Pi during the initial power on.

The fan service basically controls turning GPIO 4 on at startup, which is what the fan is connected to. Installing the fan service is really simple and we have a script for doing that.

To install, just type **sudo raspi-config**

Select **Performance Options**

![](https://cdn-learn.adafruit.com/assets/assets/000/102/162/medium800/adafruit_products_image.png?1621103068)

Select **Fan**

![](https://cdn-learn.adafruit.com/assets/assets/000/102/163/medium800/adafruit_products_image.png?1621103096)

Select **Yes**

![](https://cdn-learn.adafruit.com/assets/assets/000/102/164/medium800/adafruit_products_image.png?1621103115)

![](https://cdn-learn.adafruit.com/assets/assets/000/102/165/medium800/adafruit_products_image.png?1621103149)

And make sure you put down **GPIO pin 4 for the fan**

![](https://cdn-learn.adafruit.com/assets/assets/000/102/166/medium800/adafruit_products_image.png?1621103161)

You can customize the fan temperature setting

![](https://cdn-learn.adafruit.com/assets/assets/000/102/167/medium800/adafruit_products_image.png?1621103183)

That's it!

![](https://cdn-learn.adafruit.com/assets/assets/000/102/168/medium800/adafruit_products_image.png?1621103204)

You can then 'stress test' by running

- `sudo apt-get install stress`
- `while true; do vcgencmd measure_clock arm; vcgencmd measure_temp; sleep 10; done& stress -c 4 -t 900s`

![](https://cdn-learn.adafruit.com/assets/assets/000/102/169/medium800/adafruit_products_image.png?1621103333)

When the temperature hits the limit you set earlier, the fan should turn on, and cool the pi back down (in this case I set it to 70 C):

![](https://cdn-learn.adafruit.com/assets/assets/000/102/170/medium800/adafruit_products_image.png?1621103576)

# Adafruit BrainCraft HAT - Easy Machine Learning for Raspberry Pi

## Display Module Install

There's two ways you can use the 1.54" 240x240 display on the BrainCraft HAT. For machine learning purposes, the advanced method is the way to go, so that's what we'll be covering in this guide.

Warning: 

 **The easy way** is to use 'pure Python 3' and Pillow library to draw to the display from within Python. This is great for showing text, stats, images etc that you design yourself. If you want to do that, the BrainCraft HAT has a pretty close layout to the [Adafruit 1.3" Color TFT Bonnet](https://www.adafruit.com/product/4506) including the same type of display and a joystick, though the pinouts are slightly different. If you choose this option, You can skip this page and view the [Python Setup page](https://learn.adafruit.com/adafruit-1-3-color-tft-bonnet-for-raspberry-pi/python-setup) for instruction for that display.

**The advanced way** is to install a kernel module to add support for the TFT display that will make the console appear on the display. This is cute because you can have any program print text or draw to the framebuffer (or, say, with pygame) and Linux will take care of displaying it for you. If you don't need the console or direct framebuffer access, please consider using the 'pure Python' technique instead as it is not as delicate.

**If you plan on using the Pi Camera for vision projects, you will need to go with the advanced route!**

# Installing The 1.54" Kernel Module

We have tried to make this as easy as possible for you by providing a script that takes care of everything. You will need to set up a Virtual Environment first and there's only a couple of additional dependencies needed.

## Setup Virtual Environment

If you are installing on the Bookworm version of Raspberry Pi OS or later, you will need to install your python modules in a virtual environment. You can find more information in the [Python Virtual Environment Usage on Raspberry Pi](https://learn.adafruit.com/python-virtual-environment-usage-on-raspberry-pi) guide. To Install and activate the virtual environment, use the following commands:

```terminal
sudo apt install python3-venv
python -m venv env --system-site-packages
```

To activate the virtual environment:

```terminal
source env/bin/activate
```

With the virtual environment set up, just run the following at the terminal:

```terminal
cd ~
pip3 install --upgrade adafruit-python-shell click
sudo apt-get install -y git
git clone https://github.com/adafruit/Raspberry-Pi-Installer-Scripts.git
cd Raspberry-Pi-Installer-Scripts
sudo -E env PATH=$PATH python3 adafruit-pitft.py --display=st7789v_bonnet_240x240 --rotation=0 --install-type=mirror
```

Warning: 

![](https://cdn-learn.adafruit.com/assets/assets/000/099/785/medium800/adafruit_products_PiTFT_Installation.png?1614382465)

When you get asked to reboot, reboot!

![](https://cdn-learn.adafruit.com/assets/assets/000/095/311/medium800/adafruit_products_PiTFT_Reboot.png?1601917701)

That's it! You will now have the BrainCraft HAT with a console display on it

# Adafruit BrainCraft HAT - Easy Machine Learning for Raspberry Pi

## Camera Test

Warning: 

Now that you have everything set up, it's time to do an initial test with the camera. This should display what the camera sees on the display.

`libcamera-hello -t 0`

If you are running the command from SSH:

`DISPLAY=:0 libcamera-hello -t 0`

Press Ctrl+C to exit the test.

![](https://cdn-learn.adafruit.com/assets/assets/000/095/375/medium800/adafruit_products_Camera_Test.jpeg?1602002508)

# Adafruit BrainCraft HAT - Easy Machine Learning for Raspberry Pi

## Python Usage

At this point, you should have just about everything already set up.

Besides the display, audio, and fan, this board has quite a few other useful features on it that can be controlled through Python. We'll go through those and how to control them in Python.

## Joystick and Button
The 5-way Joystick and button just use simple `digitalio` and each uses a separate GPIO, so they're really simple to control. Here's a little script that will setup the GPIOs, Create Internal Pullups, and then print out the value to the terminal.

![adafruit_products_one_one_one.png](https://cdn-learn.adafruit.com/assets/assets/000/125/973/medium640/adafruit_products_one_one_one.png?1699564920)

```python
import time
import board
from digitalio import DigitalInOut, Direction, Pull

BUTTON_PIN = board.D17
JOYDOWN_PIN = board.D27
JOYLEFT_PIN = board.D22
JOYUP_PIN = board.D23
JOYRIGHT_PIN = board.D24
JOYSELECT_PIN = board.D16

buttons = [BUTTON_PIN, JOYUP_PIN, JOYDOWN_PIN,
           JOYLEFT_PIN, JOYRIGHT_PIN, JOYSELECT_PIN]
for i,pin in enumerate(buttons):
  buttons[i] = DigitalInOut(pin)
  buttons[i].direction = Direction.INPUT
  buttons[i].pull = Pull.UP
button, joyup, joydown, joyleft, joyright, joyselect = buttons

while True:
  if not button.value:
    print("Button pressed")
  if not joyup.value:
    print("Joystick up")
  if not joydown.value:
    print("Joystick down")
  if not joyleft.value:
    print("Joystick left")
  if not joyright.value:
    print("Joystick right")
  if not joyselect.value:
    print("Joystick select")

  time.sleep(0.01)
```

Go ahead and save the above code onto your Pi as **button\_test.py** and run it with the following command:

`python button_test.py`

Now try moving the joystick and press the button and you should see it print out what you're pressing.

![](https://cdn-learn.adafruit.com/assets/assets/000/095/376/medium800/adafruit_products_Button_Test.png?1602005022)

## DotStar LEDs
The 3 DotStar LEDS can be controlled with the DotStar CircuitPython Library. Here's a little script that will setup the DotStar LEDs and then color cycle them.

![adafruit_products_one_one_one.png](https://cdn-learn.adafruit.com/assets/assets/000/125/982/medium640/adafruit_products_one_one_one.png?1699567540)

```python
import time
import board
import adafruit_dotstar

DOTSTAR_DATA = board.D5
DOTSTAR_CLOCK = board.D6

dots = adafruit_dotstar.DotStar(DOTSTAR_CLOCK, DOTSTAR_DATA, 3, brightness=0.2)

def wheel(pos):
    # Input a value 0 to 255 to get a color value.
    # The colours are a transition r - g - b - back to r.
    if pos < 0 or pos > 255:
        return (0, 0, 0)
    if pos < 85:
        return (255 - pos * 3, pos * 3, 0)
    if pos < 170:
        pos -= 85
        return (0, 255 - pos * 3, pos * 3)
    pos -= 170
    return (pos * 3, 0, 255 - pos * 3)

while True:
    for j in range(255):
        for i in range(3):
            rc_index = (i * 256 // 3) + j * 5
            dots[i] = wheel(rc_index & 255)
        dots.show()
        time.sleep(0.01)
```

Go ahead and save the above code onto your Pi as **dotstar\_test.py** and run it with the following command:

`python dotstar_test.py`

The DotStar LEDs should start color-cycling in a rainbow.

![](https://cdn-learn.adafruit.com/assets/assets/000/095/392/medium800thumb/adafruit_products_dotstars_color_wheel.jpg?1602008042)

## GPIO JST connectors
GPIOs&nbsp; **12** &nbsp;and&nbsp; **13** &nbsp;are accessible with the JST connectors on either side of the BrainCraft HAT.

![adafruit_products_one_one_one.png](https://cdn-learn.adafruit.com/assets/assets/000/125/986/medium640/adafruit_products_one_one_one.png?1699493408)

### Parts

For this script, we'll just need one part that isn't included with the BrainCraft HAT:

Featured
### Micro Servo with 3-pin JST PH 2mm Cable - TowerPro SG92R

[Micro Servo with 3-pin JST PH 2mm Cable - TowerPro SG92R](https://www.adafruit.com/product/4326)
This tiny little servo can rotate approximately 180 degrees (90 in each direction), and works just like the standard kinds you're used to but&nbsp;_smaller_. You can use any servo code, hardware or library to control these servos. Good for beginners who want to make stuff move...

In Stock
[Buy Now](https://www.adafruit.com/product/4326)
[Related Guides to the Product](https://learn.adafruit.com/products/4326/guides)
![Angled shot of a micro servo with a JST cable.](https://cdn-shop.adafruit.com/640x480/4326-00.jpg)

### Wiring
- Connect the **JST PH 3-pin plug** into the **GPIO #12** side of the BrainCraft HAT.

![adafruit_products_Servo_bb.png](https://cdn-learn.adafruit.com/assets/assets/000/125/989/medium640/adafruit_products_Servo_bb.png?1699493349)

[Download Fritzing Diagram](https://cdn-learn.adafruit.com/assets/assets/000/095/423/original/Servo.fzz?1602025943)
### Code
```python
import time
import board
import pulseio
from adafruit_motor import servo

SERVO_PIN = board.D12
pwm = pulseio.PWMOut(SERVO_PIN, frequency=50)
servo = servo.Servo(pwm, min_pulse=750, max_pulse=2250)

while True:
    for angle in range(0, 180, 5):  # 0 - 180 degrees, 5 degrees at a time.
        servo.angle = angle
        time.sleep(0.05)
    for angle in range(180, 0, -5): # 180 - 0 degrees, 5 degrees at a time.
        servo.angle = angle
        time.sleep(0.05)
```

Go ahead and save the above code onto your Pi as **servo\_test.py** &nbsp;and run it with the following command:

`python servo_test.py`

The servo should start sweeping back and forth in 5 degree increments.

![](https://cdn-learn.adafruit.com/assets/assets/000/095/398/medium800thumb/adafruit_products_servo_test.jpg?1602018104)

## Stemma QT
For the Stemma QT port, you can use any of our 50+ sensors, but we're going to use a script that demonstrates using the BMP280 because it's so simple.

![adafruit_products_one_one_one.png](https://cdn-learn.adafruit.com/assets/assets/000/125/990/medium640/adafruit_products_one_one_one.png?1699493370)

### Parts

For this script, we'll just need a BMP280 and a Stemma QT cable:

Featured
### Adafruit BMP280 I2C or SPI Barometric Pressure & Altitude Sensor

[Adafruit BMP280 I2C or SPI Barometric Pressure & Altitude Sensor](https://www.adafruit.com/product/2651)
Bosch has stepped up their game with their new BMP280 sensor, an environmental sensor with temperature, barometric pressure that is the next generation upgrade to the BMP085/BMP180/BMP183. This sensor is great for all sorts of weather sensing and can even be used in both I2C and...

In Stock
[Buy Now](https://www.adafruit.com/product/2651)
[Related Guides to the Product](https://learn.adafruit.com/products/2651/guides)
![Adafruit BMP280 I2C or SPI Barometric Pressure & Altitude Sensor - STEMMA QT](https://cdn-shop.adafruit.com/640x480/2651-08.jpg)

Featured
### STEMMA QT / Qwiic JST SH 4-pin Cable - 100mm Long

[STEMMA QT / Qwiic JST SH 4-pin Cable - 100mm Long](https://www.adafruit.com/product/4210)
This 4-wire cable is a little over 100mm / 4" long and fitted with JST-SH female 4-pin connectors on both ends. Compared with the chunkier JST-PH these are 1mm pitch instead of 2mm, but still have a nice latching feel, while being easy to insert and remove.

<a...></a...>

In Stock
[Buy Now](https://www.adafruit.com/product/4210)
[Related Guides to the Product](https://learn.adafruit.com/products/4210/guides)
![Angled shot of STEMMA QT / Qwiic JST SH 4-pin Cable.](https://cdn-shop.adafruit.com/640x480/4210-00.jpg)

### Wiring
- Connect one side of the Stemma QT cable to **either port on the BMP280**
- Connect the other side to the Stemma QT **port on the BrainCraft HAT**

![adafruit_products_Bmp280_bb.png](https://cdn-learn.adafruit.com/assets/assets/000/125/992/medium640/adafruit_products_Bmp280_bb.png?1699493379)

[Download Fritzing Diagram](https://cdn-learn.adafruit.com/assets/assets/000/095/422/original/Bmp280.fzz?1602025932)
### Code
https://github.com/adafruit/Adafruit_CircuitPython_BMP280/blob/main/examples/bmp280_simpletest.py

Go ahead and save the above code onto your Pi as **bmp280\_simpletest.py** &nbsp;and run it with the following command:

`python bmp280_simpletest.py`

The terminal should start printing out the detected measurements.

![](https://cdn-learn.adafruit.com/assets/assets/000/095/421/medium800/adafruit_products_BMP280_Simpletest.png?1602025912)

# Adafruit BrainCraft HAT - Easy Machine Learning for Raspberry Pi

## Downloads

## Files

- [ST7789 datasheet](https://cdn-learn.adafruit.com/assets/assets/000/092/512/original/ST7789.pdf?1593024947)
- [EagleCAD PCB files on GitHub](https://github.com/adafruit/Adafruit-BrainCraft-HAT-PCB)
- [3D Model on GitHub](https://github.com/adafruit/Adafruit_CAD_Parts/tree/master/4374%20BrainCraft%20HAT)
- [Fritzing object in Adafruit Fritzing Library](https://github.com/adafruit/Fritzing-Library/blob/master/parts/Adafruit%20BrainCraft%20HAT.fzpz)

## Schematic
![](https://cdn-learn.adafruit.com/assets/assets/000/095/331/medium800/adafruit_products_Schematic.png?1601935160)

![](https://cdn-learn.adafruit.com/assets/assets/000/096/498/medium800/adafruit_products_Schematic_Page_2.png?1603823817)

![](https://cdn-learn.adafruit.com/assets/assets/000/096/499/medium800/adafruit_products_Schematic_Page_3.png?1603823836)

## Fab Print
![](https://cdn-learn.adafruit.com/assets/assets/000/095/330/medium800/adafruit_products_fab_print.png?1601935135)


## Primary Products

### Adafruit BrainCraft HAT - Machine Learning for Raspberry Pi 4

[Adafruit BrainCraft HAT - Machine Learning for Raspberry Pi 4](https://www.adafruit.com/product/4374)
The idea behind the BrainCraft HAT is that you’d be able to “craft brains” for Machine Learning on the EDGE, with Microcontrollers & Microcomputers. On&nbsp;ASK AN ENGINEER, our founder & engineer chatted with&nbsp;Pete Warden, the technical lead of the mobile,...

In Stock
[Buy Now](https://www.adafruit.com/product/4374)
[Related Guides to the Product](https://learn.adafruit.com/products/4374/guides)

## Guide Products

### Raspberry Pi 4 Model B - 2 GB RAM

[Raspberry Pi 4 Model B - 2 GB RAM](https://www.adafruit.com/product/4292)
The Raspberry Pi 4 Model B is the newest Raspberry Pi computer made, and the Pi Foundation knows you can always make a good thing _better_! And what could make the Pi 4...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4292)
[Related Guides to the Product](https://learn.adafruit.com/products/4292/guides)
### 5V 2.5A Switching Power Supply with 20AWG MicroUSB Cable

[5V 2.5A Switching Power Supply with 20AWG MicroUSB Cable](https://www.adafruit.com/product/1995)
Our all-in-one 5V 2.5 Amp + MicroUSB cable power adapter is the perfect choice for powering single-board computers like Raspberry Pi, BeagleBone, or anything else that's power-hungry!

This adapter was specifically designed to provide 5.25V, not 5V, but we still call it a 5V USB...

In Stock
[Buy Now](https://www.adafruit.com/product/1995)
[Related Guides to the Product](https://learn.adafruit.com/products/1995/guides)
### Official Raspberry Pi Power Supply 5.1V 3A with USB C

[Official Raspberry Pi Power Supply 5.1V 3A with USB C](https://www.adafruit.com/product/4298)
The official Raspberry Pi USB-C power supply is here! And of course, we have 'em in classic Adafruit black! Superfast with just the right amount of cable length to get your Pi 4 projects up and running!

Best for use with Pi 4 series, [Pi...](https://www.adafruit.com/product/5814)

In Stock
[Buy Now](https://www.adafruit.com/product/4298)
[Related Guides to the Product](https://learn.adafruit.com/products/4298/guides)
### SD/MicroSD Memory Card (8 GB SDHC)

[SD/MicroSD Memory Card (8 GB SDHC)](https://www.adafruit.com/product/1294)
Add mega-storage in a jiffy using this 8 GB class 4 micro-SD card. It comes with a SD adapter so you can use it with any of our shields or adapters. Preformatted to FAT so it works out of the box with our projects. Tested and works great with our <a...></a...>

Out of Stock
[Buy Now](https://www.adafruit.com/product/1294)
[Related Guides to the Product](https://learn.adafruit.com/products/1294/guides)
### Raspberry Pi Camera Board v2 - 8 Megapixels

[Raspberry Pi Camera Board v2 - 8 Megapixels](https://www.adafruit.com/product/3099)
Snap, snap! The Camera v2 is the new official camera board released by the Raspberry Pi Foundation!

The **Raspberry Pi Camera Board v2** is a high quality 8 megapixel Sony IMX219 image sensor custom designed add-on board for Raspberry Pi, featuring a fixed focus lens....

Out of Stock
[Buy Now](https://www.adafruit.com/product/3099)
[Related Guides to the Product](https://learn.adafruit.com/products/3099/guides)
### Flex Cable for Raspberry Pi Camera or Display - 1 meter

[Flex Cable for Raspberry Pi Camera or Display - 1 meter](https://www.adafruit.com/product/2143)
This cable will let you swap out the stock 150mm long flex cable from a Raspberry Pi Camera (either 'classic' or 'NoIR' type) or Raspberry Pi Display for a different size. Works great, just carefully open the connector on the Pi and slip this one in.

This cable is 1 meter...

In Stock
[Buy Now](https://www.adafruit.com/product/2143)
[Related Guides to the Product](https://learn.adafruit.com/products/2143/guides)
### Adafruit Raspberry Pi Camera Board Case with 1/4" Tripod Mount

[Adafruit Raspberry Pi Camera Board Case with 1/4" Tripod Mount](https://www.adafruit.com/product/3253)
This is a basic, classic **Adafruit Raspberry Pi Camera Board Enclosure** &nbsp;with a black base and a clear top.&nbsp;The case is as minimal as it gets, coming in just two pieces of polycarbonate that snap snugly together. This case will keep your&nbsp;Pi Camera safe and secure...

In Stock
[Buy Now](https://www.adafruit.com/product/3253)
[Related Guides to the Product](https://learn.adafruit.com/products/3253/guides)

## Related Guides

- [Adafruit BMP280 Barometric Pressure + Temperature Sensor Breakout](https://learn.adafruit.com/adafruit-bmp280-barometric-pressure-plus-temperature-sensor-breakout.md)
- [Raspberry Pi Care and Troubleshooting](https://learn.adafruit.com/raspberry-pi-care-and-troubleshooting.md)
- [Edge-Lit Tavern Sign with WLED - Control with WiFi or IR Remote](https://learn.adafruit.com/edge-lit-tavern-sign-with-wled-control-with-wifi-or-ir-remote.md)
- [Dancing Inflatables: Make your Holiday Display Move](https://learn.adafruit.com/dancing-inflatables-make-your-holiday-display-move.md)
- [Ultimate Youtube Live Camera](https://learn.adafruit.com/ultimate-youtube-live-camera.md)
- [Adafruit ESP32-C6 Feather](https://learn.adafruit.com/adafruit-esp32-c6-feather.md)
- [Python Edge Speech Recognition with Voice2JSON](https://learn.adafruit.com/edge-speech-recognition-with-voice2json.md)
- [Air Quality Sensor 3D Printed Enclosure](https://learn.adafruit.com/air-quality-sensor-silo-house.md)
- [No-Code IoT Door Alarm with WipperSnapper](https://learn.adafruit.com/no-code-iot-door-alarm-with-wippersnapper.md)
- [Matrix Portal M4 Boxing Interval Timer](https://learn.adafruit.com/matrix-portal-m4-boxing-interval-timer.md)
- [4x4 Rotary Encoder MIDI Messenger](https://learn.adafruit.com/4x4-rotary-encoder-midi-messenger.md)
- [Custom Scrolling Quote Board Matrix Display](https://learn.adafruit.com/aio-quote-board-matrix-display.md)
- [RGB Matrix Portal Room CO2 Monitor](https://learn.adafruit.com/matrix-portal-room-co2-monitor.md)
- [Forecast the Weather at Home with a No-Code Barometer ](https://learn.adafruit.com/dps310-analog-barometer.md)
- [Boomy The Boombox](https://learn.adafruit.com/boomy-the-boombox.md)
- [PyGamer MP3 Player with CircuitPython](https://learn.adafruit.com/pygamer-mp3-player-with-circuitpython.md)
- [Adafruit Feather RP2040 with USB Type A Host](https://learn.adafruit.com/adafruit-feather-rp2040-with-usb-type-a-host.md)
