A simple arduino burglar alarm: save sensor codes via web interface

As mentioned last time I want to make sure that the codes sensors can be stored in the EEPROM , all from a web interface !
Here’s the code that does this thing :

#include <String.h>
#include <Time.h>
#include <SPI.h>
#include <Ethernet.h>
#include <EEPROM.h>
#include <RCSwitch.h>

byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
int SERIAL_BAUD        = 9600;
EthernetServer server(8081);
RCSwitch mySwitch = RCSwitch();
int RECEIVE_PIN       = 0;
int nSensori = 5;

void setup() {
  Serial.begin(SERIAL_BAUD);
  setupComm();
  mySwitch.enableReceive(RECEIVE_PIN);
}

void loop() {
  getClientConnection();
}

void getClientConnection(){

  EthernetClient client = server.available();
  if (client) {
    String postString ="";
    Serial.println("nuova richiesta");
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if(postString.length()<15){
          postString +=c;
        }

        if (c == 'n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          client.println("<h1>Configurazione</h1>");
          client.print("<br>");

          for (int i=0; i<nSensori; i++)
          {
            String linkCompleto = "";
            linkCompleto = "<a href="./?save"+ String(i);
            linkCompleto +="">Save Sensor " + String(i);
            linkCompleto += "</a><br/>";
            client.println(linkCompleto);
            Serial.println(linkCompleto);
            //client.println("<a href="./?save1">Salva Sensore 1</a>");
          }

          client.println("<br/>");
          client.println("<a href="./?elenco">Sensors list</a>");
          client.println("</html>");
          break;
          //}
        }

        if (c == 'n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != 'r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }

      }
    }  //fine client.connected 

    Serial.println("-------------");
    Serial.println(postString);
    Serial.println("-------------");

    if(postString.indexOf("?save") > 0){ 

      int indexSave = postString.indexOf("?save");
      Serial.println("indexOf");
      Serial.println(indexSave);
      //cerco valore del sensore
      String sSensore = postString.substring(indexSave+5 ,indexSave+6);
      Serial.println("Sensore");
      Serial.println(sSensore);
      int iSensore = sSensore.toInt();
      long valore = salvaSensore(iSensore);
      client.println("<br/>");
      client.println("<p>Salvataggio sensore effettuato</p>");
      client.println("<br/>");
      client.println("Codice sensore " + sSensore);
      client.print(valore);
    }   

    if(postString.indexOf("?elenco") > 0){
      for (int i=0; i<nSensori; i++)
      {
        client.println("<p>Sensor" + String(i)+" : </p>");
        client.print(String(EEPROMReadlong(i*4)));
        Serial.println(EEPROMReadlong(i*4));
      }
    }

    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
  }
}

long salvaSensore(int iSensore)
{
  int addressTosSave = iSensore*4;
  long valore = 0;
  Serial.println("salvaSensore");
  if (mySwitch.available()) {
    Serial.println("mySwitch.available");
    valore = mySwitch.getReceivedValue();
    Serial.println("valore ");
    Serial.print(valore);
    EEPROMWritelong(addressTosSave,valore);
  }
  delay(1000);
  return valore;
} 

void EEPROMWritelong(int address, long value)
{
  //Decomposition from a long to 4 bytes by using bitshift.
  //One = Most significant -> Four = Least significant byte
  byte four = (value & 0xFF);
  byte three = ((value >> 8) & 0xFF);
  byte two = ((value >> 16) & 0xFF);
  byte one = ((value >> 24) & 0xFF);

  //Write the 4 bytes into the eeprom memory.
  EEPROM.write(address, four);
  EEPROM.write(address + 1, three);
  EEPROM.write(address + 2, two);
  EEPROM.write(address + 3, one);
}

void setupComm()
{
  Serial.println("Trying to connect");
  Serial.print("n");
  if (!Ethernet.begin(mac)){
    Serial.println("Failed to DHCP");
    // no point in carrying on, so do nothing forevermore:
    while(true);
  }

  // print your local IP address:
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }
  Serial.println("fine");
}

long EEPROMReadlong(long address)
{
  //Read the 4 bytes from the eeprom memory.
  long four = EEPROM.read(address);
  long three = EEPROM.read(address + 1);
  long two = EEPROM.read(address + 2);
  long one = EEPROM.read(address + 3);

  //Return the recomposed long by using bitshift.
  return ((four << 0) & 0xFF) + ((three << 8) & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF);
}

The resulting web interface is as follow : (avoid comments 🙂 )

