This Raspberry Pi Alexa tutorial will show you how to build and set up a fully functional personal assistant that uses your Raspberry Pi and the Alexa Voice service to respond to your voice commands.

Raspberry Pi Alexa

The only negative to making your Alexa powered device is that it cannot access music services such as Pandora or Spotify.

This Raspberry Pi Alexa however, does come with all the other bells and whistles of Amazon’s very own Echo device as it utilizes the Alexa Voice Service. By default, it will have always listening, so you can talk to your Alexa by simply saying its name.

That means you have access to Alexa, Amazon’s own virtual assistant, something that is much like Microsoft’s Cortana, Apple’s Siri and Google Now.

Utilizing the Alexa Voice Service gives you the ability to do numerous different things such as unit conversions and checking sports scores just by using your voice.

All you need to build your own Alexa powered personal assistant is a Raspberry Pi with a USB Microphone and speakers.

Equipment List

Below are all the bits and pieces that I used for this build your own Raspberry Pi Alexa tutorial, you will need a microphone and speakers handy to be able to set this up.

Recommended

Raspberry Pi

Micro SD Card

Power Supply

Network Connection

USB Microphone

Speakers

Optional

Raspberry Pi Case

Registering an Alexa Voice Service product

1. Before we get started with setting up the Raspberry Pi, we will first have to create our own Amazon Developer Account.

We can do this by going to Amazon developer web page and following the prompts. We won’t go through the exact steps to set up your account as it is self-explanatory.

Once you have created your account and logged in, we can then proceed with setting up everything we need for our Raspberry Pi Amazon Echo.

Upon logging in you will be greeted with the following screen, hover over the “Alexa” (1.) tab and select “Alexa Voice Service” (2.).

Amazon Developers homepage

2. On this next screen, click Products. This screen is the area that will allow us to set up access for our Raspberry Pi to connect to the Alexa voice service.

Amazon Alexa Voice Service

3. Now click “Create Product” to proceed on with the process of setting up a “product” for your Pi.

Amazon Alexa Products

4. On this screen, there are a few things that you will have to set before you can proceed.

(1.) Product name is displayed to users in the “Alexa App“, set this to something simple but identifiable.

(2.) Product ID is used for the authorization process. The ID must only contain letters, numbers ,and underscores. For our example, we set this to “pimylifeup_alexa_tutorial“.

(3.) Make sure that you set the “Product Type” to “Device with Alexa built-in“.

(4.) Unless you intend on creating your own companion app, set this to “No“.

(5.) Now for “Product Category“, we set this to “Other (Please Specify)” with the specified category being “Raspberry Pi“.

(6.) Finally, you can write a short description of the device. This setting is purely for the AVS service.

Amazon Alexa setting product information

5. Continuing from the previous step, there are several more options that we still have to set on this page before being able to proceed.

Most of these options are for you to indicate how you intend on using the Alexa Voice Service to Amazon.

Below is a quick run through of each of these remaining options.

(1.) Here you can set the way that you intend on people interacting with your Raspberry Pi Alexa device.

In our guide, we are setting this to both “Touch-initiated” and “Hands-free” so that you can trigger it by either pressing a button or speaking to the device.

(2.) Unless you intend on distributing your Raspberry Pi Alexa commercially set this option to “No“.

(3.) For this option select “No” unless you intend on utilizing the “Alexa for Business” service.

(4.) Select “No” for this option, unless you happen to have the device also associated with AWS IoT Core accounts.

(5.) Now for the final option, make sure that you select “No” to this option as it is not intended purely for people under the age of 13.

Amazon Alexa setting product information

6. Once you have filled in all the required options, you can proceed on with the setup process by clicking the “Next” button that is displayed at the bottom of the page.

7. You will now be prompted to set up a Login with Amazon (LWA) Security Profile.

As we don’t already have a profile, we will have to create one by clicking the “CREATE NEW PROFILE” link as shown below.

LWA Security Profile

8. Now in the text boxes enter a name for this security profile and a short description (1.). We kept these as simple descriptors for what we intend on utilizing it for.

