Christopher Mendez Martinez
Published © GPL3+

Room Control With ESP8266 | Temperature, Motion, Curtains...

This project consist on a system that let you control the brightness of a LED Strip and the curtain of your Room, know the movement and Temp

IntermediateFull instructions provided3 hours27
Room Control With ESP8266 | Temperature, Motion, Curtains...

Things used in this project

Hardware components

NodeMCU ESP8266 Breakout Board
NodeMCU ESP8266 Breakout Board
×1
DC POWER JACK 2.1MM BARREL-TYPE PCB MOUNT
TaydaElectronics DC POWER JACK 2.1MM BARREL-TYPE PCB MOUNT
×1
Resistor 220 ohm
Resistor 220 ohm
×1
Darlington High Power Transistor
Darlington High Power Transistor
×1
Linear Regulator (7805)
Linear Regulator (7805)
×1
PIR Sensor, 7 m
PIR Sensor, 7 m
×1
Capacitor 100 nF
Capacitor 100 nF
×1
TinyShield Proto Terminal Blocks
TinyCircuits TinyShield Proto Terminal Blocks
×1
Dual H-Bridge motor drivers L293D
Texas Instruments Dual H-Bridge motor drivers L293D
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

Schematics

Code

Code

Processing
/****************************************

 * Libreria

 ****************************************/

#include "UbidotsESPMQTT.h"
#include <EEPROM.h>
#include <OneWire.h> 
#include <DallasTemperature.h>

/****************************************

 * Definir constantes
 
 ****************************************/

#define TOKEN "........................." // Your Ubidots TOKEN

#define WIFINAME "..................." //Your SSID

#define WIFIPASS "..................." // Your Wifi Pass

#define DEVICE_LABEL "room"

#define VARIABLE_LABEL1  "cortina"  // Nombre de variable en Ubidots
#define VARIABLE_LABEL2  "tiraled"  // Nombre de variable en Ubidots

int brillo=0;
int brillo2=0;

const int ERROR_VALUE = 65535;  // Valor de error cualquiera
const uint8_t NUMBER_OF_VARIABLES = 2; // Cantidad de variables a las que el programa se va a suscribir
char * variable_labels[NUMBER_OF_VARIABLES] = {"cortina","tiraled"}; // Nombres de las variables

#define Sensor D4       
#define cortinaU D7
#define cortinaD D8
#define ledbar D1
#define movimiento D3 

int temp;
int memo=3;
int seguro=1;
unsigned long currentMillis = 0; 
const long interval = 11000;

float estadocortina; // Nombre de la variable que se va a usar en el codigo
float estadoled; // Nombre de la variable que se va a usar en el codigo
float value; // Variable para almacenar el dato de entrada.
uint8_t variable; // Para usar en el switch case

Ubidots ubiClient(TOKEN);

WiFiClient client;

OneWire oneWire(Sensor); 
/********************************************************************/
// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);

/****************************************

 * Funciones auxiliares

 ****************************************/

void callback(char* topic, byte* payload, unsigned int length) {
  char* variable_label = (char *) malloc(sizeof(char) * 30);
  get_variable_label_topic(topic, variable_label);
  value = btof(payload, length);
  set_state(variable_label);
  execute_cases();
  free(variable_label);

  //////////////////Tira LED///////////////////
  if(estadoled>=0){
    brillo2=(estadoled*10.24);
    if(brillo>brillo2){
      for(brillo;brillo>=brillo2;brillo--){
        analogWrite(ledbar,brillo);
        delay(1);
      }
    }
     if(brillo<brillo2){
      for(brillo;brillo<=brillo2;brillo++){
        analogWrite(ledbar,brillo);
        delay(1);
      }
    }
  }
  /////////////////Cortinas////////////////////
  if(estadocortina==100){
    if(memo==0){
      digitalWrite(cortinaU,HIGH);
      currentMillis = millis(); 
      memo = 1;
      EEPROM.write(0,memo);
    }       
  }  
  else if(estadocortina==0){

    if(memo==1){
      digitalWrite(cortinaD,HIGH);   
      currentMillis = millis();
      memo = 0; 
      EEPROM.write(0,memo);
    }  
  }  
 }



// Parse topic to extract the variable label which changed value
void get_variable_label_topic(char * topic, char * variable_label) {
  Serial.print("topic:");
  Serial.println(topic);
  sprintf(variable_label, "");
  for (int i = 0; i < NUMBER_OF_VARIABLES; i++) {
    char * result_lv = strstr(topic, variable_labels[i]);
    if (result_lv != NULL) {
      uint8_t len = strlen(result_lv);      
      char result[100];
      uint8_t i = 0;
      for (i = 0; i < len - 3; i++) { 
        result[i] = result_lv[i];
      }
      result[i] = '\0';
      Serial.print("Label is: ");
      Serial.println(result);
      sprintf(variable_label, "%s", result);
      break;
    }
  }
}

// cast from an array of chars to float value.
float btof(byte * payload, unsigned int length) {
  char * demo = (char *) malloc(sizeof(char) * 10);
  for (int i = 0; i < length; i++) {
    demo[i] = payload[i];
  }
  float value = atof(demo);
  free(demo);
  return value;
}

// State machine to use switch case
void set_state(char* variable_label) {
  variable = 0;
  for (uint8_t i = 0; i < NUMBER_OF_VARIABLES; i++) {
    if (strcmp(variable_label, variable_labels[i]) == 0) {
      break;
    }
    variable++;
  }
  if (variable >= NUMBER_OF_VARIABLES) variable = ERROR_VALUE; // Not valid
}