You must write in the browser the IP address that is printed in the Arduino console and also specifying port 8081 .
In my case , for example : 192.168.1.136:8081
There are 5 links that allow you to save the data sensors : pressing the button ” Save sensor 0 ” and pressing the sensor ( opening the door for example ) is stored the data in the EEPROM .

Schermata 2014-12-17 alle 22.31.29

Once data is saved , clicking ” View data sensors .”, you can view a summary list of what is saved in the EEPROM.

Schermata 2014-12-17 alle 22.31.01

Thie evening if I’ll have time I’ll make a video where you can see better storing operations.
The code is relatively simple.
I now try to explain how this links are done and their management.

line 14: Declaring variable nSensori: the number of sensors that I want to manage
line 53-57: Links are created dynamically according to the html syntax.
Links have this format: save0 , SAVE1 , SAVE2 . .. , depending on the link you want to press .
line 62: link to view stored code sensors.
riga 86-99: I save codes sensor
In detail:
line 84: I received “save” in the querystring, I know I need to save a sensor code…which one?
line 90: now i know the sensor code number!
line 94: I call salvaSensore: function: this function use mySwitch.getReceivedValue() function to save code sensor in the EEPROM.
line 95-99: I write in the HTML page the code sensor just saved
line 102-109: I write in HTML page the saved sensor list.it’s a simple for cycle that use  EEPROMReadlong to read each sensor code.
At this point , in the next article , we will implement what we saw today in our anti-theft !

So funny!!!!

See you soon!

A simple burglar alarm: save sensor code in the EEPROM

Here I am again , with flue … good excuse for not going to the gym and have fun with Arduino.
As I said in the previous article I’d like to make code improvements : in particular I don’t want that sensor code are written in the code but I want to give to the user the possibility to store sensore value from a web interface.
Pressing a web interface button, the wireless receiver module will listen the sensor code and store somewhere.
The first problem is : where and how to store them ? I thought at EEPROM memory in Arduino.
The values ​​that I want to use are long ( as you can see from the sketch lines 26,27,28,29 the previous article ) so I cannot  just  use a single cell in EEPROM (which can contain only one byte from 0 to 255 ) .
The long data type instead is four times a byte : 4 bytes . To summarize :

boolean – It can assume only two values ​​: true or false .

char – It contains a single character . Arduino register it as a number ( but we see the text ) . When the characters are used to record a number, may contain a value between -128 and 127 .

byte – It can contain a number between 0 and 255. As a character uses only one byte of memory .

int – It contains a number between -32’768 and 32’767 . It’s the variable type most used and uses two bytes of memory . unsigned int – It has the same function as int , it just can not contain negative numbers , but numbers between 0 and 65,535 . long – It’s twice the size of an int and contains the numbers between-2’147’483’648 and 2’147’483’647. unsigned long – Unsigned long version from 0 to 4’294’967’295 . float – It can store numbers with a comma . Occupies 4 bytes of RAM . double – A double-precision floating point with maximum 1’7976931348623157×10 ^ 308 .

So what I want to do is to split my code sensor (long) in 4 bytes and then I want to store each of these four bytes in a cell in the EEPROM . In this article I found this helpful code. I just checked if the code is ok, in my case :


/*
 I write and read a long i the EEPROM
 */
#include <EEPROM.h>;
// the setup routine runs once when you press reset:
void setup() {
 // initialize serial communication at 9600 bits per second:
 Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
 delay(5000);
 long address=0;
 long sensore1= 3557625;
 long sensore2= 10521177;
 EEPROMWritelong(address, sensore1);
 Serial.println("writing 1 code");
 address+=4;
 EEPROMWritelong(address, sensore2);
 Serial.println("writing 2 code");
 /*Serial.println(EEPROMReadlong(0));
 Serial.println(EEPROMReadlong(4));*/
}
void EEPROMWritelong(int address, long value)
{
 //Decomposition from a long to 4 bytes by using bitshift.
 //One = Most significant -> Four = Least significant byte
 byte four = (value & 0xFF);
 byte three = ((value >> 8) & 0xFF);
 byte two = ((value >> 16) & 0xFF);
 byte one = ((value >> 24) & 0xFF);
 //Write the 4 bytes into the eeprom memory.
 EEPROM.write(address, four);
 EEPROM.write(address + 1, three);
 EEPROM.write(address + 2, two);
 EEPROM.write(address + 3, one);
}
long EEPROMReadlong(long address)
{
 //Read the 4 bytes from the eeprom memory.
 long four = EEPROM.read(address);
 long three = EEPROM.read(address + 1);
 long two = EEPROM.read(address + 2);
 long one = EEPROM.read(address + 3);
 //Return the recomposed long by using bitshift.
 return ((four << 0) & 0xFF) + ((three << 8) & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF);
}

