Introduction: HomeKit HomeBridge Siri Enabled Arduino ESP8266 NodeMCU Based PIR Motion Sensor for HomeKit Automation

About: I'm a lot of things. Galen Wollenberg https://hackaday.io/projects/hacker/246423 https://www.hackster.io/LagunaComputer

HomeKit HomeBridge Siri Enabled Arduino ESP8266 NodeMCU Based PIR Motion Sensor for HomeKit Automation

by Galen Wollenberg

Build custom Motion Sensors for home automation via Siri / HomeKit / HomeBridge using NodeMCU/ESP8266/arduino microcontroller, and a HC-SR501 PIR Motion Sensor.

I can put one of each of these in each room, and then use the iOs 'Eve' app to publish automatic HomeKit Automation rules and triggers. I.E.: "if is motion detected in the bedroom, automatically turn on the Bedroom lights".

This can be combined with my CurrentAmbientLighLevel plugin, and the DS18B20 or DHT11/DHT22 plugins (or HttpTemperatureHum plugin) to make a super room sensor for HomeKit / HomeBridge.

Step 1: ​Install HomeBridge for HomeKit on a Raspberry Pi

Install HomeBridge for HomeKit on a Raspberry Pi

Test that HomeBridge and HomeKit is working on your iPhone.

See: https://github.com/nfarina/homebridge

https://github.com/nfarina/homebridge/wiki/Runnin...

https://github.com/nfarina/homebridge

Ensure these plugin are installed. It may be installed by default in the newer versions:

https://github.com/lucacri/homebridge-http-temper...

https://github.com/lagunacomputer/homebridge-Motio...

sudo npm install -g https://www.npmjs.com/package/homebridge-MotionSensor

Step 2: Parts Needed:

Parts Needed:

1x HomeBridge installed on a Raspberry Pi and working.

1x NodeMCU module

1x HC-SR501 PIR motion sensor

1x DHT11 or DHT22 temp/humidity sensor.

1x 10k ohm Photocell resistor

1x 4.7 k resistor (5k potentiometer used here to adjust light input sensitivity)

1x 2"x1.5" perf board

1x small piece of wire

1x 5v USB charger (i find the iPhone adapters to be the smallest and best)

1x usb cable end with exposed wires

Step 3: Build It

Build it

Pictured above is a sample connection of the motion sensor and a NodeMCU. We want to use a different pin than pictured above (or change the Arduino IDE code). see below.

Pictured above is a few sensors I have made with the addition of a photocell and potientiometer to adjust the light sensor sensitivity. Also pictured is an optional DS18B20 temperature sensor module. See my other Instructables if you are interested in adding the other sensors.

HC-SR501 data pin goes to NodeMCU D4 pin. check the sample Arduino code to make sure it matches the pin used in the code. For the older code, NodeMCU Digital Pin 1, set the Arduino Code to "int pirpin = 5" . This is because the NodeMCU pins map out to different GPIO#'s in reality. Google Images search "nodemcu pinout" to see a chart with the correct PIN to GPIO mappings.

HC-SR501 data pin goes to NodeMCU D4 pin

USB cable +5 & HC-SR501 VCC goes to NodeMCU Vin pin

USB cable -GND & HC-SR501 GND goes to NodeMCU GND

Photocell to A0

Step 4: Edit the HomeBridge /var/homebridge/config.json File on the Raspberry Pi HomeBridge

Edit the HomeBridge /var/homebridge/config.json file on the Raspberry Pi HomeBridge

the file may alternatively be in /home/.homebridge or /root/home/./homebridge.

read the docs from the github link
https://github.com/nfarina/homebridge

Ensure this plugin is installed. It may be installed by default in the newer versions:

https://github.com/lagunacomputer/homebridge-Motio...

https://github.com/nfarina/homebridge https://github.com/lagunacomputer/homebridge-Curr...

Program the NodeMCU using the Arduino IDE.

