Andre Mendes
Published © GPL3+

Smart Home Mini Arduino - In 30 Minutes - Posting in Ubidots

Make your smart home with Arduino system in less than 30 minutes with this project . Simple, no complicated codes. So let's start?

BeginnerFull instructions provided21,136
Smart Home Mini Arduino - In 30 Minutes - Posting in Ubidots

Things used in this project

Hardware components

Arduino Mega 2560
Arduino Mega 2560
×1
Arduino Ehernet Shield
×1
DHT11 Temperature & Humidity Sensor (4 pins)
DHT11 Temperature & Humidity Sensor (4 pins)
×1
PIR Motion Sensor (generic)
PIR Motion Sensor (generic)
×1
LED (green)
×1
Buzzer
Buzzer
×1
SparkFun Breadboard Power Supply 5V/3.3V
SparkFun Breadboard Power Supply 5V/3.3V
×1

Software apps and online services

Ubidots
Ubidots
Make your account , create 3 variables , take the data directly from your Arduino Ethernet Shield

Story

Read more

Schematics

BreadboardSchematic

Fritzing Archive

BreadboardSchematic_bb.jpg

BreadboardSchematic_Esquemático.png

Code

Humidity And Temperature And presence sensor POST With Ubidots

Arduino
All code and sensors
#include <DHT.h>
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>

// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
  0xZZ, 0xZZ, 0xZZ, 0xZZ, 0xZZ, 0xZZ // Change all ZZ MAC ADDRESS ETHERNET SHIELD
};
// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(0, 0, 0, 0); ETHERNET SHIELDIP ADDRESS LOCAL LAN

// fill in your Domain Name Server address here:
IPAddress myDns(0, 0, 0, 0); DNS IP ADDRESS LOCAL LAN

// initialize the library instance:
EthernetClient client;
   
String idvariable = ""; //Varible Temperature UBIDOTS
String idvariable_umidade = ""; //Variable Humidity UBIDOTS
String idvariable_sensorPIR = ""; //Variable presence sensor UBIDOTS
String token = ""; //TOKEN UBIDOTS

//Define PIN do Sensor
#define DHTPIN A1 // pino que estamos conectado
#define DHTTYPE DHT11 // DHT 11
 
// Conecte pino 1 do sensor (esquerda) ao +5V
// Conecte pino 2 do sensor ao pino de dados definido em seu Arduino
// Conecte pino 4 do sensor ao GND
// Conecte o resistor de 10K entre pin 2 (dados) 
// e ao pino 1 (VCC) do sensor
DHT dht(DHTPIN, DHTTYPE);

//SD Card
File dataFiles;


 
//Declarao das variveis referentes aos pinos digitais - ALARME + PIR.
int pinBuzzer = 2;
int pinSensorPIR = 3;
int pinLed = 4;
int valorSensorPIR = 0;

void setup() {

  
  // start serial port:
  Serial.begin(9600);

  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip, myDns);
  // print the Ethernet board/shield's IP address:
  Serial.print("Conexao com a REDE LOCAL - IP: ");
  Serial.println(Ethernet.localIP());     
  delay(1000);  
  
  if (Ethernet.begin(mac) == 0) {
       Serial.println("Falha na Conexao com a REDE Local");
       // no point in carrying on, so do nothing forevermore:
       for(;;);
     }

  // SD Card - Iniciando
  Serial.println("Inicializando SD card...");

  if (!SD.begin(4)) {
    Serial.println("Falha na Inicializacao do SD Card!");
    Serial.println("Falha no Modo DATA LOGGER SD Card!");
    return;
  }
  Serial.println("Inicializacao Completa");
  Serial.println("Modo DATA LOGGER Inicializado com Sucesso");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  dataFiles = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (dataFiles) {
    Serial.print("Escrevendo no Arquivo test.txt...");
    dataFiles.println("Testando 1, 2, 3.");
    // close the file:
    dataFiles.close();
    Serial.println("Escrita FInalizada com Sucesso");
  } else {
    // if the file didn't open, print an error:
    Serial.println("Erro Abrindo arquivo test.txt");
  }

  // re-open the file for reading:
  dataFiles = SD.open("test.txt");
  if (dataFiles) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (dataFiles.available()) {
      Serial.write(dataFiles.read());
    }
    // close the file:
    dataFiles.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("Erro Abrindo arquivo test.txt para LEITURA");
  }
    
     
  //Inicia Sensor DHT
  Serial.println("Iniciando - Sensor - DHT");
  dht.begin();  

  //Definido pinos como de entrada ou de sada
  pinMode(pinBuzzer, OUTPUT);
  pinMode(pinSensorPIR, INPUT);
  pinMode(pinLed, OUTPUT);
  
}