line 5: include EEPROM library line 19-22: with the EEPROMWritelong  function I write the first sensor code in the address 0 then the second sensor in the address 4. Rightly 4 bytes after the first byte . At this point I turned off Arduino and then reconnect it. Let’s check if i read the value I stored before!!! I changed the loop library to read EEPROM.

void loop() {
/*delay(5000);
long address=0;
long sensore1= 3557625;
long sensore2= 10521177;
EEPROMWritelong(address, sensore1);
Serial.println("writing 1 code");
address+=4;
EEPROMWritelong(address, sensore2);
Serial.println("writing 2 code");*/

  Serial.println("Reading Sensor 1");
Serial.println(EEPROMReadlong(0));
Serial.println("Reaging Sensor 2");
Serial.println(EEPROMReadlong(4));
delay(10000000);
}

I read this values: Schermata 2014-12-03 alle 22.25.17 It works!! Ok , at this point I know how to store the values ​​in EEPROM , in the next post I will try to build the web interface to storage sensor codes. I hope this post can be helpful! Have a good day!

A simple burglar Alarm: Ethernet shield connection

Hello again. I received ad home the Ethernet shield and it’s time to study it a bit!
What I want to understand is how to send an email to my email address .

The connection to the Arduino UNO is simple , a picture can explain better!

FZ05SN7H05NT26I.MEDIUM(from instructables.com)

We can connect the RJ45 socket to our router and the plug line to usb port (see below).

FDP0VOXH05NHCWO.MEDIUM(from instructables.com)

The most important things to keep in mind are:

  1. ethernet shield ip settings
  2. ethernet shield mac address
  3. SMTP settings to send email

My router is in DHCP so it dynamically set the IP address.
No problems for the MAC address: it can be set as you need.

There are two ways to send email with Ethernet Shield:

  1. Temboo service has a library to send email with gmail account (instruction here )
  2. SMTP2GO service to send up to 10 email with its SMTP free service (here you can register )

I choose SMTP2GO cause I discovered Temboo too late, when I finished to deploy with SMTP2GO.
If someone use Temboo let me know your opinion.

I used Nicolaj Joergensen code,it’s very clear and well explained.

#include <SPI.h>;
#include <Ethernet.h>;