Upon powering up (5V!) it should be seen on the network.

Try something like http://192.168.1.101/ .

You should get a webpage returned.

Assuming your NodeMCU pulls a DHCP ip of :192.168.1.101 (you should probably set a DHCP reservation on your router, for each ESP8266 you add) add this code to the config.json file.

( sudo nano /var/homebridge/config.json) etc:

{

"bridge": {
"name": "HomeBridge",
"username": "CC:22:3D:E3:CE:30",
"port": 51826,
"pin": "031-45-154"


},

"description": "", 

"accessories": [
    {
        "accessory": "Motion",
        "name": "Motion Sensor",
        "url": "http://192.168.1.101/?light",
        "sendimmediately": "",
        "http_method": "GET"
    }
]

"platforms": []
}

mind the last comma, you may or may not need it if you have other accessories, or Homebridge is crashing on load.

Step 5: Program NodeMCU / ESP8266 / Arduino With Code

Program

*NEW IMPROVED CODE NodeMCU / ESP8266 / Arduino IDE ( faster, lighter, better, stronger):

Use digital Pin d4 for the motion sensor, D6 for DHT, and photocell=A0 with this code:

<p>#include <br>byte mac[] = { 0x5C, 0xCF, 0x7F, 0xC1, 0x1A, 0x33 };</p><p>int photocellPin = 0;     // the cell and 10K pulldown are connected to a0
int photocellReading;     // the analog reading from the analog resistor divider</p><p>#include 
#define DHT11Pin D6</p><p>/////////////////////////////
//VARS
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 30;        </p><p>//the time when the sensor outputs a low impulse
long unsigned int lowIn;         </p><p>//the amount of milliseconds the sensor has to be low 
//before we assume all motion has stopped
long unsigned int pause = 5000;  </p><p>boolean lockLow = true;
boolean takeLowTime;  </p><p>int pirPin = 4;    //the digital pin connected to the PIR sensor's output
int ledPin = 13;</p><p>#include </p><p>IPAddress ip(192, 168, 1, 147); 
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);</p><p>const char* ssid = "IWILLSTEALYOURMONEY";
const char* password = "namnamnewnew";</p><p>// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);</p><p>DHT dht(DHT11Pin, DHT11);
unsigned long previousMillis = 0;        // will store last temp was read
const long interval = 2000;   </p><p>/////////////////////////////
//SETUP
void setup(){
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(pirPin, LOW);</p><p>WiFi.begin(ssid, password);
//WiFi.config(ip, gateway, subnet);
while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    //WiFi.begin(ssid, password);
    //Serial.print(".");
  }
  //Serial.println("");
  //Serial.println("WiFi connected");
  
  // Start the server
  server.begin();
  //Serial.println("Server started");
Serial.println("");
  // Print the IP address
  Serial.println(WiFi.localIP());</p><p>  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(1000);
      }
    Serial.println(" done");
    Serial.println("SENSOR ACTIVE");
    delay(50);</p><p>  }
  
 </p><p>  // get humidity
  float humidity = dht.readHumidity();
  // get temperature as C
  float celsius = dht.readTemperature();
  // get temperature as F
  float fahrenheit = dht.readTemperature(true);</p><p>// prepare a web page to be send to a client (web browser)
