PIR example

The code above will show if PIR detector detect any movement.

/*
 * IoT PIR example
 *
 * This example subscribe to the "pir" topic. When a message received, then it
 * will switch the pir module "ON" and "OFF"
 *
 * Created 21 Febuary 2018 by Heiko Pikner and Mallor Kingsepp
 */
 
#include <Arduino.h>
#include <ittiot.h>
 
//Pin definition for the pir (GPIO14)
#define PIR_PIN D5
//Pin definition for the pir LED (GPIO16)
#define PIR_LED_PIN D4
 
// PIR state for detection
bool pirState;
// State that switches PIR on and off
bool onState;
 
// If message received for PIR topic. For example:
// mosquitto_pub -u test -P test -t "ITT/IOT/3/pir" -m "1"
void iot_received(String topic, String msg)
{
  Serial.print("MSG FROM USER callback, topic: ");
  Serial.print(topic);
  Serial.print(" payload: ");
  Serial.println(msg);
  if(msg == "1")
  {
	onState = true;
  }
 
  if(msg == "0")
  {
	onState = false;
  }
}
 
// Function started after the connection to the server is established.
void iot_connected()
{
  Serial.println("MQTT connected callback");
  // Subscribe to the topic "pir"
  iot.subscribe("pir");
  iot.log("IoT PIR example!");
}
 
void setup()
{
  Serial.begin(115200);
  Serial.println("Booting");
 
  // Print json config to serial
  iot.printConfig();
  // Initialize IoT library
  iot.setup();
  // Initialize relay pin
  pinMode(PIR_PIN, INPUT);
  pinMode(PIR_LED_PIN, OUTPUT);
}
 
void loop()
{
  // IoT behind the plan work, it should be periodically called
  iot.handle();
  delay(200);
 
if(onState == true){
 
  if(digitalRead(PIR_PIN))
  {
    if(pirState == false)
    {
      digitalWrite(PIR_LED_PIN, HIGH);
      String msg = String("Motion detected!");
      iot.publishMsg("pir", msg.c_str());
      //Serial.println(msg);
      pirState = true;
    }
  }
  else
  {
    if(pirState == true)
    {
      digitalWrite(PIR_LED_PIN, LOW);
      pirState = false;
    }
  }
 }
else{
   iot.log("PIR offline");
  delay(2000);
}
}
en/iot/examples/pir.txt · Last modified: 2018/03/20 10:57 by Somepub
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0