"This blog is about toggling LED on or off with a button click on a web page, from a phone or a desktop."
Happy New Year! I recently started exploring long pending IoT in my things to learn. I'm planning to document as tryout samples. As a Hello World I tried out blinking LED using a Raspberry Pi 2, took it little further, toggled LED on or off as you tap on a button in a web page.
Here is a quick demo-
Why Raspberry Pi?I've a choice (available with me) between Arduino and Raspberry Pi. With Arduino, I would need to buy additional WiFi module. Arduino can do one job at a time and it can do that well. It works great with direct sensor interactions, may it be temperature sensor, proximity sensor etc.
Raspberry Pi is a computer in it self. It comes with LAN cable connectivity, I could connect a 300 INR (5 USD appx) Wifi dongle and get it connected to Internet. I'm using Raspbian. Microsoft has Windows 10 IoT core which could be installed on a (micro) SD card and used with Raspberry Pi 2.
There is a choice of programing languages with Raspberry Pi. In this sample I'm using more popular Python.
Web Page that toggles LED
Just needed a central location on cloud to store on/off state. It could be anything. Firebase is a good solution for such things. And I believe it's a good platform for IoT going forward.
- Firebase is literally no setup, ready made cloud back-end.
- It's no schema and JSON data store.
- Easy to get and update data with REST API and setup security rules.
- It's backed by Google Cloud if you are thinking scalability.
I uploaded a simple page with button that flips a flag on Firebase as you click on the button. This page is deployed to Firebase hosting service. Raspberry Pi uses this flag, turns LED on if the value is true (and vice versa).
Raspberry Pi Setup
Raspberry Pi 2 has a 40 pin layout. Refer to below picture- pins are
- GPIO (General Purpose Input/Output) - could be used in code to set a value HIGH or LOW to interface with sensors and devices.
- 3.3 volts and 5 volts power
|Reference - http://www.element14.com/community/docs/DOC-73950/l/raspberry-pi-2-model-b-gpio-40-pin-block-pinout|
Here is the connection to LED. Positive on LED connects to Pin 7/GIPO04 and ground on LED connects to a resistor which in turn connects to ground on pin 06. Resistor is to make sure too much current doesn't get pass through the LED which could damage it.
import RPi.GPIO as GPIO
pin = 7
# Board mode is safer option to use with pin numbers matching between older and
# newer versions of Raspberry Pi, hence no confusion
client = http.client.HTTPSConnection('<< firebase URL>>')
httpResponse = client.getresponse()
dataStream = httpResponse.read()
dataString = str(dataStream, 'utf-8')
switchLedOn = json.loads(dataString)
# switchLedOn holds true/false as user toggles the switch
# with a button on the web page.
#retry after 2 seconds.
Complete sample is uploaded to Github. Happy Coding and Happy New Year.