String prepareHtmlPage()
{
  //gettemperature(); 
  String htmlPage = 
     String("HTTP/1.1 200 OK\r\n") +
            "Content-Type: application/json;charset=utf-8\r\n" +
            "Connection: close\r\n" +  // the connection will be closed after completion of the response
            "Refresh: 5\r\n" +  // refresh the page automatically every 5 sec
            "\r\n" +
            //"" +
            //"
" +
            "{" + "\"lightval\":" + String(analogRead(A0)) + "," + "\"pirval\":" + String(digitalRead(D4)) + "," + "\"temperature\":" + float(dht.readTemperature()) + "," + "\"fahrenheit\":" + float(dht.readTemperature(true)) + "," + "\"humidity\":" + float(dht.readHumidity()) + "}" +
            //"</p><p>" +
            "\r\n";
  return htmlPage;
}</p><p>////////////////////////////
//LOOP
void loop(){</p><p>readPhotocell();</p><p>//delay(10000);
  // get humidity
  float humidity = dht.readHumidity();
  // get temperature as C
  float celsius = dht.readTemperature();
  // get temperature as F
  float fahrenheit = dht.readTemperature(true);
  // print results
  Serial.print("Humidity: "); Serial.print(humidity);
  Serial.print(" Celsius: "); Serial.print(celsius);
  Serial.print(" Fahrenheit: "); Serial.println(fahrenheit);</p><p>     if(digitalRead(pirPin) == HIGH){
       digitalWrite(ledPin, HIGH);   //the led visualizes the sensors output pin state
       if(lockLow){  
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow = false;            
         Serial.println("---");
         Serial.print("motion detected at ");
         Serial.print(millis()/1000);
         Serial.println(" sec"); 
         delay(50);
         }         
         takeLowTime = true;
       } ////high</p><p>     if(digitalRead(pirPin) == LOW){       
       digitalWrite(ledPin, LOW);  //the led visualizes the sensors output pin state</p><p>       if(takeLowTime){
        lowIn = millis();          //save the time of the transition from high to LOW
        takeLowTime = false;       //make sure this is only done at the start of a LOW phase
        }
       //if the sensor is low for more than the given pause, 
       //we assume that no more motion is going to happen
       if(!lockLow && millis() - lowIn > pause){  
           //makes sure this block of code is only executed again after 
           //a new motion sequence has been detected
           lockLow = true;                        
           Serial.print("motion ended at ");      //output
           Serial.print((millis() - pause)/1000);
           Serial.println(" sec");
           delay(50);
           }
       }    //low</p><p>  WiFiClient client = server.available(); 
  // wait for a client (web browser) to connect
  if (client)
  {
    Serial.println("\n[Client connected]");
    while (client.connected())
    {
      // read line by line what the client (web browser) is requesting
      if (client.available())
      {
        String line = client.readStringUntil('\r');
        Serial.print(line);
        // wait for end of client's request, that is marked with an empty line
        if (line.length() == 1 && line[0] == '\n')
        {
          client.println(prepareHtmlPage());
          break;
        }
      }
    }
    delay(1); // give the web browser time to receive the data</p><p>    // close the connection:
    client.stop();
    Serial.println("[Client disonnected]");
  }</p><p>       
  }   //loop</p><p>void readPhotocell(){</p><p>photocellReading = analogRead(photocellPin);  
 Serial.print(WiFi.localIP());
  Serial.print(" Analog reading = ");
  Serial.print(photocellReading);     // the raw analog reading</p><p>  // We'll have a few threshholds, qualitatively determined
  if (photocellReading < 10) {
    Serial.println(" - Dark");
  } else if (photocellReading < 200) {
    Serial.println(" - Dim");
  } else if (photocellReading < 500) {
    Serial.println(" - Light");
  } else if (photocellReading < 800) {
    Serial.println(" - Bright");
  } else {
    Serial.println(" - Very bright");
  }
          
}</p><p>/*
void gettemperature() {
  // Wait at least 2 seconds seconds between measurements.
  // if the difference between the current time and last time you read
  // the sensor is bigger than the interval you set, read the sensor
  // Works better than delay for things happening elsewhere also
  unsigned long currentMillis = millis();
 
  if(currentMillis - previousMillis >= interval) {
    // save the last time you read the sensor 
    previousMillis = currentMillis;   
 
    // Reading temperature for humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
    humidity = dht.readHumidity();          // Read humidity (percent)
    celsius = dht.readTemperature();     // Read temperature as Fahrenheit
    fahrenheit = dht.readTemperature(true);     // Read temperature as Fahrenheit
    // Check if any reads failed and exit early (to try again).
    if (isnan(humidity) || isnan(fahrenheit)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }
  }
}</p><p>*/</p><br>

