Kuncono Liem
Published © GPL3+

Simple IoT Auto Light with Motion Sensor and Cayenne

I want to turn on the light automatically when I'm entering a room, and when I leave the room I can turn it off using my cellphone.

BeginnerShowcase (no instructions)1 hour1,893
Simple IoT Auto Light with Motion Sensor and Cayenne

Things used in this project

Hardware components

NodeMCU ESP8266 Breakout Board
NodeMCU ESP8266 Breakout Board
×1
PIR Motion Sensor (generic)
PIR Motion Sensor (generic)
×1
Relay (generic)
×1

Software apps and online services

Arduino IDE
Arduino IDE
Cayenne
myDevices Cayenne

Story

Read more

Code

PIR_LIGHT.ino

C/C++
#define CAYENNE_PRINT Serial  // Comment this out to disable prints and save space
#include "CayenneDefines.h"
#include "CayenneWiFi.h"
#include "CayenneWiFiClient.h"
#define RELAY_PIN 5

// Cayenne authentication token. This should be obtained from the Cayenne Dashboard.
char token[] = ""; // Insert your token here
char ssid[] = ""; // Insert your SSID here
char pwd[] = ""; // Insert your SSID password here

// Virtual Pin of the Digital Motion Sensor widget.
#define VIRTUAL_PIN V12

// Digital pin the motion sensor is connected to. Do not use digital pins 0 or 1 since those conflict with the use of Serial.
const int motionSensorPin = 4;

void setup()
{
  Serial.begin(115200);
  Cayenne.begin(token, ssid, pwd);
  pinMode(RELAY_PIN, OUTPUT);

}

void loop()
{
  Cayenne.run();
  checkSensor();
}

int previousState = -1;
int currentState = -1;
unsigned long previousMillis = 0;

void checkSensor()
{
  unsigned long currentMillis = millis();
  // Check sensor data every 250 milliseconds
  if (currentMillis - previousMillis >= 250) {
    // Check the sensor state and send data when it changes.
    currentState = digitalRead(motionSensorPin);
    if (currentState != previousState) {
      Cayenne.virtualWrite(VIRTUAL_PIN, currentState);
      previousState = currentState;
    }
        previousMillis = currentMillis;
  }
}

CAYENNE_IN(V21)
{
  // get value sent from dashboard
  int currentValue = getValue.asInt(); // 0 to 1

  // assuming you wire your relay as normally open
  if (currentValue == 0) {
    digitalWrite(RELAY_PIN, HIGH);
  } else {
    digitalWrite(RELAY_PIN, LOW);
  }
}

Credits

Kuncono Liem

Kuncono Liem

7 projects • 9 followers

Comments