Arduino Code

The Arduino will send a message over USB Serial connection whenever movement is detected. However, this could have the potential to generate a lot of emails. For this reason the Arduino sends a different message if its too soon to send another email.

Download: file
int pirPin = 7;

int minSecsBetweenEmails = 60; // 1 min

long lastSend = -minSecsBetweenEmails * 1000l;

void setup()
{
  pinMode(pirPin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  long now = millis();
  if (digitalRead(pirPin) == HIGH)
  {
    if (now > (lastSend + minSecsBetweenEmails * 1000l))
    {
      Serial.println("MOVEMENT");
      lastSend = now;
    }
    else
    {
      Serial.println("Too soon");
    }
  }
  delay(500);
}

The variable “minSecsBetweenEmails” can be changed to whatever you feel is a reasonable value. Here it is set to 60 seconds, so emails will not be sent at a rate of more than one a minute.

To keep track of when the last request to send an email was sent, a variable “lastSend” is used. This is initialized to a negative number, equal to the negative of the number of milliseconds specified in the “minSecsBetweenEmails” variable. This ensures that the PIR can be triggered immediately that the Arduino sketch starts.

Within the loop, the function “millis()” is used to get the number of milliseconds since the Arduino started and compare it with that last time the alarm was triggered and only if it is more than the specified number of seconds since last time does it send the message “MOVEMENT”. Otherwise even though movement has been detected, it just sends the message “Too soon”.

Before you link things up to your Python program, you can test the Arduino setup by just opening the Serial Monitor on the Arduino IDE.

This guide was first published on Feb 28, 2013. It was last updated on Feb 28, 2013. This page (Arduino Code) was last updated on Jul 21, 2019.