// Function with switch case to determine which variable changed and assigned the value accordingly to the code variable
void execute_cases() {  
  switch (variable) {
  
    case 0:
      estadocortina = value;
      if(seguro){
      if(estadocortina==100){
        memo=1;
      }
      else if(estadocortina==0){
        memo=0;
      }
      seguro=0;
      }
      Serial.print("Cortina en: ");
      Serial.println(estadocortina);
      Serial.println();
      break;
    case 1:
      estadoled = value;
      Serial.print("Tira de LED en: ");
      Serial.println(estadoled);
      Serial.println();
      break;
    case ERROR_VALUE:
      Serial.println("error");
      Serial.println();
      break;
    default:
      Serial.println("default");
      Serial.println();
  }

}
/****************************************

 * Funcion principal

 ****************************************/

void setup() {

  // put your setup code here, to run once:
  
  ubiClient.ubidotsSetBroker("industrial.api.ubidots.com"); // Sets the broker properly for the business account

  ubiClient.setDebug(false); // Pass a true or false bool value to activate debug messages

  Serial.begin(115200);

  pinMode(cortinaU, OUTPUT);
  pinMode(cortinaD, OUTPUT);
  pinMode(ledbar, OUTPUT);
  Serial.println("EEPROM");
  Serial.println(memo);

  ubiClient.wifiConnection(WIFINAME, WIFIPASS);

  ubiClient.begin(callback);

  if(!ubiClient.connected()){

  ubiClient.reconnect();

  }

  char* deviceStatus = getUbidotsDevice(DEVICE_LABEL);

  if (strcmp(deviceStatus, "404") == 0) {


ubiClient.add("cortina", 0); //Insert your variable Labels and the value to be sent
ubiClient.ubidotsPublish(DEVICE_LABEL);
ubiClient.add("tiraled", 0); //Insert your variable Labels and the value to be sent
ubiClient.ubidotsPublish(DEVICE_LABEL);


ubiClient.loop();

  }


  ubiClient.ubidotsSubscribe(DEVICE_LABEL,VARIABLE_LABEL1); //Insert the Device and Variable's Labels
  ubiClient.ubidotsSubscribe(DEVICE_LABEL,VARIABLE_LABEL2); //Insert the Device and Variable's Labels


  Serial.println(variable_labels[1]);
  memo = EEPROM.read(0);
  EEPROM.write(0,0);
}

void loop() {
   

  // put your main code here, to run repeatedly:

  if(!ubiClient.connected()){

  ubiClient.reconnect();

  ubiClient.ubidotsSubscribe(DEVICE_LABEL,VARIABLE_LABEL1); //Insert the Device and Variable's Labels
  ubiClient.ubidotsSubscribe(DEVICE_LABEL,VARIABLE_LABEL2); //Insert the Device and Variable's Labels



  }
  ubiClient.loop();

  sensors.requestTemperatures(); // Send the command to get temperature readings 
  temp = sensors.getTempCByIndex(0);
  int mov = digitalRead(movimiento);
    //float value2 = analogRead(2) // uncomment this line to read the GPIO2 of the ESP8266
   ubiClient.add("temperatura", temp); //Insert your variable Labels and the value to be sent
    ubiClient.ubidotsPublish(DEVICE_LABEL);
     ubiClient.add("movimiento", mov); //Insert your variable Labels and the value to be sent
    ubiClient.ubidotsPublish(DEVICE_LABEL);
    
    
      if (millis()> currentMillis + interval) {
        
    // save the last time you blinked the LED    
    // set the LED with the ledState of the variable:
    if(estadocortina==100){
    digitalWrite(cortinaU, LOW);
    }
    if(estadocortina==0){
    digitalWrite(cortinaD, LOW);
    }
      
  }
    delay(100);
}



char* getUbidotsDevice(char* deviceLabel) {
  char* data = (char *) malloc(sizeof(char) * 700);
  char* response = (char *) malloc(sizeof(char) * 400);
  sprintf(data, "GET /api/v1.6/devices/%s/", deviceLabel);
  sprintf(data, "%s HTTP/1.1\r\n", data);
  sprintf(data, "%sHost: industrial.api.ubidots.com\r\nUser-Agent:googlehome/1.0\r\n", data);
  sprintf(data, "%sX-Auth-Token: %s\r\nConnection: close\r\n\r\n", data, TOKEN);
  free(data);
 
  if (client.connect("industrial.api.ubidots.com", 80)) {
    client.println(data);
  } 
  else {
    free(data);
    free(response);
    return "e";
  }
  int timeout = 0;
  while(!client.available() && timeout < 5000) {
    timeout++;
    if (timeout >= 4999){
      free(data);
      free(response);
      return "e";
    }
    delay(1);
    }

  int i = 0;
  while (client.available()) {
    response[i++] = (char)client.read();
    if (i >= 399){
      break;
    }
  }
  char * pch;
  char * statusCode;
  int j = 0;
  pch = strtok (response, " ");
  while (pch != NULL) {
    if (j == 1 ) {
      statusCode = pch;
    }

    pch = strtok (NULL, " ");
    j++;
  }
  free(response);
  return statusCode;

}

Credits

Christopher Mendez Martinez

Christopher Mendez Martinez

19 projects • 15 followers
Mendez is a youtuber and an Electronic Engineering student who loves automation, programming and sharing his knowledge with everyone.

Comments

Add projectSign up / Login