// Arduino network information
byte mac[] = {  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
EthernetClient client;
char smtpServer[] = "smtpcorp.com";
void setup()
{
  Serial.begin(9600);  // for debug mode
  setupComm();
}
void loop()
{
  email("hallo");
  delay(1000);
}
//  ethernet shield connection init
void setupComm()
{
  Serial.println("Trying to connect");
  if (!Ethernet.begin(mac)){
    Serial.println("Failed to DHCP");
    // verifyng connection
    while(true);
  }
  delay(10000);
  // IP address is:
  Serial.print("IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }
  Serial.println();
}
// now I send email
bool email(char* text)
{
  bool success = false;
  Serial.println("Sending email...");
  if (client.connect(smtpServer, 2525)){            //2525 is SMTP Server port
    Serial.println("connected");
    delay(100);
    client.println("EHLO arduino");
    for(int i=0; i<999; ++i){
      if(client.read() > 0)
        break;
    }
    Serial.println("responded");
    client.println("AUTH LOGIN");                     //see "http://base64-encoder-online.waraxe.us/"
    client.println("xxxxxxxxxx");           		 //Type your username  and encode it
    client.println("yyyyyyyyyy");        			//Type your password  and encode it</p>
    // Put your "from" email address here
    client.println("MAIL FROM:<dumm@gmail.com>"); //Seems you can write what you want here...
    for(int i=0; i<999; ++i){
      if(client.read() > 0)
        break;
    }
    client.println("RCPT TO:<mail@mail.com>");
    for(int i=0; i<999; ++i){
      if(client.read() > 0)
        break;
    }
    client.println("DATA");
    for(int i=0; i<999; ++i){
      if(client.read() > 0)
        break;
    }
    //Sender
    client.println("from: mail@mail.com"); //Sender address
    client.println("to: mail@mail.com");  //Receiver address
    client.println("SUBJECT: From your arduino");
    client.println("");
    client.println(text);
    client.println(".");
    client.println("QUIT");
    for (int i = 0; i<999; ++i){
      if(i > 998){
        Serial.println("error: No response");
      }
      if(client.read() > 0)
        break;
    }
    success = true;
    client.println();
    Serial.println("end");
  }
  else {
    Serial.println("Failed");
    client.println("QUIT"); //Disconnection
  }
  client.stop();
  return success;
}

Code explanation:

line  5: MAC Address setting: as told before you can choose the numerbs you want!
line  7:  SMTP server address (is smtpcorp.com for the SMTP2GO service)
line 15: email function: we send an email with “ciao” as text message.
line 22: ethernet shield initialization
line 30-33: here we display the IP address assigned in DHCP by my router. It’s really help know Ethernet shield address expecially if you want to use our shield as webserver.
line 42: SMTP command to send email.
line 51: 64 base encode for SMTP2GO username
line 52: 64 base encode for SMTP2GO password.

This link can be useful for encoding in 64 base: http://base64-encoder-online.waraxe.us/
For example CICCIO username will be Q0lDQ0lP in 64 base.

I uploaded the sketch on Arduino UNO and i received my first email!
At line 16 I set a delay, every 1 second Arduino will try to send an email!
Be careful cause SMTP2GO service provides up to 10 daily emails in the free edition.

It’s all for today with ethernet shield: i have all I want.

The next steps is to send a custom email when one sensor will detect an intrusion: I want to know witch sensor and at what time.

See you soon!

Ps. Meanwhile I received Arduino Nano!… 🙂 🙂

A simple burglar Alarm: the noise sensor

The noise sensor FC04 is really easy to use.
It only has 3 pins: Vcc, GND e SNG, therefore the connections I have established are the followings:

Pin Receiver Pin Arduino
Vcc 5 V
GND GND
SNG Pin 2 (digital)

The sensor has a noise threshold set by a screw: if a noise  over the threshold is detected, a HIGH signal is sent to the selected pin (2 in our case).

Therefore the sketch can be:

 

int SERIAL_BAUD        = 9600;
int SENSOR_DIGITAL_PIN =    2;
int SOUND_DELAY        =   50; /* a small delay to not detect multiple noises or echos */
void setup() {
    Serial.begin(SERIAL_BAUD);
    pinMode(SERIAL_BAUD, INPUT);
}
void loop() {
    if (digitalRead(SENSOR_DIGITAL_PIN) == LOW) {
        Serial.print("Rumore!");
        delay(SOUND_DELAY);
    }
}

Now we can merge together the two programs (movement and noise sensor) to make Arduino send me an email in case of suspected intrusion.

I’ll work on internet shield in the next post: as always done i’ll try to understand how it works itself  and then add it with the noise sensor above and the movement sensor previously published .

A presto!

A simple burglar Alarm: reading data sensors

I found really useful  rc -switch library to read sensor data.

First of all i wanted to understand what happens  when I activate the door sensor or PIR sensor.
I connected the receiver to Arduino as the table below:

Pin Receiver Pin Arduino
Vcc 5 V
GND GND
DATA Pin 2 (digital)

I used the breadboard included in the arduino starter kit. 


I included the rc switch  library and copied it in Arduino library folder.
My filesystem under libraries\RCswitch\ look like:

  • keywords.txt
  • RCSwitch.cpp
  • RCSwitch.h
  • example folder

We can open Arduino Ide and copy and paste this code:

 

#include <RCSwitch.h>;
RCSwitch mySwitch = RCSwitch();

void setup() {
   Serial.begin(9600);
   mySwitch.enableReceive(0); // Receiver on inerrupt 0 =&gt; that is pin #2
}

void loop() {
   if (mySwitch.available()) {

      int value = mySwitch.getReceivedValue();

      if (value == 0) {
         Serial.print("Unknown encoding");
     } else {
         Serial.print("Received ");
         Serial.print( mySwitch.getReceivedValue() );
         Serial.print(" / ");
         Serial.print( mySwitch.getReceivedBitlength() );
         Serial.print("bit ");
         Serial.print("Protocol: ");
         Serial.println( mySwitch.getReceivedProtocol() );
      }

      mySwitch.resetAvailable();
   }
}

Uploading sketch to Arduino  and opening console monitor on 9600 baud I can read this values:

  1. door sensor 1: Received 1398111 / 24bit Protocol: 1
  2. door sensor 2: Received 1394004 / 24bit Protocol: 1
  3. PIR sensor      :Received 1392102 / 24bit Protocol: 1

At this point I can use these values ​​to intercept door opening or movements into house and  make Arduino send me an email or a text message.
I opted to receive an email: here comes ethernet shield .