NodeMCU / ESP8266 / Arduino IDE Code version:

<p>#include <br>//#include </p><p>//byte mac[] = { 0x5C, 0xCF, 0x7F, 0x24, 0x84, 0x3D }; //physical mac address
//byte mac[] = { 0x5C, 0xCF, 0x7F, 0x24, 0x84, 0x3D }; //physical mac address
byte mac[] = { 0x5C, 0xCF, 0x7F, 0x24, 0x66, 0x69 }; //physical mac address
//byte ip[] = { 192, 168, 1, 133 }; // ip in lan
//byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
//byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
//EthernetServer server(80); //server port</p><p>String readString; </p><p>#include 
#include </p><p>/*-----( Declare Constants )-----*/
#define ONE_WIRE_BUS D4 /*-(Connect to Pin 2 )-*</p><p>*-----( Declare objects )-----*/
/* Set up a oneWire instance to communicate with any OneWire device*/
OneWire ourWire(ONE_WIRE_BUS);</p><p>/* Tell Dallas Temperature Library to use oneWire Library */
DallasTemperature sensors(&ourWire);</p><p>/*-----( Declare Variables )-----*</p><p>/////////////////////</p><p>int photocellPin = 0;     // the cell and 10K pulldown are connected to a0
int photocellReading;     // the analog reading from the analog resistor divider</p><p>boolean pirReading = false; 
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 30;</p><p>//the time when the sensor outputs a low impulse
long unsigned int lowIn;</p><p>//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;</p><p>boolean lockLow = true;
boolean takeLowTime;
int pirPin = 4;    //the digital pin connected to the PIR sensor's output</p><p>#include </p><p>IPAddress ip(192, 168, 1, 133); 
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);</p><p>const char* ssid = "IWILLSTEALYOURMONEY";
const char* password = "namnamnewnew";</p><p>// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);</p><p>#include 
dht DHT;
#define DHT11_PIN D6</p><p>void setup(){
Serial.begin(115200);
  pinMode(5, OUTPUT); //pin selected to control
  //start Ethernet
  //Ethernet.begin(mac, ip, gateway, gateway, subnet);</p><p>WiFi.begin(ssid, password);
//WiFi.config(ip, gateway, subnet);
while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    //WiFi.begin(ssid, password);
    //Serial.print(".");
  }
  //Serial.println("");
  //Serial.println("WiFi connected");
  
  // Start the server
  server.begin();
  //Serial.println("Server started");</p><p>  // Print the IP address
  Serial.println(WiFi.localIP());</p><p>  
  //server.begin();
  //enable serial data print 
  //Serial.begin(9600); </p><p>sensors.begin();</p><p>  pinMode(pirPin, INPUT);  ///PIR
    digitalWrite(pirPin, LOW);
  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(1000);
      }
    Serial.println(" done");
    Serial.println("SENSOR ACTIVE");
    delay(50);
}</p><p>void loop(){
readPIR();
readPhotocell();
//int chk = DHT.read11(DHT11_PIN);
//Serial.print(DHT.humidity);</p><p>float temperatureIndoor;
  float temperatureOutdoor;
  float humidity;
  sensors.requestTemperatures(); // Send the command to get temperatures
          temperatureIndoor = (sensors.getTempCByIndex(0));
  delay(100);
  // Create a client connection
  //EthernetClient client = server.available();
  WiFiClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();</p><p>        //read char by char HTTP request
        if (readString.length() < 100) {</p><p>          //store characters to string 
          readString += c; 
          //Serial.print(c);
        } </p><p>        //if HTTP request has ended
        if (c == '\n') {</p><p>          ///////////////
        </p><p>   /////original code for dht
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json;charset=utf-8");
          client.println("Server: Arduino");
          client.println("Connnection: close");
          client.println();
          //sensors.requestTemperatures(); // Send the command to get temperatures
          //temperatureIndoor = (sensors.getTempCByIndex(0));
          //temperatureOutdoor = (sensors.getTempFByIndex(0));
 //Serial.print(sensors.getTempCByIndex(0));</p><p> humidity = (DHT.humidity);
          client.print("{");
          client.print("\"temperature\":");
          client.print(temperatureIndoor);
          client.print(",");
          client.print("\"humidity\":");
          client.print(humidity);
          
          //client.print("}");
          //client.println();
             
          
         client.print(",");
          //client.print("{");
          client.print("\"lightval\":");
          client.print(photocellReading);
          client.print("}");
          client.println();
     
 original code for dht
*/</p><p>          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json;charset=utf-8");
          client.println("Server: Arduino");
          client.println("Connnection: close");
          client.println();
          sensors.requestTemperatures(); // Send the command to get temperatures
          temperatureIndoor = (sensors.getTempCByIndex(0));
          //temperatureOutdoor = (sensors.getTempFByIndex(0));
 
          client.print("{");
          client.print("\"temperature\":");
          client.print(temperatureIndoor);
          client.print(",");
          //client.print("\"humidity\":");
          //client.print(temperatureOutdoor);
          
          //client.print("}");
          //client.println();
       
          //client.print(",");
          //client.print("{");
          client.print("\"lightval\":");
          client.print(photocellReading);
          client.print(",");
