Raspberry Pi GPIO control using Amazon Alexa Voice Services

Published  June 29, 2018   2
Raspberry Pi GPIO control using Amazon Alexa Voice Services

Have you ever thought about a speaker which can be controlled by your voice!!! What if we can control our home appliances this way and make these appliances smarter? Voice assistants becoming more popular as we are heading towards an era of AI and IoT based systems. You have heard about Google Assistant, Apple Siri and Amazon Alexa. These all are Voice based AI systems, what makes these different from each other is their ecosystems, and this is where Amazon Alexa standout the most. Google, Apple and Amazon, all these companies already launched their smart speakers but Amazon was first to introduce smart speakers. Amazon echo, Echo Dot Spot, etc. are the smart speakers which are available in market.

Amazon provides the API for using its much popular voice service, Alexa. It is open source and available on Github. Further you can install or integrate Alexa on custom devices like Raspberry Pi and get the full Amazon Echo functionality in that device.

Using Alexa voice service, we can play music, get information about weather, book tickets and many more. All you have to do is ‘ask’. In this tutorial, we will see how we can control Raspberry Pi GPIO using Alexa Voice services to glow an LED.


Perquisite Material:

Hardware Requirements:

  1. Raspberry Pi 3 [Recommended] or Raspberry Pi 2 Model B [Supported] and SD Card (8GB or more)
  2. External Speaker with 3.5mm AUX cable
  3. Any Webcam or USB 2.0 Microphone
  4. Relay module
  5. LED


Note: Webcam has inbuilt microphone so, we will use this in place of USB 2.0 microphone.

Webcam as USB microphone

Software Apps and Web Requirements:

  1. Register an account with Alexa Voice Services
  2. Register an account with PubNub
  3. Register an account with IFTTT

We also assume that your Raspberry pi is already set up with an Raspbian OS and is connected to the internet. With these in place let’s proceed with the tutorial. If you are new to Raspberry Pi then go through Getting started with Raspberry pi first.

The whole tutorial is mainly divided into 5 parts, which are as follows:

  1. If you don’t have monitor then we have to setup the Raspberry Pi with SSH and VNC, also check the USB Microphone connectivity.
  2. Set up Your Amazon Developer and installing Alexa on Raspberry Pi
  3. Setting up PubNub and IFTTT for Alexa Home Automation
  4. Hardware connection
  5. Python code for Alexa Pi GPIO Control

If you simply wants to control an LED with your voice, the also check our Bluetooth based Voice controlled LED project.


Part 1: Setting up the Raspberry Pi with SSH and VNC

First, we will connect Raspberry Pi with SSH and VNC. For this follow tutorials on official Raspberry Pi’s website, links are given below.

For SSH: SSh link

For VNC : VNC link

If you have Monitor then you can leave this step and go directly to step 2 which is Setting Up The Alexa Voice Service(Avs). Before that we have to check mic connectivity.


Checking Webcam Mic with Raspberry Pi:

1. Open Raspberry Pi terminal and type arecord -l command. This will display the hardware devices which are connected to Raspberry Pi as shown below:

Checking for hardware device connected to Raspberry Pi


Card 1 is your webcam’s mic that we are going to use. If it is not displayed, your webcam may be defective.


2. Now, check if mic is working by running the record audio command as :

arecord  /home/pi/Desktop/test.wav  -D  sysdefault:CARD=1


3. To play the recorded audio type this command :

omxplayer -p  -o  local /home/pi/Desktop/test.wav


If you have connected Raspberry Pi with monitor using HDMI cable then by default audio output is through your monitor’s speaker (if there is inbuilt speaker in it). So, to change it to 3.5mm you have to type the following command:

sudo raspi-config and go to Advance option. 


Select Audio from the list -> select Force 3.5mm -> select Ok and Restart you Raspberry Pi.

Now, you should hear the sound from 3.5mm jack.

NOTE: If you want to increase or decrease the input voice loudness for microphone the type alsamixer in the terminal. Select sound card from the terminal by pressing F6.

Press F4 to change the Mic dB gain and set it as you want.

Increase or decrease the input voice loudness for microphone from Raspberry Pi


If you have USB 2.0 microphone then steps followed are same to check the microphone. Here we have used Webcam for USB microcphone.


Part 2: Set up Your Amazon Developer Account and Configure Alexa Voice Services on Raspberry Pi:

We have already explained this in detail in our previous tutorial where we have built a Amazon Echo smart speaker. Here are we are focusing on controlling Raspberry Pi GPIO with Alexa so we are not explaining the whole process again, so read the previous article and get your Speaker ready with Alexa voice services installed on your Raspberry pi.

To test Alexa, just wake her up by saying her name! Check the Demo Video Given at the end of the tutorial.

Testing Alexa using Raspberry Pi


You can ask her about temperature of your city to check it is working or not.


Part 3: Setting up PubNub and IFTTT for Alexa Pi Home Automation:

For controlling Raspberry Pi GPIO using this Alexa Pi, we need the help of PubNub python SDK and IFTTT. We will give commands to IFTTT through Alexa, and PubNub gives signal to RPi to turn on/off the LED. So we will first install the PubNub on Raspberry Pi.


Part 3-1: Installing PubNub Python SDK:

PubNub provides a messaging API to publish/subscribe any message on their Global network. Here we are using IFTTT and Alexa to publish the message on PubNub, for making Raspberry Pi GPIO low/high. This message is received by Raspberry Pi and Pi will turn On or OFF the LED accordingly. Follow below steps to setup PubNub on Raspberry Pi:

Step 1: Open terminal on your RPi and run the following command  to install SDK:

sudo pip install pubnub==3.9.0


