Introduction: Cayenne, Python and MQTT Tutorials-1 - Digital Input
This guide is part of a series of guides that cover the basics of using Cayenne with Raspberry Pi, Python and MQTT.
This tutorial show you how to send momentary button press digital data to Cayenne IO Dashboard by using Python and MQTT.
Step 1: Wiring
You will need the following parts for this tutorial:
- 1x Raspberry Pi
- 1x momentary button
- 2x male-female jumper wires
You need to connect these pins:
- Rpi ground to one side of the momentary button
- Rpi pin 2 to other side of the momentary button
Step 2: Sign Up!
To use Cayenne IOT Dashboard, you need to sign up Cayenne from the website.
Step 3: Selecting Device
After log in, Select "Bring Your Own Thing".
A window will pop up with MQTT and your Client details. You will use these informations in Python script. When you connect Cayenne MQTT Broker by running Python script, you will direct to Dashboard.
Step 4: Adding Widget
To add 2-State widget, click on:
- Add new
- Custom widgets
- 2-State Display Widget
Then fill widget infos and click on Add Widget. You can change widget infos later on widget.
Note: Channnel number must be same as in Python script.
Step 5: Python Code
You need to install this library for Python script. It is MQTT library to communicate RPİ and Cayenne IOT Broker.
This library can be installed using pip and pip3:
pip install cayenne-mqtt (for Python2)
pip3 install cayenne-mqtt (for Python3) >>>for this tutorial.
Note: In the script, you must modify your MQTT credentials and widget channel.
import cayenne.client #Cayenne MQTT Client
from time import sleep from gpiozero import Button button=Button(2) # Declaring button pin 2
# Cayenne authentication info. This should be obtained from the Cayenne Dashboard. MQTT_USERNAME = "YOUR MQTT USERNAME" MQTT_PASSWORD = "YOUR MQTT PASSWORD " MQTT_CLIENT_ID = "YOUR CLİENT ID"
client = cayenne.client.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)
def send_on(): client.virtualWrite(3, 1) #Publish "1" to Cayenne MQTT Broker Channel 3 print("Button pressed\n")
def send_off(): client.virtualWrite(3, 0) #Publish "0" to Cayenne MQTT Broker Channel 3 print("Button released\n")
button.when_pressed=send_on #When button pressed run send_on function button.when_released=send_off #When button released run send_off function while True: client.loop()
After run the script, you will connect to Cayenne MQTT Broker.
Press and release the button. Button state widget changes the value.
Step 6: IFTT Integration
If you want to take notification by e-mail or SMS
To use IFTT in Cayenne:
- Create new trigger from "Add new" then give it a name
- Drag device to first space and select Button State.
- Choose "1" ( if you want to take notification when button pressed)
- Click on "add custom recipent" and "send e-mail".
- Finally "Save it"
Press the momentary button and check your e-mail.
This video shows final stage.