client.print("\"pirval\":");
          client.print(pirReading);
//client.print("True");</p><p>          
          client.print("}");
          client.println();</p><p>          //stopping client
          client.stop();</p><p>          ///////////////////// control arduino pin
          if(readString.indexOf("?on") >0)//checks for on
          {
            Serial.println(readString.indexOf("on"));
            
            digitalWrite(5, HIGH);    // set pin 5 high
            Serial.println("Led On");</p><p>          }
          if(readString.indexOf("?off") >0)//checks for off
          {
            Serial.println(readString.indexOf("off"));
            digitalWrite(5, LOW);    // set pin 5 low
            Serial.println("Led Off");
          }
          if(readString.indexOf("?temp") >0)//checks for off
          {
            Serial.println(readString.indexOf("temp"));</p><p>            temperatureIndoor = (sensors.getTempCByIndex(0));
       
            //digitalWrite(5, LOW);    // set pin 5 low
            Serial.println("temp sent");
          }
          if(readString.indexOf("?light") >0)//checks for off
          {
            Serial.println(readString.indexOf("light"));</p><p>       
            //digitalWrite(5, LOW);    // set pin 5 low
            Serial.println("light sent");
          }</p><p>         
          //clearing string for next read
          readString="";</p><p>//sensors.requestTemperatures(); // Send the command to get temperatures