Install 3.9.0 version only, other version will not work with the python script which we will going to run in the last.

Installing PubNub Python SDK in Raspberry Pi


Step 2: Now, go to PubNub and sign in with your credentials.

Sign In on PubNub


Step 3:. Obtain the Publish and Subscribe Keys we will be using later on.

Publish and Subscribe Keys on PubNub


Part 3-2: Setting up IFTTT for Amazon Alexa Service:

IFTTT is a free web-based service that allows users to create chains of simple conditional statements, called “recipes”, which are triggered based on changes to other web services such as Gmail, Facebook, Instagram, and Pinterest. IFTTT is an abbreviation of “If This Then That”.

For this project, IFTTT is used to make the Raspberry Pi GPIO LOW/HIGH based on the speech command received by Alexa service running on RPi.

Follow these steps to make an Applet:

Step 1:- Login to IFTTT with your credentials or Sign Up if you don’t have an account on it.

Login to IFTT


Step 2:- On My Applets, Click on New Applet

Choose New Applet on IFTT


Step 3:- Click on +this

Step 4:- Search Amazon Alexa and click on it, sign in with your amazon developer account details.

Search Amazon Alexa on IFTT


Step 5:- Choose the trigger, Say a specific phrase

Choose for Say a specific phrase for alexa


Step 6:- Provide turn on the light” as the phrase, click on Create Trigger.

Provide Phrase and create trigger for alexa on IFTT


Step 7:- Click on +that

Click on +that for giving condition to alexa


Step 8:- Search for Webhooks, click on it and Select Make a Web Request

Search for Webhooks click on it and Select Make a Web Request


Step 9:- Webhooks provides the REST WEB Request, Use the Publish and Subscribe keys obtained from the PubNub and modify the following URL.



Step 10:- Paste the modified URL to the URL text box.

Paste URL of PubNub in IFTT


Step 11:- Set the Method as GET, Content as application/json and click on save.

Create Action for Alexa with GET method


Step 12:- Follow the same steps to create the trigger for “turn off the light” and modify the URL to the following. 


Review and finish Alexa command


Step 13:-  We are now ready with all the web components for the demo.


Part 4: Hardware connections and Circuit Diagram:

For this project, we need a simple LED for testing purpose. Below is the circuit diagram and Hardware connections to controlling Raspberry Pi GPIO with Amazon Alexa.

We will using GPIO18 in our python script so, connect relay your LED 18. You can change this in python script.

Circuit diagram for Raspberry Pi GPIO control using Amazon Alexa Voice Services


Circuit Hardware for Raspberry Pi GPIO control using Amazon Alexa Voice Services


Part 5: Python Code for Controlling the LED:

Find the complete Python Script at the end of this tutorial.

You need to edit Pub and Sub key with your pubnub keys in the python code.

# Initialize the Pubnub Keys 
pub_key = "***************************"
sub_key = "************************"


Now run the Script

python alexaRpi.py


Now we are all set for the demo, Make sure you are running all the three services from the Part 1 (the three terminals) before continuing.

Python Code for Controlling the Light on Raspberry Pi with Alexa


To give any command you need to wake up Alexa service by calling “Alexa” each time you want to send a command. You will hear a beep sound. Once you hear the beep, say “Alexa Trigger Turn on the Light.” You can see the light turns ON within a moment. And then if you say “Alexa Trigger Turn off the Light”, the light should turn OFF.

That’s it…. You can further add a relay to control AC appliance, even you can control many appliances by using more relays and more GPIO pins of Raspberry pi.

Check the complete code and Demonstration Video below. Also check our all the Home Automation Projects here.

#Import all the libraries
import RPi.GPIO as GPIO
import time
from pubnub import Pubnub
# Initialize the Pubnub Keys 
pub_key = "***************************"
sub_key = "************************"
LIGHT = 18           #define pin of RPi on which you want to take output
def init():          #initalize the pubnub keys and start subscribing
 global pubnub    #Pubnub Initialization
 GPIO.output(LIGHT, False) 
 pubnub = Pubnub(publish_key=pub_key,subscribe_key=sub_key)
 pubnub.subscribe(channels='alexaTrigger', callback=callback, error=callback, reconnect=reconnect, disconnect=disconnect)
def control_alexa(controlCommand):          #this function control Aalexa, commands received and action performed
  if(controlCommand["trigger"] == "light" and controlCommand["status"] == 1):
   GPIO.output(LIGHT, True) 
   print "light is on"
   GPIO.output(LIGHT, False) 
   print "light is off"
def callback(message, channel):        #this function waits for the message from the aleatrigger channel
def error(message):                    #if there is error in the channel,print the  error
 print("ERROR : " + str(message))
def reconnect(message):                #responds if server connects with pubnub
def disconnect(message):               #responds if server disconnects with pubnub
if __name__ == '__main__':
 init()                    #Initialize the Script

Have any question realated to this Article?

Ask Our Community Members


Hello Rishabh,

I have followed your instruction on the controlling the GPIO using Alexa Voice Services and it worked first time. I am very happy with the outcome. The process is simple and efective. Every time I ask Alexa to triger light on or off, she says: contacting IFTTT. I do not mind this but is there an option to disable this?

also, I have been wondering if two way comunication can also be done using the pubnub and IFTTT? I am not a professional programmer and I would appreciate your guidance on this. technically I would like to use raspberry pi to read from temperature sensor and send the value to alexa, when I ask her.

I will be fllowing your other tutorials as well as I found them easy to follow. I am a consumer and not much of the inventor - I hope you understand.



hello it’s great. But why led light just for a while? In code there is no time , while or other command? How can I make it to light constantly ?