Part 3: Arduino Home Security

Once it was all hooked up, it was time to write the code to run the security system!

I noticed that when a door or window was opened, the analog input was typically reporting a reading of less than 1000. However, these values seemed pretty unstable and would sometimes fluctuate wildly. I’m not sure if this was due to my wiring job, the wiring inside the walls, or some kind of interference.

In an attempt to solve this, I tried hooking the shared lead from the sensors to the Arduino’s ground port. The readings seemed to be more stable – when there was no alarm condition, the analog inputs reported readings less than 20 and around 30-100 when a sensor was tripped. To be honest, I’m not exactly sure why this works, but I suspect the sensors are inducing a very small voltage in the line when they’re tripped.

My code samples the Arduino’s analog inputs once every 100 milliseconds and looks for a reading above the threshold (currently 20). If it finds a high reading, it increments a “breach” counter. Once the threshold is breached 10 times, the alarm is activated and I receive a text message. This is done via a call by the Arduino to a webpage where I’ve set up a PHP script to send the text notification. If the alarm condition disappears (i.e. the sensor reading drops back below 20), the breach count is decremented until it reaches 0. At that point, another text is sent out indicating that the alarm has been cleared. Here’s a sample of the logic (this one is for the analog input #4 which is connected to the door sensor):


  if (val4 > threshold4)
  {
    Serial.print("frontDoor: ");
    Serial.print(val4);
    Serial.print("\n");
    
    if (alarm4)
    {
      if (breach4 < 10)
        breach4++;
    }
    else
    {
      if (breach4 > 9)
      {
        alarm4 = 1;
        send_alert(4);
      }
      else
        breach4++;
    }
  }
  else 
  {
    if (alarm4)
    {
      if (breach4 > 0)
        breach4--;
      else
      {
        alarm4 = 0;
        send_alert(14);
      }
    }
    else
    {
      if (breach4 > 0)
        breach4--;
    }
  }

Success:
photo

Here’s the full Arduino code, as well as the PHP code that sends the proper alert. The code doesn’t yet have error checking and all the security features implemented yet, but it’s a work in progress. Enjoy!

Arduino Security System Code
PHP Code to Send Text Alerts

Leave a Comment