Project tutorial
Create Your First Connected Light using Arduino Yun

Create Your First Connected Light using Arduino Yun © GPL3+

Control and monitor a connected light from mobile, tablet and desktop using Lelylan & MQTT.

  • 1,379 views
  • 0 comments
  • 0 respects

Components and supplies

Ard yun
Arduino Yun
×1
Momentary Push button
×10
Resistor Kit
×1
LEDs various colors 10mm
×20

Apps and online services

About this project

1. Software

To program your Arduino Yun, you need to install the Arduino IDE and the following libraries (if you do not know how to install a library checkout this tutorial).

PubSubClient

This is a fork of the original PubSubClient setting the max packet size to 512 bytes (needed for Lelylan to work).

2. Hardware Setup

The schematic represents the LED, resistor and push button setup. With this setup each time you press the button, the LED is turned on and off.

3. Lelylan Setup

Open Lelylan Dashboard and create a new device by following 3 simple steps (if you are new to Lelylan, you can sign up for free). 

  • Set a meaningful name (e.g. bedroom light). 
  • Choose the device type. For this tutorial choose Basic Light. 
  • Choose "Connect with MQTT" as connectivity option.

Once the device is created, click the settings link (placed under the device name) and get the device ID and device secret. You'll need them in the next section.

4. Code

Once the (virtual) device is defined on Lelylan you need to make it communicate with Arduino. Copy the sketch below in the code section and change the following variables: deviceIddeviceSecretoutTopic, inTopic and clientId. It will not take more than one minute.

5. You are done

Access Lelylan Dashboard and control your connected light from mobile, tablet and desktop. If any problem occurs, let @lelylan know. For more details, checkout the code explenation section in the original article.

Code

Code snippet #1Arduino
#include <SPI.h>
#include <YunClient.h>
#include <PubSubClient.h>
/* ------------------ */
/* SKETCH CREDENTIALS */
/* ------------------ */
char* deviceId     = "<DEVICE-ID>";             // * set your device id (will be the MQTT client username)
char* deviceSecret = "<DEVICE-SECRET>";         // * set your device secret (will be the MQTT client password)
char* outTopic     = "devices/<DEVICE-ID>/set"; // * MQTT channel where physical updates are published
char* inTopic      = "devices/<DEVICE-ID>/get"; // * MQTT channel where lelylan updates are received
char* clientId     = "<CLIENT-ID>";             // * set a random string (max 23 chars, will be the MQTT client id)
/* ------------ */
/* SKETCH LOGIC */
/* ------------ */
/* Server settings */
byte server[] = { 96, 126, 109, 170 }; // MQTT server address
/* Sample payload published to lelylan */
/* The id is the status property id of the basic light /*
/* http://lelylan.github.io/types-dashboard-ng/#/types/518be107ef539711af000001/ */ 
char* payloadOn  = "{\"properties\":[{\"id\":\"518be5a700045e1521000001\",\"value\":\"on\"}]}";
char* payloadOff = "{\"properties\":[{\"id\":\"518be5a700045e1521000001\",\"value\":\"off\"}]}";
/* Yun configuration */
byte mac[] = { 0xA0, 0xA0, 0xBA, 0xAC, 0xAE, 0x12 };
YunClient yun;
/* MQTT communication */
void callback(char* topic, byte* payload, unsigned int length); // subscription callback
PubSubClient client(server, 1883, callback, yun);         // mqtt client
/* Pins configuration */
int inPin = 3; // button
int outPin = 13; // led
/* Button and led logics */
int state = HIGH;     // current state of the output pin
int reading;          // current reading from the input pin
int previous = LOW;   // previous reading from the input pin
long time = 0;        // the last time the output pin was toggled
long debounce = 200;  // the debounce time, increase if the output flickers
/* arduino setup */
void setup() {
  Serial.begin(9600);
  delay(500);
  Serial.println("Start initialization of Yun...");
  Bridge.begin();
  Serial.println("Bridge finished setup");
  Serial.println("Starting connection to lelylan...");
  lelylanConnection();      // MQTT server connection
  pinMode(inPin, INPUT);    // button pin setup
  pinMode(outPin, OUTPUT);  // led pin setup
}
/* arduino loop */
void loop() {
  lelylanConnection();
  char* value;
  reading = digitalRead(inPin);  // read the button state
  // if the input just went from LOW and HIGH and we've waited long enough to ignore
  // any noise on the circuit, toggle the output pin and remember the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == LOW) {
      Serial.println("[PHYSICAL] Led turned on");
      lelylanPublish("on");
      state = HIGH;
    } else {
      Serial.println("[PHYSICAL] Led turned off");
      lelylanPublish("off");
      state = LOW;
    }
    time = millis();
  }
  // effectively update the light status
  digitalWrite(outPin, state);
  previous = reading;
}
/* MQTT server connection */
void lelylanConnection() {
  // add reconnection logics
  if (!client.connected()) {
    // connection to MQTT server
    if (client.connect(clientId, deviceId, deviceSecret)) {
      Serial.println("[PHYSICAL] Successfully connected with MQTT");
      lelylanSubscribe(); // topic subscription
    }
  }
  client.loop();
}
/* MQTT publish */
void lelylanPublish(char* value) {
  if (value == "on")
    client.publish(outTopic, payloadOn); // light on
  else
    client.publish(outTopic, payloadOff); // light off
}
/* MQTT subscribe */
void lelylanSubscribe() {
  client.subscribe(inTopic);
}
/* Receive Lelylan message and confirm the physical change */
void callback(char* topic, byte* payload, unsigned int length) {
  // copu the payload content into a char*
  char* json;
  json = (char*) malloc(length + 1);
  memcpy(json, payload, length);
  json[length] = '\0';
  // update the physical status and confirm the executed update
  if (String(payloadOn) == String(json)) {
    Serial.println("[LELYLAN] Led turned on");
    lelylanPublish("on");
    state = HIGH;
  } else {
    Serial.println("[LELYLAN] Led turned off");
    lelylanPublish("off");
    state = LOW;
  }
  digitalWrite(outPin, state);
  free(json);
}
Github
https://github.com/andreareginato/pubsubclient

Schematics

Schematic #1
750x750 548eb60ba73ac4 tgeqtqxh5a

Comments

Similar projects you might like

Yun Light

Project tutorial by Tony ZHANG

  • 6,811 views
  • 3 comments
  • 25 respects

Controlling LED light intensity using smartphone light senso

Project tutorial by Nikola Travis

  • 1,758 views
  • 0 comments
  • 3 respects

Ultrasonic Map-Maker using an Arduino Yun

Project tutorial by Satyavrat Wagle

  • 51,960 views
  • 37 comments
  • 152 respects

Control your light with Arduino

Project tutorial by GiorgioTraverso

  • 1,807 views
  • 0 comments
  • 2 respects

The "Tennis Ball" Garage Stop Light

Project tutorial by Team Stuart Mace

  • 9,656 views
  • 2 comments
  • 36 respects

Secure YUN

Project tutorial by Abhishek

  • 1,547 views
  • 1 comment
  • 12 respects
Add projectSign up / Login