FractalTech
Published © GPL3+

Control lights, alarm, and climate from your phone using ESP

Smart home with ESP8266: control LEDs, buzzer & DHT11 via Wi-Fi

BeginnerFull instructions provided103
Control lights, alarm, and climate from your phone using ESP

Things used in this project

Hardware components

ESP8266 ESP-12E
Espressif ESP8266 ESP-12E
×1
Resistor 220 ohm
Resistor 220 ohm
×2
Through Hole Resistor, 5.1 kohm
Through Hole Resistor, 5.1 kohm
×1
DHT11 Temperature & Humidity Sensor (4 pins)
DHT11 Temperature & Humidity Sensor (4 pins)
×1
Buzzer
Buzzer
×1
5 mm LED: Yellow
5 mm LED: Yellow
×1
5 mm LED: Green
5 mm LED: Green
×1
Breadboard (generic)
Breadboard (generic)
×1
Jumper wires (generic)
Jumper wires (generic)
×1

Software apps and online services

SyncCanvas
Arduino IDE
Arduino IDE

Hand tools and fabrication machines

Mastech MS8217 Autorange Digital Multimeter
Digilent Mastech MS8217 Autorange Digital Multimeter

Story

Read more

Schematics

Conexion

Code

Example

Arduino
#include <ESP8266WiFi.h>   // Librera para conexin WiFi / WiFi connection library
#include <DHT11.h>         // Librera para sensor DHT11 / DHT11 sensor library

// ================== Pines y Variables / Pins and Variables ==================
const int LED = 5;             // GPIO5 (D1) - LED con encendido/apagado / On/off LED
const int LEDPWM = 4;          // GPIO4 (D2) - LED con control PWM / PWM dimmable LED
const int Passive_buzzer = 12; // GPIO12 (D6) - Zumbador pasivo / Passive buzzer

// ================== Configuracin WiFi / WiFi Configuration ==================
const char* ssid = "MiRedWiFi";           // Nombre de la red WiFi / WiFi network name
const char* password = "miContrasea"; // Contrasea WiFi / WiFi password
const char* serverIP = "xxx.xxx.xxx.xxx";   // Direccin IP del servidor / Server IP address
const int serverPort = 3141;              // Puerto del servidor / Server port

WiFiClient client; // Objeto cliente TCP / TCP client object

// ================== Sensor DHT11 / DHT11 Sensor ==================
DHT11 dht11(2); // GPIO2 (D4) conectado al sensor DHT11 / Connected to DHT11 sensor

// ================== Variables Globales / Global Variables ==================
bool leer = false;       // Indica si se debe leer el sensor / Whether to read the sensor
long tiempoActual = 0;   // Tiempo actual / Current time
long tiempoAnterior = 0; // ltimo tiempo de lectura / Last reading time
long deltaT = 0;         // Diferencia de tiempo / Time difference
String codigo = "";      // Cdigo recibido desde el servidor / Command received
String codigo2 = "";     // Parte del cdigo / Part of the command
int valor = 0;           // Valor numrico extrado / Extracted numeric value

// ================== Configuracin Inicial / Setup ==================
void setup() {
  // Conectarse a la red WiFi / Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500); // Esperar conexin / Wait for connection
  }

  // Conectar al servidor TCP una vez conectado a WiFi / Connect to TCP server
  conectarServidor();

  // Configurar los pines como salida / Configure pins as output
  pinMode(LED, OUTPUT);
  pinMode(LEDPWM, OUTPUT);
  pinMode(Passive_buzzer, OUTPUT);

  // Estado inicial / Initial state
  digitalWrite(LED, LOW);        // LED apagado / LED off
  analogWrite(LEDPWM, 0);        // LED PWM apagado / LED dim off
  tone(Passive_buzzer, 0);       // Zumbador sin sonido / Buzzer off
}

// ================== Bucle Principal / Main Loop ==================
void loop() {
  // Si el cliente TCP se desconecta, intenta reconectar / Reconnect if client disconnected
  if (!client.connected()) {
    // Estado inicial / Initial state
    digitalWrite(LED, LOW);        // LED apagado / LED off
    analogWrite(LEDPWM, 0);        // LED PWM apagado / LED dim off
    tone(Passive_buzzer, 0);       // Zumbador sin sonido / Buzzer off
    conectarServidor();
    delay(1000);
    return;
  }

  // Leer datos entrantes del servidor / Read incoming data from server
  if (client.available()) {
    char c = client.read(); // Leer carcter / Read character
    if (c != '\n') {
      codigo += c; // Acumular el cdigo / Accumulate command
    } else {
      codigo.trim(); // Quitar espacios en blanco / Remove whitespace

      // Procesar comandos simples / Process simple commands
      if (codigo == "A") {
        leer = true;  // Activar lectura del sensor / Enable sensor reading
      } else if (codigo == "B") {
        leer = false; // Desactivar lectura del sensor / Disable sensor reading
      } else if (codigo == "C") {
        digitalWrite(LED, HIGH); // Encender LED / Turn LED on
      } else if (codigo == "D") {
        digitalWrite(LED, LOW);  // Apagar LED / Turn LED off
      } else if (codigo == "E") {
        tone(Passive_buzzer, 523); // Encender zumbador / Play buzzer (C note)
      } else if (codigo == "F") {
        tone(Passive_buzzer, 0);   // Apagar zumbador / Stop buzzer
      } else {
        // Comando para controlar intensidad PWM del LED / PWM brightness command
        codigo2 = codigo.substring(0, 2);         // Obtener prefijo / Get command prefix
        valor = codigo.substring(2).toInt();      // Obtener valor numrico / Get numeric value
        if (codigo2 == "LP") {
          analogWrite(LEDPWM, valor); // Aplicar PWM al LED / Apply PWM to LED
        }
      }
      codigo = ""; // Limpiar comando / Clear command
    }
  }

  // Si la lectura est habilitada / If reading is enabled
  if (leer) {
    tiempoActual = millis();               // Tiempo actual / Current time
    deltaT = tiempoActual - tiempoAnterior; // Tiempo desde la ltima lectura / Time since last read

    if (deltaT >= 5000) { // Leer cada 5 segundos / Read every 5 seconds
      int temperature = 0;
      int humidity = 0;
      int result = dht11.readTemperatureHumidity(temperature, humidity);

      // Enviar datos si la lectura fue exitosa / Send data if read successful
      if (result == 0) {
        client.print("T");       // Envia datos al grafico de temperatura / Temperature tag
        client.println(temperature);
        client.print("GTH");         // Envia dato de humedad / Humidity tag
        client.println(humidity);
      }
      tiempoAnterior = tiempoActual; // Actualizar tiempo / Update time
    }
  }
}

// ================== Conexin al Servidor / Connect to Server ==================
void conectarServidor() {
  if (client.connect(serverIP, serverPort)) {
    // Enviar mensaje de conexin exitosa / Send connected message
    client.println("ESP8266 conectado");
  }
  // Si falla, se intentar de nuevo en el loop / Retry in main loop if fails
}

Credits

FractalTech
2 projects • 1 follower

Comments