void loop()
   {

    
      // A leitura da temperatura e umidade pode levar 250ms!
      // O atraso do sensor pode chegar a 2 segundos.
      float h = dht.readHumidity();
      float t = dht.readTemperature();
      // testa se retorno  valido, caso contrrio algo est errado.
      if (isnan(t) || isnan(h)) 
      {
        Serial.println("Falha na Leitura do Sensor - DHT");
      } else {

      //Lendo o valor do sensor PIR. Este sensor pode assumir 2 valores
      //1 quando detecta algum movimento e 0 quando no detecta.
      valorSensorPIR = digitalRead(pinSensorPIR);
       
      Serial.print("Sensor de Movimento - Valor Recebido: ");  
      Serial.println(valorSensorPIR);
       
        //Verificando se ocorreu deteco de movimentos
        if (valorSensorPIR == 1) {
          ligarAlarme();
        } else {
          desligarAlarme();
        }

        
       int value_temperatura = t;
       int value_umidade = h;
       int value_sensorPIR = valorSensorPIR; 
       save_value(String(value_temperatura));
       save_value_umidade(String(value_umidade));     
       save_value_sensorPIR(String(value_sensorPIR));
      }
   }
 
 
 //Grava Dados Variavel 1 - Temperatura
   void save_value(String value_temperatura)
   {
     // if you get a connection, report back via serial:
     int num=0;
     String var = "{\"value\":"+ String(value_temperatura) + "}";
     num = var.length();
     delay(500);
     if(client.connect("things.ubidots.com", 80))
     {
       Serial.println("connected");

       // New lines according to ubidots support:

        //Temperatura
       client.println("POST /api/v1.6/variables/"+idvariable+"/values HTTP/1.1");
       Serial.println("POST /api/v1.6/variables/"+idvariable+"/values HTTP/1.1");
       client.println("Content-Type: application/json");
       Serial.println("Content-Type: application/json");
       client.println("Content-Length: "+String(num));
       Serial.println("Content-Length: "+String(num));
       client.println("X-Auth-Token: "+token);
       Serial.println("X-Auth-Token: "+token);
       client.println("Host: things.ubidots.com\n");
       Serial.println("Host: things.ubidots.com\n");
       client.print(var);
       Serial.print(var+"\n");
     }
     else
     {
       // if you didn't get a connection to the server:
       Serial.println("Falha na Gravacao - Variavel 2 - Temperatura");
     }

     if (!client.connected())
     {
       Serial.println();
       Serial.println("DESCONECTANDO...");
       client.stop();
     }

     if (client.available())
     {
       char c = client.read();
       Serial.print(c);
     }   
     client.flush();
     client.stop();

   }

    //Grava DAdos Variavel 2 - Humidade
   void save_value_umidade(String value_umidade)
   {
     // if you get a connection, report back via serial:
     int num=0;
     String var2 = "{\"value\":"+ String(value_umidade) + "}";
     num = var2.length();
     delay(1000);
     if(client.connect("things.ubidots.com", 80))
     {
       Serial.println("connected");

       // New lines according to ubidots support:

        //Temperatura
       client.println("POST /api/v1.6/variables/"+idvariable_umidade+"/values HTTP/1.1");
       Serial.println("POST /api/v1.6/variables/"+idvariable_umidade+"/values HTTP/1.1");
       client.println("Content-Type: application/json");
       Serial.println("Content-Type: application/json");
       client.println("Content-Length: "+String(num));
       Serial.println("Content-Length: "+String(num));
       client.println("X-Auth-Token: "+token);
       Serial.println("X-Auth-Token: "+token);
       client.println("Host: things.ubidots.com\n");
       Serial.println("Host: things.ubidots.com\n");
       client.print(var2);
       Serial.print(var2+"\n");
     }
     else
     {
       // if you didn't get a connection to the server:
       Serial.println("Falha na Gravacao - Variavel 1 - Humidade");
     }

     if (!client.connected())
     {
       Serial.println();
       Serial.println("DESCONECTANDO...");
       client.stop();
     }

     if (client.available())
     {
       char c = client.read();
       Serial.print(c);
     }

     client.flush();
     client.stop();

   }


    //Grava Dados Variavel 3 - Sensor PIR
   void save_value_sensorPIR(String value_sensorPIR)
   {
     // if you get a connection, report back via serial:
     int num=0;
     String var3 = "{\"value\":"+ String(value_sensorPIR) + "}";
     num = var3.length();
     delay(1000);
     if(client.connect("things.ubidots.com", 80))
     {
       Serial.println("connected");

       // New lines according to ubidots support:

        //Temperatura
       client.println("POST /api/v1.6/variables/"+idvariable_sensorPIR+"/values HTTP/1.1");
       Serial.println("POST /api/v1.6/variables/"+idvariable_sensorPIR+"/values HTTP/1.1");
       client.println("Content-Type: application/json");
       Serial.println("Content-Type: application/json");
       client.println("Content-Length: "+String(num));
       Serial.println("Content-Length: "+String(num));
       client.println("X-Auth-Token: "+token);
       Serial.println("X-Auth-Token: "+token);
       client.println("Host: things.ubidots.com\n");
       Serial.println("Host: things.ubidots.com\n");
       client.print(var3);
       Serial.print(var3+"\n");
     }
     else
     {
       // if you didn't get a connection to the server:
       Serial.println("Falha na Gravacao - Variavel 1 - Humidade");
     }

     if (!client.connected())
     {
       Serial.println();
       Serial.println("DESCONECTANDO...");
       client.stop();
     }

     if (client.available())
     {
       char c = client.read();
       Serial.print(c);
     }

     client.flush();
     client.stop();

   }   


  //Alarme de Presena
  void ligarAlarme() {
    //Ligando o led
    digitalWrite(pinLed, HIGH);
     
    //Ligando o buzzer com uma frequencia de 1500 hz.
    tone(pinBuzzer, 1500);
    delay(4000); //tempo que o led fica acesso e o buzzer toca
    
    if (valorSensorPIR != 1){ 
      desligarAlarme();
    }
  }
 
  void desligarAlarme() {
    //Desligando o led
    digitalWrite(pinLed, LOW);
     
    //Desligando o buzzer
    noTone(pinBuzzer);
  }
   

  

Credits

Andre Mendes

Andre Mendes

1 project • 18 followers
Ti engineer infra structure, VoIP engineer, system engineer, maker, hacker and electronics enthusiast
Thanks to Web Search.

Comments