For our tutorial, we set the “Profile Name” to “Pi My Life Up Raspberry Pi Alexa” and set the “Profile Description” to “Profile for Pi My Life Up’s Raspberry Pi Alexa“.

The “Security Profile Name” field makes it easy to identify the security profile and what it is being utilized for. The “Security Profile Description” field is meant to explain what the profile is for.

Once you have set both fields, click the “NEXT” button (2.) to proceed.

LWA Security Profile - Step 2

9. With the “Login with Amazon” security profile created we can proceed to generating the required ID information so that we can make a connection to the Alexa Voice Service from our Raspberry Pi.

First, switch to the “Other devices and platforms” tab (1.) within the “Platform Information” section.

This section will allow us to generate the relevant data that we require to make a connection to the Alexa Voice Service.

Now we need to set a “Client ID name” (2.) before we can generate the actual ID and authorization data.

The client ID is used for identifying and authorizing your Raspberry Pi to connect to Alexa. This value is not shown to the end user and is purely for authorization.

For our guide, we set the client ID to “pi_my_life_up_raspberrypi_alexa” as it represents both the device and what we intend on utilizing it for.

Once you have set a client ID press the “GENERATE ID” button (3.).

LWA Security Profile Generate ID - Step 3

10. With the Client ID generated go ahead and click the “DOWNLOAD” (1.) button.

Make sure that you save the file somewhere that’s easily accessible as we will need to grab the contents of this file later on in the tutorial.

Now tick the checkbox next to the “I agree” (2.) to the terms and conditions text.

Once you have downloaded the Client ID files go ahead and click the “FINISH” (3.) button.

LWA Security Profile Download ID - Step 4

11. You have now successfully created your product allowing you to access the AWS API.

Product created

12. Before we can set up Alexa on our Raspberry Pi, we must enable the security profile that we just created.

To do this, you will need to go to the “Login With Amazon” homepage.

13. On this screen, you need to select the LWA Security profile that we created in previous steps (1.)

Once selected, click the “Confirm” (2.) button.

Login with amazon

14. Here you are required to set the “Consent Privacy Notice URL” (1.). If you are only using this for personal use, you can set this to a fake URL to proceed.

For our tutorial, we just set the consent URL to “http://example.com” as we do not plan on this to be a publicly accessible profile.

Once you have set a Consent Privacy Notice URL, go ahead and press the “Save” (2.) button.

Enter Consent Screen Information

Setting up Alexa on the Raspberry Pi

1. Before we proceed to install Alexa to the Raspberry Pi, let’s first ensure that we are running the latest available software.

You can achieve this by running the commands below on your Raspberry Pi.

sudo apt-get update
sudo apt-get upgrade

2. Now let’s download all the installation and configuration scripts that we require from the alexa-device-sdk GitHub.

These scripts will setup and configure Alexa on your Raspberry Pi and handle most of the grunt work of setting up the Alexa software.

Download all three scripts by running the following three commands.

wget https://raw.githubusercontent.com/alexa/avs-device-sdk/master/tools/Install/setup.sh 
wget https://raw.githubusercontent.com/alexa/avs-device-sdk/master/tools/Install/genConfig.sh
wget https://raw.githubusercontent.com/alexa/avs-device-sdk/master/tools/Install/pi.sh

3. With all the scripts now available to us we will now want to move the config.json file that we downloaded earlier to the right location.

If you downloaded the file on your Raspberry Pi, then you can move it to the /home/pi location and skip to step 5.

Otherwise, you can create a new file by running the following command.

nano ~/config.json

4. Now copy and paste the contents of the config.json file you downloaded earlier to this file.

The contents should end up being 6 lines long as we have shown in our example below.

{
 "deviceInfo": {
  "clientId": "amzn1.application-oa2-client.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "productId": "pimylifeup_alexa_tutorial"
 }
}

Once you have entered the correct data, go ahead and save the file by pressing CTRL + X then Y and finally ENTER.

5. Now we can go ahead and run the “setup.sh” script by running the command below.

This script will install all the necessary information and prepare Alexa on your Raspberry Pi.

sudo bash setup.sh config.json

