To connect a Raspberry Pi to Alexa for voice-controlled GPIO projects, the most reliable method in 2026 is bypassing clunky IFTTT webhooks and using the Alexa Smart Home Skill API via a bridge service like SinricPro. This allows your Pi to act as a native smart switch with sub-second latency, direct local network communication, and secure credential handling. Below is the complete bench-tested guide to wiring a 5V relay to your Pi, writing the Python control script, and debugging the inevitable connection drops.
Project Overview & Hardware Requirements
This build targets the Raspberry Pi 4 Model B (4GB RAM) running Raspberry Pi OS (Bookworm, 64-bit). While the code will run on a Pi 3B+ or Pi 5, the Pi 4 offers the best balance of stable Wi-Fi and GPIO drive current for this specific relay module without requiring an external logic level shifter.
| Component | Exact Variant / Specification | Est. Price |
|---|---|---|
| Microcontroller | Raspberry Pi 4 Model B (4GB RAM) | $55.00 |
| Relay Module | 4-Channel 5V Relay (Optocoupler Isolated, Active-LOW) | $7.50 |
| Power Supply | Official 5V 3A USB-C Power Supply (White/Black) | $8.00 |
| Wiring | 22 AWG Stranded Hookup Wire (Pre-crimped Dupont ends) | $6.00 |
| Protection | 1N4007 Flyback Diodes (if not pre-soldered on relay) | $2.00 |
Hardware Wiring & Pin Mapping
We are using Broadcom (BCM) pin numbering, not physical board pin numbers. The relay module is optocoupler-isolated, meaning the Pi's 3.3V logic triggers an internal LED, which switches the 5V relay coil. This protects your Pi's CPU from back-EMF spikes.
| Raspberry Pi Pin (BCM) | Physical Pin # | Relay Module Pin | Wire Color (Suggested) |
|---|---|---|---|
| GPIO 17 | 11 | IN1 | Orange |
| GPIO 27 | 13 | IN2 | Yellow |
| GPIO 22 | 15 | IN3 | Green |
| 5V Power | 2 | VCC | Red |
| Ground | 6 | GND | Black |
Python Environment & Voice Control Code
Before running the code, install the required libraries and enable the GPIO interface. Open your terminal and run:
sudo apt update && sudo apt install python3-rpi.gpio python3-pip
pip3 install sinricpro asyncio
You will need to create a free account at Sinric.pro, create a 'Switch' device, and copy your App Key, App Secret, and Device ID into the variables below. This service securely bridges your local Pi to the Alexa Smart Home Skill API without requiring you to host your own AWS Lambda functions.
import asyncio
import RPi.GPIO as GPIO
from sinricpro import SinricPro
from sinricpro.devices import SinricProSwitch
# --- PIN DEFINITIONS & CREDENTIALS ---
RELAY_PIN_BCM = 17 # Physical Pin 11
APP_KEY = 'YOUR_APP_KEY_HERE'
APP_SECRET = 'YOUR_APP_SECRET_HERE'
DEVICE_ID = 'YOUR_DEVICE_ID_HERE'
# --- GPIO SETUP ---
GPIO.setmode(GPIO.BCM)
GPIO.setup(RELAY_PIN_BCM, GPIO.OUT)
# Most 5V relay modules are Active-LOW. HIGH = Off, LOW = On.
GPIO.output(RELAY_PIN_BCM, GPIO.HIGH)
# --- CALLBACK HANDLERS ---
async def on_power_state(device_id: str, state: bool):
"""Handles Alexa 'Turn On' / 'Turn Off' commands."""
try:
if state:
GPIO.output(RELAY_PIN_BCM, GPIO.LOW) # Energize relay
print(f'Device {device_id} turned ON')
else:
GPIO.output(RELAY_PIN_BCM, GPIO.HIGH) # De-energize relay
print(f'Device {device_id} turned OFF')
return True, state
except Exception as e:
print(f'GPIO Execution Error: {e}')
return False, state
# --- MAIN EXECUTION LOOP ---
async def main():
switch = SinricProSwitch(DEVICE_ID)
switch.on_power_state(on_power_state)
sinricpro = SinricPro(APP_KEY, APP_SECRET)
sinricpro.add_device(switch)
try:
print('Connecting to Alexa Smart Home Bridge...')
await sinricpro.run()
except KeyboardInterrupt:
print('Manual interrupt received.')
except Exception as e:
print(f'Network or Auth Error: {e}')
finally:
# Critical: Clean up GPIO to prevent pin lockouts on restart
GPIO.cleanup()
print('GPIO cleaned up. Exiting safely.')
if __name__ == '__main__':
asyncio.run(main())
Debugging: First Three Things to Check When It Fails
When bridging local hardware to cloud voice assistants, failures usually happen at the network or logic boundary. If the Alexa app displays the exact toast notification "Device doesn't support this request" or your terminal logs "ERROR: websocket closed with code 1006: Abnormal Closure", follow this ranked diagnostic path.
The First Three Things to Check:
- Wi-Fi AP Isolation / Client Isolation: If your router has 'Guest Network' or 'AP Isolation' enabled, the Pi cannot maintain the persistent WebSocket connection to the bridge. Ensure the Pi is on your main LAN with client-to-client communication enabled.
- Active-LOW vs Active-HIGH Logic: If Alexa says the device is 'On' but the relay is off (or vice versa), your relay module logic is inverted. Swap
GPIO.HIGHandGPIO.LOWin theon_power_statecallback. - Credential Mismatch (App Key vs Secret): A 1006 Abnormal Closure immediately after connection usually means the App Key and App Secret are swapped in your Python variables, or the Device ID belongs to a different SinricPro account.
Ranked Causes for 'Device Doesn't Support This Request':
- Cause 1 (80%): The Alexa Smart Home Skill was not re-linked after adding the new device ID to your SinricPro dashboard. Go to the Alexa App > Skills > SinricPro > Disable, then Enable to force a device discovery.
- Cause 2 (15%): The Python script crashed silently due to a GPIO pin conflict. Run
sudo lsof | grep gpioto ensure no other service (like Home Assistant or a rogue cron job) is holding Pin 17. - Cause 3 (5%): The relay module's optocoupler LED has burned out. Measure the voltage across the IN1 and GND pins with a multimeter while triggering Alexa; if it stays at 3.3V instead of dropping to ~1.2V, the Pi is outputting correctly but the relay hardware is dead.
Extending and Simplifying the Build
How to Extend: To add environmental awareness, wire a DHT22 temperature sensor to GPIO 4. You can map the sensor data to an Alexa Temperature Sensor endpoint using the SinricProTemperatureSensor class. This allows you to ask, "Alexa, what is the server room temperature?" while retaining switch control.
How to Simplify: If writing custom Python scripts and managing WebSocket daemons feels like overkill, simplify the build by flashing Home Assistant OS onto a MicroSD card. Home Assistant includes a native 'Emulated Hue' or 'Alexa Smart Home' integration that handles the cloud linking via a GUI, allowing you to map Pi GPIO pins to Alexa using YAML configuration files instead of raw Python code.
Frequently Asked Questions
Can I connect Raspberry Pi to Alexa without an internet connection?
No, not natively using the Smart Home Skill API. Alexa's voice processing and the Smart Home API routing require an active internet connection to reach AWS servers. If you need strictly offline, local-network voice control, you must abandon Alexa and use a local voice satellite like Rhasspy or Mycroft paired with a local MQTT broker, though this sacrifices the commercial voice recognition accuracy of Alexa.
Why does my Raspberry Pi to Alexa relay click but the connected light doesn't turn on?
The 'click' confirms the 5V coil is energizing and the physical armature is moving. The failure is on the high-voltage (load) side. First, verify your load is wired to the COM (Common) and NO (Normally Open) terminals, not the NC (Normally Closed) terminal. Second, check the relay's contact rating; if you are switching an inductive load like a large motor or a cheap LED driver with a high inrush current, the contacts may have welded together or pitted, preventing proper current flow despite the mechanical click.
Is it safe to leave the Raspberry Pi to Alexa relay script running 24/7?
Running a Python script directly in the terminal via python3 script.py is not safe for 24/7 operation; if the SSH session drops or the terminal closes, the script dies and the GPIO pins may lock. For persistent operation, wrap the script in a systemd service. Create a file at /etc/systemd/system/alexa-relay.service, point the ExecStart to your Python path, and enable it with sudo systemctl enable alexa-relay. This ensures the script auto-restarts on boot and recovers from network drops via the Restart=always directive.






