Introduction: Cayenne, Python and MQTT Tutorials-2 - Digital Output

Turn on a LED or lamp or relay from anywhere with Cayenne IOT Dashboard.

This tutorial will show you how to turn a LED on and off from Cayenne IOT Dashboard.

Step 1: Wiring

You will need the following parts for this tutorial:

1x Raspberry Pi

2x male-female jumper wires

1x 560 ohm resistor

1x 10mm LED

You will need to connect the following pins to the LED and resistor:

Rasp. Pi GND to LED cathode (short leg)

Rasp. Pi Pin 17 to one leg of the 560 ohm resistor

LED anode (long leg) to the second leg of the 560 ohm resistor

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 Button Controller widget, click on:

  • Add new
  • Custom widgets
  • Button Controller 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 "message.channel" 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.

  • cayenne-mqtt

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.

messsage.channel is channel of Led widget and it is a integer.

message.value is value of received message from Cayenne and it is a string.

<p>import cayenne.client #Cayenne MQTT Client<br>from gpiozero import LED
led=LED(17) #Declaring button pin 17</p><p># 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 CLIENT ID"</p><p># The callback for when a message is received from Cayenne.
def on_message(message):
    print("message received: " + str(message))
    if message.channel==1: #Dashboard Led widget channel. They must be same. 
        if message.value=="1": #If led command "1", turn led on(message.value must be string)
            led.on()
        elif message.value=="0": #If led command "0", turn led off(message.value must be string)
            led.off()</p><p>client = cayenne.client.CayenneMQTTClient()
client.on_message = on_message #When message recieved from Cayenne run on_message function
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)</p><p>while True:
  client.loop()</p>

Step 6: Final Stage

This video shows final stage.