Top 4 easy to make ESP32 projects for IOT applications.

 

Top 4 easy to make ESP32 projects .




These codes were takenform https://wokwi.com/

  • ESP32 WIFI SCANNER

/*
ESP32 WiFi Scanning example
This code demonstrates how to scan for available WiFi networks using an ESP32 module.
*/

#include "WiFi.h"

void setup() {
  Serial.begin(115200); // Initialize serial communication at 115200 baud rate
  Serial.println("Initializing WiFi..."); // Print a message indicating WiFi initialization
  WiFi.mode(WIFI_STA); // Set WiFi mode to station (client) mode
  Serial.println("Setup done!"); // Print a message indicating setup completion
}

void loop() {
  Serial.println("Scanning..."); // Print a message indicating the start of WiFi scanning

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks(); // Scan for available WiFi networks and store the number of networks found
  Serial.println("Scan done!"); // Print a message indicating the completion of WiFi scanning
  if (n == 0) {
    Serial.println("No networks found."); // Print a message indicating that no networks were found
  } else {
    Serial.println();
    Serial.print(n);
    Serial.println(" networks found"); // Print the number of networks found

    // Iterate through each network found and print its details
    for (int i = 0; i < n; ++i) {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1); // Print the network number
      Serial.print(": ");
      Serial.print(WiFi.SSID(i)); // Print the SSID (name) of the network
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i)); // Print the received signal strength indicator (RSSI) of the network
      Serial.print(")");
      // Print "*" if the network is encrypted, otherwise print " "
      Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*");
      delay(10); // Delay to prevent overwhelming the serial monitor
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000); // Delay for 5 seconds before starting the next scan
}
  • ESP32 NTP-SERVER WITH I2C LCD INTERFACE
// Learn about the ESP32 WiFi simulation in
// https://docs.wokwi.com/guides/esp32-wifi

#include <WiFi.h> // Include the WiFi library
#include <Wire.h> // Include the Wire library for I2C communication
#include <LiquidCrystal_I2C.h> // Include the LiquidCrystal library for I2C LCD

LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2); // Create an instance of the LCD object

#define NTP_SERVER     "pool.ntp.org" // NTP server address
#define UTC_OFFSET     0 // UTC offset in seconds
#define UTC_OFFSET_DST 0 // UTC offset during daylight saving time

// Function to display a spinner animation on the LCD
void spinner() {
  static int8_t counter = 0; // Counter to keep track of spinner state
  const char* glyphs = "\xa1\xa5\xdb"; // Spinner characters
  LCD.setCursor(15, 1); // Set cursor position to display spinner
  LCD.print(glyphs[counter++]); // Print the spinner character
  if (counter == strlen(glyphs)) { // Reset counter if end of spinner characters array is reached
    counter = 0;
  }
}

// Function to print local time on the LCD
void printLocalTime() {
  struct tm timeinfo; // Structure to hold time information
  if (!getLocalTime(&timeinfo)) { // Get local time from NTP server
    LCD.setCursor(0, 1);
    LCD.println("Connection Err"); // Print error message if connection to NTP server fails
    return;
  }

  LCD.setCursor(8, 0);
  LCD.println(&timeinfo, "%H:%M:%S"); // Print time in HH:MM:SS format

  LCD.setCursor(0, 1);
  LCD.println(&timeinfo, "%d/%m/%Y   %Z"); // Print date in DD/MM/YYYY format and time zone abbreviation
}

void setup() {
  Serial.begin(115200); // Initialize serial communication at 115200 baud rate

  LCD.init(); // Initialize the LCD
  LCD.backlight(); // Turn on the LCD backlight
  LCD.setCursor(0, 0);
  LCD.print("Connecting to "); // Print a message indicating connection to WiFi
  LCD.setCursor(0, 1);
  LCD.print("WiFi ");

  WiFi.begin("Wokwi-GUEST", "", 6); // Connect to WiFi network
  while (WiFi.status() != WL_CONNECTED) { // Wait until connected to WiFi
    delay(250);
    spinner(); // Display spinner animation while waiting for connection
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP()); // Print IP address once connected to WiFi

  LCD.clear();
  LCD.setCursor(0, 0);
  LCD.println("Online"); // Print "Online" message on the LCD
  LCD.setCursor(0, 1);
  LCD.println("Updating time..."); // Print "Updating time..." message on the LCD

  configTime(UTC_OFFSET, UTC_OFFSET_DST, NTP_SERVER); // Configure time settings using NTP server
}

void loop() {
  printLocalTime(); // Continuously print local time on the LCD
  delay(250); // Delay between time updates
}
  • ESP32 HTTP IOT SERVER
/*
ESP32 HTTP IoT Server Example for Wokwi.com

  This code demonstrates how to create an HTTP server on an ESP32 board for IoT applications.
  The server controls two LEDs and provides a web interface to toggle their states.

  To test this code, you need the Wokwi IoT Gateway, as explained here:
  https://docs.wokwi.com/guides/esp32-wifi#the-private-gateway

  Then start the simulation, and open http://localhost:9080
  in another browser tab.

  Note that the IoT Gateway requires a Wokwi Club subscription.
  To purchase a Wokwi Club subscription, go to https://wokwi.com/club
*/

#include <WiFi.h> // Include the WiFi library
#include <WiFiClient.h> // Include the WiFiClient library
#include <WebServer.h> // Include the WebServer library
#include <uri/UriBraces.h> // Include the UriBraces library for URI parsing

#define WIFI_SSID "Wokwi-GUEST" // WiFi SSID
#define WIFI_PASSWORD "" // WiFi password
#define WIFI_CHANNEL 6 // WiFi channel for faster connection