6. Before the setup process can start, you will be asked about whether you agree to various terms and agreements as the Alexa Device SDK relies on multiple third-party repositories.

We have included an example of what this message should look like below.

To proceed with the installation process, you will need to type in “AGREE” and press ENTER to continue.

If for some reason you do not agree with the terms you can enter “QUIT” but the software will not be installed and setup.

Please note that the setup process can take some time as there are a fair few packages that will be installed and several that will need to be automatically compiled from scratch.

#############################################################################
#############################################################################


AVS Device SDK Raspberry pi Script - Terms and Agreements


The AVS Device SDK is dependent on several third-party libraries, environments,
and/or other software packages that are installed using this script from
third-party sources ("External Dependencies"). 


These are terms and conditions associated with the External Dependencies
(available at https://github.com/alexa/avs-device-sdk/wiki/Dependencies) that
you need to agree to abide by if you choose to install the External Dependencies.

If you do not agree with every term and condition associated with the External
Dependencies, enter "QUIT" in the command line when prompted by the installer.

Else enter "AGREE".


#############################################################################
#############################################################################

7. Once the setup process has completed, we will still need to install a few additional packages for the Alexa software to work correctly.

For some reason, these packages aren’t installed during the standard setup process, and you will run into errors without them.

Install these additional packages by running the command below.

sudo apt-get install gstreamer1.0-alsa gstreamer1.0-tools gstreamer1.0-plugins-ugly

Setting up your Audio for your Raspberry Pi Alexa device

1. Before we go ahead and run the Alexa software, we must first ensure that our audio is configured correctly.

We must first retrieve the card and device numbers for both our microphone and our audio output.

1a. Run the following command to list all available recording devices. From this command write down the card number and the device number for your microphone.

arecord -l

1b. Now run the following command to list all playback devices. Record both the card number and the device number for the device you want to output through.

Note that the Raspberry Pi’s 3.5mm-jack is typically labeled as Analog or bcm2835 ALSA, with the HDMI output being identified as bcm2835 IEC958/HDMI.

aplay -l

2. Now that we have all the device and card numbers that we require, we now need to go ahead and create our .asoundrc file for the pi user by running the command below.

This .asoundrc file is used for the ALSA sound driver to know what devices to utilize.

nano /home/pi/.asoundrc

3. In this file, you will need to enter the following lines to configure your audio.

Replace both with their respective values that you retrieved during step 1 of this section.

pcm.!default {
  type asym
  capture.pcm "mic"
  playback.pcm "speaker"
}
pcm.mic {
  type plug
  slave {
    pcm "hw:,"
  }
}
pcm.speaker {
  type plug
  slave {
    pcm "hw:,"
  }
}

4. Once you are done, you can save the file by pressing CTRL + X then Y and finally ENTER.

Authorizing and running Alexa on your Raspberry Pi

1. Now with Alexa setup on our Raspberry Pi, we can now proceed to start up the sample Alexa app to get our device authorized.

You need to enter the following command on your Raspberry Pi to start the Alexa sample app.

sudo bash startsample.sh

2. The first time you start up the sample Alexa app, you will be greeted with the message shown below.

{xxxx} is a unique code that has been generated to authorize your Raspberry Pi to access the Alexa voice service.

To authorize your Raspberry Pi, go to Amazon Code and follow the prompts to approve your Raspberry Pi’s connection to Alexa.

The Alexa sample app will automatically talk with the Amazon web servers to detect when you have authorized the device.

##################################
#       NOT YET AUTHORIZED                      #
##################################

#############################################################################
#       To authorize, browse to: 'https://amazon.com/us/code' and enter the code: {XXXX}          #
#############################################################################

3. Once you see the text below, then you will know that your Raspberry Pi has been successfully authorized to talk with the Alexa Voice Service.

You may have to scroll up through the command line history as the Alexa software will produce a fair amount of output once it has been marked as authorized.

###########################
#       Authorized!                          #
###########################

4. There are various ways you can interact with the Alexa sample software. The easiest way of interacting with it is to say “Alexa” followed by your prompt to the Alexa Voice Service.

Alternatively, you can also enter “t” into the command line to skip the process of having to say “Alexa” out loud.

If you want you can use “h” which will simulate holding a button down. Using “h” will make the Alexa sample software continually listen until you enter “h” into the command line again.

If everything is working as it should, you will get a response streamed from the Alexa Voice Service to your Raspberry Pi. This response will be played back through the audio device you configured earlier.

Getting your Raspberry Pi Alexa device to start on boot

1. To get the Alexa software to startup at boot on our Raspberry Pi ,we will have to first make some modifications to the “SampleApp” code.

By default the code is designed to wait on input from stdin, but when stdin isn’t available it will throw errors so we will have to modify the input loop.

Begin modifying the “UserInputManager.cpp” script by running the following command.

sudo nano /home/pi/avs-device-sdk/SampleApp/src/UserInputManager.cpp

2. Within this file use nano’s CTRL + W functionality to find the following section of code. We found it easiest to find it by searching for “m_interactionManager->begin();

Below that section of code and within the while loop make sure you add the code displayed below. This additional code will sleep the input thread and stop any of the input handling to happen.

Find the following block of code

void UserInputManager::run() {
    if (!m_interactionManager) {
        return;
    }
    m_interactionManager->begin();
    while (true) {

Add Below

        std::this_thread::sleep_for(std::chrono::hours(1));
        continue;

3. After the changes the code should look like what we have displayed below.

void UserInputManager::run() {
    if (!m_interactionManager) {
        return;
    }
    m_interactionManager->begin();
    while (true) {
        std::this_thread::sleep_for(std::chrono::hours(1));
        continue;

4. Now save the file by pressing CTRL + X then Y and finally ENTER.

5. As we have now modified one of the scripts we will now need to recompile it.

Don’t worry this will be a fairly quick process as we just need to rerun the setup script from earlier as shown in the following two commands.

cd /home/pi
sudo bash setup.sh config.json

6. Now that we have compiled the Alexa SampleApp we can now proceed on to creating a service file so that we can automatically start our Alexa service at startup.

Let’s create this service file by running the following command.

sudo nano /lib/systemd/system/alexa.service

7. Within this service file, you will need to enter the lines shown below.

These lines of text will define how the operating system should handle our service.

It tells the operating system what user will execute the bash script. It also sets that we require the network to be active before initializing Alexa.

[Unit]
Description=Raspberry Pi Alexa
Wants=network-online.target
After=network-online.target

[Service]
Type=simple
ExecStart=/bin/bash /home/pi/startsample.sh
Restart=on-abort
User=pi
Group=pi

[Install]
WantedBy=multi-user.target

Once everything has been entered you can save the file by pressing CTRL + X then Y and finally ENTER.

8. With our Alexa service created we need to enable it before it can load on startup.

To enable the new service will use the systemctl utility. Type in the following command to enable it.

sudo systemctl enable alexa.service

9. With the Alexa service now enabled, let’s proceed to start it. Starting the service now will allow us to ensure that everything is working as it should be.

Start the service by running the command below on your Raspberry Pi.

sudo systemctl start alexa.service

10. With the service started you should now be able to use the “Alexa” hotword to interact with your Raspberry Pi Alexa device.

If you get no response, you can check the status of the service by running the following command.

sudo systemctl status alexa.service

Improving your Microphone Gain

1. If your microphone is having trouble picking up your voice, then one solution would be to increase the microphone gain. It is possible to do this by utilizing alsamixer.

To launch alsamixer type the following command into terminal:

alsamixer

Alsa Mixer

2. Once the AlsaMixer app has loaded up, you can press F6 to select a different USB Device, use the arrow keys to select your microphone and press Enter.

3. With your microphone selected, use the arrow keys to increase the capture volume. Once you are happy with the capture volume, you can press ESC to exit.

4. Now to keep these new setting, we will need to tell alsa to store the new settings and make them permanent. To do this, we can run the following command:

sudo alsactl store

You should now have a fully operational, build your own, Raspberry Pi Amazon Alexa up and running. If you found this tutorial helpful or you have run into any issues, then feel free to leave a comment below.

Ultimate Books of Pi Bottom
Subscribe to get our FREE Crash Course to the Raspberry Pi.