//Serial.print("Device 1 (index 0) = ");
//Serial.print(sensors.getTempFByIndex(0));
//Serial.println(" Degrees F");</p><p>        }                     ///c=n
      }                //client available
    }             //client connected
  }         //if client
}      //loop</p><p>void readPhotocell(){</p><p>photocellReading = analogRead(photocellPin);  
 Serial.print(WiFi.localIP());
  Serial.print(" Analog reading = ");
  Serial.print(photocellReading);     // the raw analog reading</p><p>  // We'll have a few threshholds, qualitatively determined
  if (photocellReading < 10) {
    Serial.println(" - Dark");
  } else if (photocellReading < 200) {
    Serial.println(" - Dim");
  } else if (photocellReading < 500) {
    Serial.println(" - Light");
  } else if (photocellReading < 800) {
    Serial.println(" - Bright");
  } else {
    Serial.println(" - Very bright");
  }
          
}</p><p>void readPIR(){
  Serial.println(pirReading);     // the raw analog reading
 if (digitalRead(pirPin) == HIGH) {
    //digitalWrite(ledPin, HIGH);   //the led visualizes the sensors output pin state
    if (lockLow) {
      //makes sure we wait for a transition to LOW before any further output is made:
      lockLow = false;
      Serial.println("---");
      Serial.print("motion detected at ");
      Serial.print(millis() / 1000);
      Serial.println(" sec");
      delay(50);
    }
    takeLowTime = true;
pirReading = true; 
    //alarmTriggered();
  }</p><p>  if (digitalRead(pirPin) == LOW) {
    //digitalWrite(ledPin, LOW);  //the led visualizes the sensors output pin state
pirReading = false; 
    if (takeLowTime) {
      lowIn = millis();          //save the time of the transition from high to LOW
      takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
    //if the sensor is low for more than the given pause,
    //we assume that no more motion is going to happen
    if (!lockLow && millis() - lowIn > pause) {
      //makes sure this block of code is only executed again after
      //a new motion sequence has been detected
      lockLow = true;
      Serial.print("motion ended at ");      //output
      Serial.print((millis() - pause) / 1000);
      Serial.println(" sec");
      delay(50);
    }
  }</p><p>}</p>









<br>

Arduino Mega with Ethernet Shield Code version:

<p>#include <br>//#include </p><p>//byte mac[] = { 0x5C, 0xCF, 0x7F, 0x24, 0x84, 0x3D }; //physical mac address
byte mac[] = { 0x5C, 0xCF, 0x7F, 0x24, 0x66, 0x69 }; //physical mac address
//byte ip[] = { 192, 168, 1, 101 }; // ip in lan
//byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
//byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
//EthernetServer server(80); //server port</p><p>String readString; </p><p>#include 
#include </p><p>/*-----( Declare Constants )-----*/
#define ONE_WIRE_BUS D4 /*-(Connect to Pin 2 )-*</p><p>*-----( Declare objects )-----*/
/* Set up a oneWire instance to communicate with any OneWire device*/
OneWire ourWire(ONE_WIRE_BUS);</p><p>/* Tell Dallas Temperature Library to use oneWire Library */
DallasTemperature sensors(&ourWire);</p><p>/*-----( Declare Variables )-----*</p><p>/////////////////////</p><p>int photocellPin = 0;     // the cell and 10K pulldown are connected to a0
int photocellReading;     // the analog reading from the analog resistor divider</p><p>#include </p><p>IPAddress ip(192, 168, 1, 101); 
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);</p><p>const char* ssid = "IWILLSTEALYOURMONEY";
const char* password = "namnamnewnew";</p><p>// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);</p><p>#include 
dht DHT;
#define DHT11_PIN D6</p><p>void setup(){
Serial.begin(115200);
  pinMode(5, OUTPUT); //pin selected to control
  //start Ethernet
  //Ethernet.begin(mac, ip, gateway, gateway, subnet);</p><p>WiFi.begin(ssid, password);
//WiFi.config(ip, gateway, subnet);
while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    //WiFi.begin(ssid, password);
    //Serial.print(".");
  }
  //Serial.println("");
  //Serial.println("WiFi connected");
  
  // Start the server
  server.begin();
  //Serial.println("Server started");</p><p>  // Print the IP address
  Serial.println(WiFi.localIP());</p><p>  
  //server.begin();
  //enable serial data print 
  //Serial.begin(9600); </p><p>sensors.begin();</p><p>  
}</p><p>void loop(){</p><p>readPhotocell();
//int chk = DHT.read11(DHT11_PIN);
//Serial.print(DHT.humidity);</p><p>float temperatureIndoor;
  float temperatureOutdoor;
  float humidity;
  sensors.requestTemperatures(); // Send the command to get temperatures
          temperatureIndoor = (sensors.getTempCByIndex(0));
  delay(100);
  // Create a client connection
  //EthernetClient client = server.available();
  WiFiClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();</p><p>        //read char by char HTTP request
        if (readString.length() < 100) {</p><p>          //store characters to string 
          readString += c; 
          //Serial.print(c);
        } </p><p>        //if HTTP request has ended
        if (c == '\n') {</p><p>          ///////////////
  </p><p>          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json;charset=utf-8");
          client.println("Server: Arduino");
          client.println("Connnection: close");
          client.println();
          //sensors.requestTemperatures(); // Send the command to get temperatures
          //temperatureIndoor = (sensors.getTempCByIndex(0));
          //temperatureOutdoor = (sensors.getTempFByIndex(0));
 //Serial.print(sensors.getTempCByIndex(0));</p><p> humidity = (DHT.humidity);
          client.print("{");
          client.print("\"temperature\":");
          client.print(temperatureIndoor);
          client.print(",");
          client.print("\"humidity\":");
          client.print(humidity);
          
          //client.print("}");
          //client.println();
             
          
         client.print(",");
          //client.print("{");
          client.print("\"lightval\":");
          client.print(photocellReading);
          client.print("}");
          client.println();</p><p>          //stopping client
          client.stop();</p><p>          ///////////////////// control arduino pin
          if(readString.indexOf("?on") >0)//checks for on
          {
            Serial.println(readString.indexOf("on"));
            
            digitalWrite(5, HIGH);    // set pin 5 high
            Serial.println("Led On");</p><p>          }
          if(readString.indexOf("?off") >0)//checks for off
          {
            Serial.println(readString.indexOf("off"));
            digitalWrite(5, LOW);    // set pin 5 low
            Serial.println("Led Off");
          }
          if(readString.indexOf("?temp") >0)//checks for off
          {
            Serial.println(readString.indexOf("temp"));</p><p>            temperatureIndoor = (sensors.getTempCByIndex(0));
       
            //digitalWrite(5, LOW);    // set pin 5 low
            Serial.println("temp sent");
          }
          if(readString.indexOf("?light") >0)//checks for off
          {
            Serial.println(readString.indexOf("light"));</p><p>       
            //digitalWrite(5, LOW);    // set pin 5 low
            Serial.println("light sent");
          }</p><p>         
          //clearing string for next read
          readString="";</p><p>//sensors.requestTemperatures(); // Send the command to get temperatures
//Serial.print("Device 1 (index 0) = ");
//Serial.print(sensors.getTempFByIndex(0));
//Serial.println(" Degrees F");</p><p>        }                     ///c=n
      }                //client available
    }             //client connected
  }         //if client
}      //loop</p><p>void readPhotocell(){</p><p>photocellReading = analogRead(photocellPin);  
 Serial.print(WiFi.localIP());
  Serial.print(" Analog reading = ");
  Serial.print(photocellReading);     // the raw analog reading</p><p>  // We'll have a few threshholds, qualitatively determined
  if (photocellReading < 10) {
    Serial.println(" - Dark");
  } else if (photocellReading < 200) {
    Serial.println(" - Dim");
  } else if (photocellReading < 500) {
    Serial.println(" - Light");
  } else if (photocellReading < 800) {
    Serial.println(" - Bright");
  } else {
    Serial.println(" - Very bright");
  }
          
}</p><br>

ok

Step 6: Test the New Accessory in IOS HomeKit App

Test the new Accessory in iOS HomeKit App

Test the new Accessory in iOS HomeKit App and Siri


Check out my Light Sensor plugin for HomeBridge / HomeKit !

https://github.com/lagunacomputer/homebridge-Curr...

Step 7: Create HomeKit Automation Rules and Triggers Within the IOS 'Eve' App From the App Store.

Create HomeKit Automation Rules and Triggers within the iOS 'Eve' app from the App Store.

You could create a Scene that uses the Motion Detected Trigger to turn on the Living Room Lamp.

Using the Triggers feature in the Eve iOS App (i assume you can do the same with an Apple TV4)

Step 8: Optional - Basic 3D Printable Box

Optional - Basic 3D Printable Box