WebServer server(80); // Create an instance of the WebServer object

const int LED1 = 26; // Pin for LED 1
const int LED2 = 27; // Pin for LED 2

bool led1State = false; // Variable to store the state of LED 1
bool led2State = false; // Variable to store the state of LED 2

// Function to send HTML response to client
void sendHtml() {
  String response = R"(
    <!DOCTYPE html><html>
      <head>
        <title>ESP32 Web Server Demo</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
          html { font-family: sans-serif; text-align: center; }
          body { display: inline-flex; flex-direction: column; }
          h1 { margin-bottom: 1.2em; }
          h2 { margin: 0; }
          div { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: auto auto; grid-auto-flow: column; grid-gap: 1em; }
          .btn { background-color: #5B5; border: none; color: #fff; padding: 0.5em 1em;
                 font-size: 2em; text-decoration: none }
          .btn.OFF { background-color: #333; }
        </style>
      </head>
           
      <body>
        <h1>ESP32 Web Server</h1>

        <div>
          <h2>LED 1</h2>
          <a href="/toggle/1" class="btn LED1_TEXT">LED1_TEXT</a>
          <h2>LED 2</h2>
          <a href="/toggle/2" class="btn LED2_TEXT">LED2_TEXT</a>
        </div>
      </body>
    </html>
  )";
  response.replace("LED1_TEXT", led1State ? "ON" : "OFF");
  response.replace("LED2_TEXT", led2State ? "ON" : "OFF");
  server.send(200, "text/html", response); // Send HTML response to client
}

void setup(void) {
  Serial.begin(115200); // Initialize serial communication at 115200 baud rate
  pinMode(LED1, OUTPUT); // Set LED pin as output
  pinMode(LED2, OUTPUT); // Set LED pin as output

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); // Connect to WiFi network
  Serial.print("Connecting to WiFi ");
  Serial.print(WIFI_SSID);
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println(" Connected!");

  Serial.print("IP address: ");
  Serial.println(WiFi.localIP()); // Print IP address once connected to WiFi

  server.on("/", sendHtml); // Handle root URL request by sending HTML response

  // Handle toggle URL request to toggle LED state
  server.on(UriBraces("/toggle/{}"), []() {
    String led = server.pathArg(0); // Get LED number from URL
    Serial.print("Toggle LED #");
    Serial.println(led);

    switch (led.toInt()) {
      case 1:
        led1State = !led1State; // Toggle LED 1 state
        digitalWrite(LED1, led1State); // Set LED 1 state
        break;
      case 2:
        led2State = !led2State; // Toggle LED 2 state
        digitalWrite(LED2, led2State); // Set LED 2 state
        break;
    }

    sendHtml(); // Send HTML response to client
  });

  server.begin(); // Start the HTTP server
  Serial.println("HTTP server started");
  Serial.println("HTTP server started");
  Serial.println("HTTP server started");
  Serial.println("HTTP server started");
  Serial.println("HTTP server started");
}

void loop(void) {
  server.handleClient(); // Handle client requests
  delay(2); // Small delay to handle client requests efficiently
}

  • MICROPYTHON IOT WEATHER STATION WITH ESP32 BY https://wokwi.com/projects/322577683855704658

"""
MicroPython IoT Weather Station Example for Wokwi.com

To view the data:

1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"

Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.

Copyright (C) 2022, Uri Shaked

https://wokwi.com/arduino/projects/322577683855704658
"""

import network  # Import the network module for connecting to WiFi
import time  # Import the time module for adding delays
from machine import Pin  # Import the Pin class from the machine module
import dht  # Import the DHT module for interacting with the DHT22 sensor
import ujson  # Import the ujson module for JSON encoding/decoding
from umqtt.simple import MQTTClient  # Import the MQTTClient class from the umqtt.simple module

# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"  # MQTT client ID
MQTT_BROKER = "broker.mqttdashboard.com"  # MQTT broker address
MQTT_USER = ""  # MQTT username (if required)
MQTT_PASSWORD = ""  # MQTT password (if required)
MQTT_TOPIC = "wokwi-weather"  # MQTT topic to publish weather data

sensor = dht.DHT22(Pin(15))  # Create an instance of the DHT22 sensor connected to pin 15

print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)  # Create an instance of the WLAN object for station mode
sta_if.active(True)  # Activate the station interface
sta_if.connect('Wokwi-GUEST', '')  # Connect to the WiFi network
while not sta_if.isconnected():  # Wait until connected to WiFi
  print(".", end="")
  time.sleep(0.1)
print(" Connected!")

print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)  # Create an instance of the MQTT client
client.connect()  # Connect to the MQTT broker
print("Connected!")

prev_weather = ""  # Variable to store previous weather data
while True:
  print("Measuring weather conditions... ", end="")
  sensor.measure()  # Measure temperature and humidity
  message = ujson.dumps({
    "temp": sensor.temperature(),  # Get temperature reading
    "humidity": sensor.humidity(),  # Get humidity reading
  })
  if message != prev_weather:  # Check if weather data has changed
    print("Updated!")
    print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
    client.publish(MQTT_TOPIC, message)  # Publish weather data to MQTT broker
    prev_weather = message  # Update previous weather data
  else:
    print("No change")
  time.sleep(1)  # Delay for 1 second before next measurement

Comments

Popular posts from this blog

Digital clock " DS1307 RTC" with PIC16F877A microcontroller and I2C

Smart Elevator simulation with arduino uno and Proteus

Temperature sensor with PIC16F877a using Analog to Digital convertion.