Screenshot 2014-04-20 21.16.11

Make an LED light blink on your Raspberry Pi from your Corona SDK app

Screenshot 2014-04-20 21.16.11Today I want to continue my work to connect my Corona app to my Raspberry Pi, making an LED light blink on my Raspberry Pi’s breadboard setup when I press a colored circle on my Corona app on my simulator. This way, I can play “red light / green light” from the comfort of my couch, while lights light up on my Raspberry Pi in another room. I’m sure I’ll find a use for this demo some day :)

This tutorial builds on my previous work with lua and Raspberry Pi. You need to have your Pi set up with LED lights ready to blink red and green as described in that tutorial. This time, however, we’re not going to use Mihini to hook directly to the Pi except for convenience; we are instead going to have our Corona app talk to an MQTT installation in the cloud, namely the convenient open source portal set up by the Eclipse foundation at iot.eclipse.org. You can post right to this portal without even needing an API key; it’s extremely easy and intuitive.

First though, you need to get Corona to understand MQTT. MQTT is Message Queuing Telemetry Transport (MQTT) and is a protocol designed to connect the physical world devices and networks, with applications and middleware used in IT and Web development, making it an ideal connectivity protocol for IoT and M2M. Per Eclipse: “It is a lightweight publish-subscribe protocol that runs on embedded devices and mobile platforms, while connecting to highly scalable enterprise and web servers over wired and wireless networks. It is useful for connections with remote embedded systems where a small code footprint is required and/or network bandwidth is at a premium or connectivity unpredictable, and, for mobile applications that require small size, low power usage, minimised data packets, and efficient distribution of information to one or many receivers.” (http://iot.eclipse.org/protocols.html). For our purposes, we are going to use it to get our Pi to send and receive little messages, and our Corona app to do the same. Specifically, the Corona app is going to send a signal to a topic, which I call “jen” and send a payload, which will either be “red” or “green”, to tell the Pi what light to blink.

Here’s the codebase for the Corona project. Again, props to Jesse Warden and Benjamin Cabé who got me started in the right direction!

The Corona codebase is very simple. You need to include an MQTT folder with two files inside: matt_library.lua and utility.lua; this allows the Corona app to ping an MQTT server and both send payloads and watch for them to be received at the same time. In main.lua, I have simply included that library and then invoked a few commands:

create a client by contacting iot.eclipse.org, connect your mobile device to it, and subscribe to a topic called ‘jen’ which is generated on the fly:

mqtt_client = MQTT.client.create("iot.eclipse.org", 1883, callback)
mqtt_client:connect(system.getInfo( "deviceID" ))
mqtt_client.KEEP_ALIVE_TIME = 120
mqtt_client:subscribe({ "/jen" })

You can do the same, but I recommend creating a new topic so that it won’t collide with mine.

Then, I drew a red and green circle and added a touch event, differentiating between its color and publishing a payload of either ‘red’ or ‘green’ to the ‘jen’ topic:

local function onTouch( event )
    if event.phase == "ended" then
        print(event.target.id)
        if event.target.id == "red" then
          mqtt_client:publish("/jen", "red")  
        else
          mqtt_client:publish("/jen", "green")
        end
        return true
    end
end

You can run your Corona sim to see this code in action – in debug mode, you can watch the payload being published.

Now, you need the Raspberry Pi to subscribe to this topic, listen for these payloads to be sent, consume them and do something with them. For this to happen, we have to do a few more installations on the Pi, namely an MQTT broker called Mosquitto on the Pi.

Here are the instructions in full.

Now, you need to place a small Python script onto your Pi and run it as root so it can control the GPIO pins:

import mosquitto
import RPi.GPIO as GPIO
import time
 
topic_names = []
 
redLedPin=24
greenLedPin=25
GPIO.setmode(GPIO.BCM)
GPIO.setup(redLedPin,GPIO.OUT)
GPIO.setup(greenLedPin,GPIO.OUT)
 
def red():
	GPIO.output(redLedPin,1)
	time.sleep(0.2)
	GPIO.output(redLedPin,0)
	time.sleep(0.2)
 
def green():
	GPIO.output(greenLedPin,1)
	time.sleep(0.5)
	GPIO.output(greenLedPin,0)
	time.sleep(0.2)
 
def on_message(mqttc, obj, msg,):
    payload = str(msg.payload)
    print(msg.topic + " Payload is " + payload)
    if payload == 'green':
        green()
    elif payload == 'red':
        red()
    else:
        time.sleep(0.5)
    topic_names.append(msg.topic)
 
try:
    mqttc = mosquitto.Mosquitto()
    mqttc.on_message = on_message
 
    mqttc.connect("iot.eclipse.org", 1883, 60)
    mqttc.subscribe("jen", 0)
 
    mqttc.loop_forever()
 
except KeyboardInterrupt:
    print "Received topics:"
    for topic in topic_names:
        print topic

I named this file mqtt.py.

Here, we have the Python script listening for changes to the topic “jen”. If “green” comes through in a payload, blink the green led, and blink the red led for “red” in the payload.

Lastly, making sure that mosquitto is running on the Pi, run your Python script:

sudo python mqtt.py

Go back to your Corona simulator and touch either the red or green circle. Does the right LED light up? If so, you did it!

Leave a Reply