Long-Range LoRa-Based Remote Actuator Control using ESP32

This project is ideal for controlling devices over long distances using LoRa (Long Range) technology, which is great for applications in rural areas, agriculture, and IoT networks where internet access is limited.


In this project, you'll use two ESP32 boards with LoRa modules to control an actuator remotely. One ESP32 with a LoRa module will act as the transmitter, sending control commands. The other ESP32 with a LoRa module will be the receiver, controlling the actuator based on the received commands.


Key components:

- ESP32 boards (2x)

- LoRa modules (e.g., SX1278 or RFM95)

- Actuator (e.g., relay module, servo motor)

- 3.7V LiPo batteries (optional for portability)

- Breadboard, jumper wires, and a 5V power supply


Software requirements:

- Arduino IDE with LoRa library (`arduino-lora` library)


Wiring the Components


#1. Transmitter Setup

ESP32 to LoRa Module (SX1278):

  - `MISO` (LoRa) to `GPIO19` (ESP32)

  - `MOSI` (LoRa) to `GPIO23` (ESP32)

  - `SCK` (LoRa) to `GPIO18` (ESP32)

  - `NSS/CS` (LoRa) to `GPIO5` (ESP32)

  - `RST` (LoRa) to `GPIO14` (ESP32)

  - `DIO0` (LoRa) to `GPIO26` (ESP32)

  - `3.3V` (LoRa) to `3.3V` (ESP32)

  - `GND` (LoRa) to `GND` (ESP32)


#2. Receiver Setup

ESP32 to LoRa Module (SX1278):

  - Same connections as the transmitter.


Connecting the Actuator (e.g., Relay) to ESP32:

  - `Signal` pin of the relay to `GPIO15` (ESP32)

  - `VCC` of the relay to `3.3V` or `5V`

  - `GND` of the relay to `GND` (ESP32)


Coding the Transmitter (ESP32)


#include <SPI.h>

#include <LoRa.h>


#define LORA_CS 5

#define LORA_RST 14

#define LORA_IRQ 26


void setup() {

  Serial.begin(115200);

  LoRa.setPins(LORA_CS, LORA_RST, LORA_IRQ);


  if (!LoRa.begin(433E6)) {

    Serial.println("Starting LoRa failed!");

    while (1);

  }


  Serial.println("LoRa Transmitter");

}


void loop() {

  // Example: Sending "ON" or "OFF" command to control the actuator

  String message;

  if (digitalRead(2) == HIGH) {  // Replace with your input logic

    message = "ON";

  } else {

    message = "OFF";

  }


  LoRa.beginPacket();

  LoRa.print(message);

  LoRa.endPacket();


  Serial.print("Sent message: ");

  Serial.println(message);


  delay(2000);  // Adjust delay as needed

}


Coding the Receiver (ESP32)


#include <SPI.h>

#include <LoRa.h>


#define LORA_CS 5

#define LORA_RST 14

#define LORA_IRQ 26

#define RELAY_PIN 15


void setup() {

  Serial.begin(115200);

  pinMode(RELAY_PIN, OUTPUT);

  LoRa.setPins(LORA_CS, LORA_RST, LORA_IRQ);


  if (!LoRa.begin(433E6)) {

    Serial.println("Starting LoRa failed!");

    while (1);

  }


  Serial.println("LoRa Receiver");

}


void loop() {

  int packetSize = LoRa.parsePacket();

  if (packetSize) {

    String receivedMessage = "";

    while (LoRa.available()) {

      receivedMessage += (char)LoRa.read();

    }


    Serial.print("Received: ");

    Serial.println(receivedMessage);


    // Control the actuator based on received message

    if (receivedMessage == "ON") {

      digitalWrite(RELAY_PIN, HIGH);

      Serial.println("Relay turned ON");

    } else if (receivedMessage == "OFF") {

      digitalWrite(RELAY_PIN, LOW);

      Serial.println("Relay turned OFF");

    }

  }

}


Explanation of the Code


Transmitter Code:

  - Initializes the LoRa module to operate at 433 MHz (you may need to adjust the frequency based on your region).

  - Sends "ON" or "OFF" messages based on input (e.g., a button press).

  - Uses `LoRa.beginPacket()` and `LoRa.endPacket()` to send data over the air.


Receiver Code:

  - Waits for incoming LoRa packets and reads the message.

  - Controls the relay based on the message: "ON" activates the relay, "OFF" deactivates it.

  - Uses `LoRa.parsePacket()` to check for new incoming packets.


Testing and Deployment


1. Upload the transmitter code to one ESP32 and the receiver code to the other ESP32.

2. Power up both ESP32s, ensuring that the LoRa modules are properly connected.

3. Monitor the Serial Monitor of both ESP32s to check the status of sent and received messages.

4. Test the control functionality by simulating the input on the transmitter side (e.g., pressing a button or sending an "ON" command).

5. Observe the actuator's behavior connected to the receiver to ensure it reacts accordingly.


Tips for Optimizing Range


- Use antennas for both LoRa modules to maximize the range.

- Ensure there are minimal obstructions between the transmitter and receiver.

- Adjust the spreading factor (SF) in the LoRa library for better range or faster transmission.


Applications


- Remote farm irrigation control.

- Controlling remote lighting systems.

- Industrial automation in remote areas.

- Home automation across large properties.


This guide offers a comprehensive approach to building a Long-Range LoRa-Based Remote Actuator Control system, combining LoRa communication with the power of ESP32. By using this setup, you can achieve reliable control over distances, ideal for IoT and automation projects in areas with limited infrastructure.


ESP-NOW Based Long-Range Actuator Control

Welcome to the World of Wireless Actuator Control!  

In this project, we will build a long-range wireless actuator control system using ESP-NOW, a low-latency communication protocol developed by Espressif. With this project, you’ll be able to control various actuators such as relays, servo motors, or solenoids from a distance using ESP32 or ESP8266 microcontrollers.


This setup is ideal for applications where you need to control devices remotely, such as:

- Remote control of agricultural equipment (e.g., water pumps, valves)

- Long-distance home automation (e.g., garage doors, lights)

- Outdoor systems (e.g., garden irrigation)


What is ESP-NOW?


ESP-NOW is a proprietary protocol by Espressif that enables direct peer-to-peer communication between ESP32 or ESP8266 devices without the need for a Wi-Fi router. It operates on the 2.4 GHz band and supports data transfers up to 250 bytes per packet. Its key benefits include:

- Low Latency: Almost real-time communication with minimal delay.

- Long Range: Range can exceed 200 meters in open spaces.

- Power Efficiency: Ideal for battery-operated devices due to its low power consumption.

- Wi-Fi Independence: Devices communicate directly, making it perfect for remote areas.


Materials Required


Hardware:

- 2x ESP32 or ESP8266 boards (one for the transmitter and one for the receiver)

- Actuator (e.g., 5V relay module, servo motor, or solenoid)

- Breadboard and jumper wires

- Power supply (e.g., 5V USB power bank or adapter)

- 220-ohm resistor (if using a status LED)


Software:

- Arduino IDE with ESP32/ESP8266 core installed.

- ESP-NOW library (comes built-in with the ESP32 core).


Step 1: Setting Up the Arduino IDE


1. Install the ESP32/ESP8266 Core:

   - Open the Arduino IDE and go to File > Preferences.

   - In the Additional Board Manager URLs field, add:

     - For ESP32: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json

     - For ESP8266: http://arduino.esp8266.com/stable/package_esp8266com_index.json

   - Go to Tools > Board > Boards Manager, search for ESP32 or ESP8266, and install the core.

   

2. Select the Board:

   - After installation, select your board under Tools > Board (e.g., ESP32 Dev Module).


Step 2: Understanding the Communication Protocol


ESP-NOW Workflow:

- The transmitter sends a command (e.g., “ON” or “OFF”) to the receiver.

- The receiver processes this command and activates or deactivates the actuator.

- ESP-NOW uses MAC addresses for direct communication between devices. Each ESP32/ESP8266 has a unique MAC address, which we will use to identify the transmitter and receiver.


Step 3: Building the Circuit


Transmitter Setup:

- Components: ESP32/ESP8266 board, a push-button (to send commands), and a 220-ohm resistor with an LED (for visual confirmation).

- Connections:

  - Connect one end of the push-button to GPIO 12 and the other end to GND.

  - Connect the 220-ohm resistor to GPIO 2, and the other end of the resistor to the anode (+) of the LED. Connect the cathode (-) to GND.


Receiver Setup:

- Components: ESP32/ESP8266 board, relay module, and the actuator (e.g., a motor or light).

- Connections:

  - Connect the relay module’s signal pin to GPIO 5 of the ESP32/ESP8266.

  - Connect the relay’s VCC and GND to 5V and GND of the ESP board, respectively.

  - Connect the actuator (e.g., a motor or solenoid) to the NO (Normally Open) and COM (Common) terminals of the relay.


Step 4: Writing the Code


#Transmitter Code (ESP32/ESP8266)

Copy this code into your Arduino IDE and upload it to the transmitter ESP32/ESP8266:


#include <esp_now.h>

#include <WiFi.h>


// Replace with the MAC address of the receiver ESP32/ESP8266

uint8_t receiverAddress[] = {0x24, 0x0A, 0xC4, 0x3E, 0x4A, 0x28}; // Change this to your receiver's MAC

const int buttonPin = 12; // GPIO pin connected to the button

const int ledPin = 2; // GPIO pin connected to an indicator LED


struct_message {

  char command[10];

} dataToSend;


void setup() {

  pinMode(buttonPin, INPUT_PULLUP);

  pinMode(ledPin, OUTPUT);

  

  // Initialize Wi-Fi and ESP-NOW

  WiFi.mode(WIFI_STA);

  esp_now_init();

  esp_now_add_peer(receiverAddress, ESP_NOW_ROLE_COMBO, 1, NULL, 0);

}


void loop() {

  // Check button state and send command

  if (digitalRead(buttonPin) == LOW) {

    strcpy(dataToSend.command, "ON");

    digitalWrite(ledPin, HIGH); // Turn on LED when sending "ON"

  } else {

    strcpy(dataToSend.command, "OFF");

    digitalWrite(ledPin, LOW); // Turn off LED when sending "OFF"

  }

  

  // Send command over ESP-NOW

  esp_now_send(receiverAddress, (uint8_t *)&dataToSend, sizeof(dataToSend));

  delay(1000); // Adjust delay for how frequently data is sent

}


#Receiver Code (ESP32/ESP8266)

Copy this code into your Arduino IDE and upload it to the receiver ESP32/ESP8266:


#include <esp_now.h>

#include <WiFi.h>


const int relayPin = 5; // GPIO pin connected to the relay module


struct_message {

  char command[10];

} incomingData;


void setup() {

  pinMode(relayPin, OUTPUT);

  WiFi.mode(WIFI_STA);

  esp_now_init();

  esp_now_register_recv_cb(OnDataReceive);

}


void OnDataReceive(const uint8_t * mac, const uint8_t *incomingData, int len) {

  memcpy(&incomingData, incomingData, sizeof(incomingData));

  

  if (strcmp(incomingData.command, "ON") == 0) {

    digitalWrite(relayPin, HIGH); // Activate relay

  } else if (strcmp(incomingData.command, "OFF") == 0) {

    digitalWrite(relayPin, LOW); // Deactivate relay

  }

}


void loop() {

  // Loop can remain empty; the callback handles the incoming data

}


Step 5: Pairing the Devices


1. Get the MAC Address:

   - Upload a simple sketch to each ESP32 that prints the MAC address using `WiFi.macAddress()`.

   - Replace `receiverAddress` in the transmitter code with the receiver’s MAC address.


2. Upload the Code: Load the transmitter code onto one ESP32 and the receiver code onto the other.


Step 6: Testing and Debugging


1. Power On both devices.

2. Press the Button on the transmitter:

   - The LED on the transmitter should light up when sending the “ON” command.

   - The actuator connected to the relay on the receiver should activate accordingly.

3. Troubleshooting Tips:

   - If there’s no response, check the wiring and ensure both devices are within range.

   - Ensure the MAC address in the transmitter code matches the receiver’s address.

   - Adjust `delay()` values for optimal responsiveness.


Step 7: Optimizing for Range and Power


1. Improve Range:

   - Use an external antenna if available.

   - Place the devices at a higher elevation and avoid obstacles like walls.

2. Power Management:

   - Use deep sleep mode for battery-operated devices when idle.

   - Activate the transmitter only when sending commands to reduce power consumption.


Testing and Troubleshooting


1. Verify MAC Address: Ensure the MAC address in the transmitter code matches the receiver.

2. Check Serial Monitor: Use the Serial Monitor to debug and verify if commands are being sent and received.

3. Verify Connections: Double-check wiring to ensure all connections are correct and secure.

4. Adjust Delays: Modify the delay() values in the transmitter code for optimal response time.


Conclusion


With this setup, you have a robust, long-range wireless control system for various applications. ESP-NOW offers a simple yet powerful way to connect devices without needing a Wi-Fi network. Try integrating sensors or automating the control logic for even more versatile projects!


Building an Internet Radio Using an ESP32

I've always been fascinated by how compact devices can connect to the internet and play music from all around the world. With a bit of curiosity and a lot of tinkering, I decided to build an internet radio using an ESP32. This little microcontroller is packed with features—Wi-Fi, Bluetooth, and a ton of GPIO pins—making it perfect for this project.


In this article, I'll take you through the entire process, from gathering the materials to setting up the code, and then assembling everything into a functional internet radio. So, grab your ESP32 and let's get started!


Materials Needed


Before jumping into the build, here’s a list of materials you’ll need:

- ESP32 Dev Board: I used the ESP32 DevKit V1, which is widely available and easy to work with.

- I2S Audio Decoder: An I2S decoder like the MAX98357A or the VS1053 is perfect for converting digital audio signals to analog output.

- Speaker: A small 3W speaker works great for this project, but you can use any small speaker that suits your needs.

- Jumper Wires: For connecting everything together.

- Breadboard: For prototyping the circuit before soldering.

- Power Supply: A USB cable for the ESP32 or a 5V power adapter.


Step 1: Setting Up the ESP32 Development Environment


To program the ESP32, you'll need the Arduino IDE installed on your computer. If you haven’t installed it yet, you can download it from the [Arduino website](https://www.arduino.cc/en/software).


Once you have the IDE installed, follow these steps to set up the ESP32 board:

1. Open the Arduino IDE and go to File > Preferences.

2. In the "Additional Board Manager URLs" field, add the following URL:

https://dl.espressif.com/dl/package_esp32_index.json


3. Go to Tools > Board > Board Manager, and search for "ESP32" and install the package.


With this, your Arduino IDE is ready to program the ESP32.


Step 2: Wiring the I2S Decoder to the ESP32


The I2S interface allows the ESP32 to communicate with audio decoders for outputting sound. Here’s how I connected my MAX98357A I2S decoder to the ESP32:


- MAX98357A Pinout:

- LRC (WS): Connect to GPIO 25 of the ESP32.

- BCLK: Connect to GPIO 26.

- DIN (SD): Connect to GPIO 22.

- VIN: Connect to 5V from the ESP32.

- GND: Connect to GND on the ESP32.


Make sure all the connections are firm and double-check the wiring before proceeding. I used a breadboard for this stage to make adjustments easier.


Step 3: Finding Streaming URLs


To make the internet radio work, you’ll need the streaming URL of an internet radio station. There are many directories like [Radio Browser](https://www.radio-browser.info/) or [Shoutcast](https://www.shoutcast.com/) where you can find streaming links.


I chose a station with a simple MP3 stream URL:

http://stream.live.vc.bbcmedia.co.uk/bbc_radio_one


Step 4: Writing the Code


Now, it’s time to get the ESP32 to play that stream. I used the `ESP32-audioI2S` library, which simplifies streaming audio over the internet. Here’s the step-by-step process for setting it up:


1. Install the Audio Library:

   - In the Arduino IDE, go to Sketch > Include Library > Manage Libraries.

   - Search for `ESP32-audioI2S` and install it.


2. The Code:

   Here’s the code I used for streaming audio from an internet station:


   #include "Arduino.h"

   #include "Audio.h"

   #include "WiFi.h"


   const char* ssid = "Your_SSID";

   const char* password = "Your_PASSWORD";

   const char* streamURL = "http://stream.live.vc.bbcmedia.co.uk/bbc_radio_one";


   Audio audio;


   void setup() {

     Serial.begin(115200);

     WiFi.begin(ssid, password);

     while (WiFi.status() != WL_CONNECTED) {

       delay(500);

       Serial.print(".");

     }

     Serial.println("Connected to WiFi");


     audio.setPinout(26, 25, 22);

     audio.connecttohost(streamURL);

   }


   void loop() {

     audio.loop();

   }


Replace `Your_SSID` and `Your_PASSWORD` with your Wi-Fi credentials. This code initializes the Wi-Fi connection, sets up the I2S audio pins, and streams music from the URL.


Step 5: Uploading the Code


Connect your ESP32 to the computer using a USB cable. Select the correct board and COM port from Tools > Board and Tools > Port. Then, click the upload button in the Arduino IDE.


Once the code is uploaded, open the Serial Monitor to check the connection status. If everything is set up correctly, you should see the ESP32 connecting to your Wi-Fi and then streaming the audio.


Step 6: Testing the Audio Output


With the code running, you should start hearing music from the connected speaker. The quality depends on the strength of your Wi-Fi connection and the bitrate of the stream. For me, it was an exciting moment to hear the audio playing from the speaker—proof that everything was working as planned!


Step 7: Building a Custom Enclosure


To give my internet radio a polished look, I decided to build a simple enclosure using an old wooden box. I drilled holes for the speaker and the ESP32's USB port, allowing easy access for reprogramming.


Inside, I mounted the ESP32 and the audio decoder with double-sided tape, ensuring the wires were neatly arranged. A bit of hot glue kept everything in place. It gave the project a nice finished look, making it presentable as a desk accessory.


Step 8: Adding a Display (Optional)


If you want to get fancier, you can add an OLED display to show the station name, song information, or even just a simple equalizer. The I2C OLEDs are pretty straightforward to use with the ESP32.


Here’s a small snippet to get started with a 128x64 OLED:


#include <Wire.h>

#include <Adafruit_GFX.h>

#include <Adafruit_SSD1306.h>


#define SCREEN_WIDTH 128

#define SCREEN_HEIGHT 64

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);


void setup() {

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

  display.display();

  delay(2000);

  display.clearDisplay();

  display.setTextSize(1);

  display.setTextColor(SSD1306_WHITE);

  display.setCursor(0,0);

  display.println("Internet Radio");

  display.display();

}


This code will display a simple “Internet Radio” message on the OLED screen. From here, you can customize the display to show any information you want.


Step 9: Troubleshooting Tips


Here are a few common issues I faced during the build and how I solved them:

- No Audio Output: Double-check your I2S connections and ensure the audio decoder is receiving power.

- Frequent Wi-Fi Drops: Make sure you have a strong Wi-Fi signal. Moving closer to the router helped stabilize my connection.

- Code Upload Failures: Press and hold the "BOOT" button on the ESP32 while uploading the code if you encounter issues.


Final Thoughts


Building this internet radio was a fulfilling experience. It’s amazing how the ESP32, a little board, can turn into a streaming device that plays music from across the globe. Plus, I now have a cool internet radio that I built myself, adding a touch of personal flair to my workspace.


If you're looking to dive deeper into the world of DIY electronics, an ESP32 internet radio is a fantastic project. Not only does it provide a practical application, but it also opens up a whole new world of possibilities for integrating the ESP32 with other gadgets and services. Happy tinkering!


Remote Data Logger with Google Sheets using ESP32

Hey there, fellow DIY enthusiasts! Have you ever wished you could remotely log sensor data and store it neatly in a Google Sheets spreadsheet? Well, I did, and that’s how I ended up building my very own ESP32 remote data logger. The ESP32 is an incredible little microcontroller, perfect for projects that require Wi-Fi connectivity. So, I thought, why not use it to gather sensor data and have it all automatically logged in a Google Sheet for easy access? In this guide, I'll walk you through every step I took to bring this project to life, from setting up the ESP32 to coding it to talk with Google Sheets.


Why This Project?


Before diving into the build, let me tell you why I found this project exciting. As someone who’s into home automation, I love keeping track of environmental data like temperature and humidity. But running to the sensor to get readings? Not so much. By setting up the ESP32 to log data to Google Sheets, I can access those readings from anywhere—whether I’m on the couch or halfway across the world. Plus, Google Sheets is free and easy to use, which made it the perfect choice for storing my data.


Materials I Used:


Here’s everything I needed to get started:

- ESP32 Development Board (I used a standard ESP32 DevKitC)

- USB Cable (for programming the ESP32)

- DHT22 Sensor (measures temperature and humidity)

- Breadboard and some jumper wires

- Laptop with Arduino IDE installed (v2.0 or later)

- A Google account (for setting up Google Sheets)


Step 1: Setting Up the ESP32 with the Arduino IDE


First things first, I needed to make sure my Arduino IDE was ready for the ESP32. Here’s how I did it:


1. Install the ESP32 Board:

   - I opened up my Arduino IDE, went to File > Preferences, and pasted this URL into the Additional Board Manager URLs field:

https://dl.espressif.com/dl/package_esp32_index.json

   - Then, I headed to Tools > Board > Board Manager, searched for "ESP32", and clicked Install.


2. Connect the ESP32:

   - With my ESP32 plugged into the laptop via a USB cable, I selected the correct board and port from Tools > Board and Tools > Port.

   - For my setup, I used the "ESP32 Dev Module."


3. Test the Setup:

   - To make sure everything was working, I uploaded the WiFiScan example sketch from File > Examples > WiFi > WiFiScan. If you see a list of available networks in the Serial Monitor, you’re good to go!


Step 2: Wiring the Sensor


Next, it was time to connect the DHT22 temperature and humidity sensor to the ESP32. Here’s the wiring setup I used:


- VCC of the DHT22 connected to the 3.3V pin on the ESP32.

- GND of the DHT22 to the GND of the ESP32.

- Data Pin of the DHT22 to GPIO 4 on the ESP32 (you can use a different pin if you like, but remember to update the code).


I opted for the DHT22 because it’s a bit more accurate than the DHT11, but the DHT11 would work fine for this project too.


Step 3: Preparing Google Sheets for Data Logging


With the ESP32 and sensor ready, I turned my attention to Google Sheets. Here’s how I set up the spreadsheet:


1. Create a New Google Sheet:

   - I went to [Google Sheets](https://sheets.google.com) and created a new sheet titled "ESP32 Data Logger". 

   - I kept the first row for headers: Timestamp, Temperature, and Humidity.


2. Create a Google Apps Script:

   - From the Google Sheets interface, I navigated to Extensions > Apps Script. This is where I wrote a simple script that would allow my ESP32 to send data directly to the sheet.

   - I deleted any existing code in the script editor and replaced it with this:


     function doGet(e) {

         var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

         var row = [];

         var d = new Date();

         row.push(d);

         for (var param in e.parameter) {

             row.push(e.parameter[param]);

         }

         sheet.appendRow(row);

         return ContentService.createTextOutput("Success");

     }


   - I saved the script and deployed it as a Web App by clicking on Deploy > New Deployment, selecting Web App, and setting access to Anyone. This generated a Web App URL—make sure to copy it, as we’ll need it in the next step!


Step 4: Writing the Arduino Code


With my Google Sheets ready to receive data, it was time to code the ESP32. Here’s the code I used:


#include <WiFi.h>

#include <HTTPClient.h>

#include "DHT.h"


#define DHTPIN 4  // Pin where the DHT22 is connected

#define DHTTYPE DHT22


const char* ssid = "your_SSID";  // Replace with your Wi-Fi SSID

const char* password = "your_PASSWORD";  // Replace with your Wi-Fi Password

const char* serverURL = "your_google_script_url";  // Replace with your Web App URL


DHT dht(DHTPIN, DHTTYPE);


void setup() {

    Serial.begin(115200);

    WiFi.begin(ssid, password);

    

    while (WiFi.status() != WL_CONNECTED) {

        delay(1000);

        Serial.println("Connecting to WiFi...");

    }

    

    Serial.println("Connected to WiFi");

    dht.begin();

}


void loop() {

    if (WiFi.status() == WL_CONNECTED) {

        float temperature = dht.readTemperature();

        float humidity = dht.readHumidity();

        

        if (!isnan(temperature) && !isnan(humidity)) {

            HTTPClient http;

            String url = String(serverURL) + "?temp=" + temperature + "&humidity=" + humidity;

            

            http.begin(url);

            int httpResponseCode = http.GET();

            

            if (httpResponseCode > 0) {

                String response = http.getString();

                Serial.println("Response: " + response);

            } else {

                Serial.println("Error sending request");

            }

            

            http.end();

        } else {

            Serial.println("Failed to read from DHT sensor!");

        }

    } else {

        Serial.println("WiFi Disconnected");

    }

    

    delay(60000);  // Log data every 60 seconds

}


Step 5: Testing the ESP32 Data Logger


With the code uploaded, I opened the Serial Monitor and watched as my ESP32 connected to Wi-Fi and started sending data to my Google Sheets. After a few seconds, I switched to my Google Sheet, and there it was—fresh rows of temperature and humidity data, complete with timestamps!


Troubleshooting Tips


Along the way, I ran into a couple of hiccups, so here are a few tips if you encounter similar issues:

- Wi-Fi Connection Issues: Double-check your SSID and password. I also found that bringing the ESP32 closer to my router helped stabilize the connection.

- Google Script Issues: If you get "permission denied" errors, make sure your Web App URL has access set to "Anyone."

- Sensor Readings Not Displaying: Ensure that the sensor is wired correctly, and double-check that you’ve specified the right GPIO pin in the code.


Conclusion: What’s Next?


And that’s it! I now have a fully functional ESP32 remote data logger that sends sensor data straight to Google Sheets. This setup is a great foundation for future projects—imagine monitoring plant soil moisture, tracking energy consumption, or even logging weather data. With a bit of creativity, you can tailor this project to fit a wide range of use cases.


Happy logging, and see you in the next project!


Boosting My IoT Network: ESP32 into a Wi-Fi Repeater

As a DIY enthusiast, I'm always on the lookout for ways to improve the connectivity of my IoT devices around the house. I have several gadgets like smart lights, sensors, and a few home automation devices, but sometimes they struggle to maintain a strong connection in certain parts of my home. That's when I thought, "Why not use an ESP32-S3 as a Wi-Fi repeater?".


The ESP32-S3 is a powerful microcontroller with enhanced Wi-Fi capabilities compared to its predecessor, and it seemed like the perfect solution to extend the reach of my home network without investing in an expensive mesh router. Here’s how I managed to turn my ESP32-S3 into a Wi-Fi repeater, and I’ll walk you through each step, from setting up the hardware to configuring the software.


Why I Chose the ESP32-S3 for This Project


Before diving into the setup, let me explain why I picked the ESP32-S3. The ESP32-S3 is an upgraded version of the standard ESP32, featuring more processing power, additional GPIO pins, and better support for AI and machine learning applications. These features make it ideal for Wi-Fi-related projects and ensure stable performance, especially when dealing with multiple connected devices. And since it comes with both Wi-Fi and Bluetooth, it’s great for any IoT project that requires flexible communication capabilities.


What I Needed for the Project


To get started, I gathered the following items:


- ESP32-S3 Development Board (I used the ESP32-S3 DevKitC)

- Micro-USB Cable (to power and program the ESP32-S3)

- Computer (running the Arduino IDE, which I’ll explain how to set up)

- Wi-Fi Network (the one I wanted to extend)


I also made sure I had a decent power source because I wanted my repeater to run reliably without interruptions. I planned to power the ESP32-S3 using a USB adapter, but even a simple USB port on a computer could work for testing.


Step 1: Setting Up the Arduino IDE for ESP32-S3


The first step was setting up the Arduino IDE to support the ESP32-S3. If you're new to this, don't worry—it's pretty straightforward:


1. I opened the Arduino IDE on my computer.

2. Went to File > Preferences.

3. In the Additional Boards Manager URLs field, I pasted the following URL:

https://dl.espressif.com/dl/package_esp32_index.json
4. Then, I went to Tools > Board > Boards Manager, searched for "ESP32," and installed the ESP32 package. This gave me access to a wide range of ESP32 boards, including the ESP32-S3.

5. After installation, I selected ESP32S3 Dev Module from the Tools > Board menu, making sure the right board was selected.


This setup allowed my Arduino IDE to recognize the ESP32-S3 and made it ready for programming.


Step 2: Installing the Necessary Libraries


Since I was planning to use the ESP32-S3 as a Wi-Fi repeater, I needed a library to manage its dual-mode Wi-Fi capability—acting both as a client to connect to my main Wi-Fi and as an Access Point (AP) for other devices.


I found a very useful library for this purpose on GitHub, the ESP32 Wi-Fi Repeater by Martin Ger. I downloaded the library from the repository:


- The library is available at:  

https://github.com/martin-ger/esp_wifi_repeater


I extracted the contents into the Arduino libraries folder on my computer. With this library in place, I could easily configure the ESP32-S3 to function as a repeater.


Step 3: Connecting the ESP32-S3 to My Computer


I connected the ESP32-S3 to my computer using a micro-USB cable. It's important to ensure that the right **COM port** is selected under **Tools > Port** in the Arduino IDE. This way, the IDE can properly communicate with the ESP32-S3 for uploading code.


Step 4: Configuring the Wi-Fi Repeater Code


Now came the fun part—writing the code to turn the ESP32-S3 into a Wi-Fi repeater. I created a new sketch in the Arduino IDE and wrote the following code:


#include <WiFi.h>

#include <WiFiAP.h>

#include <WiFiSTA.h>


// Configuration settings

const char* ssid = "YOUR_SSID";         // Replace with your Wi-Fi network SSID

const char* password = "YOUR_PASSWORD"; // Replace with your Wi-Fi network password


void setup() {

  Serial.begin(115200);


  // Start the Wi-Fi connection

  WiFi.mode(WIFI_AP_STA);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(500);

    Serial.print(".");

  }


  Serial.println("");

  Serial.println("Wi-Fi connected!");

  Serial.print("IP address: ");

  Serial.println(WiFi.localIP());


  // Set up the Access Point (AP)

  WiFi.softAP("ESP32_S3_Repeater", "12345678"); // AP SSID and password

  Serial.println("Access Point configured.");

  Serial.print("AP IP address: ");

  Serial.println(WiFi.softAPIP());

}


void loop() {

  // Keep the repeater running

  delay(1000);

}


In this code:

- I replaced `YOUR_SSID` and `YOUR_PASSWORD` with the credentials of my home Wi-Fi network.

- I configured the ESP32-S3 to act as both a client to connect to my existing Wi-Fi and as an access point called ESP32_S3_Repeater with a password of 12345678.


Step 5: Uploading the Code and Testing


With the code ready, I clicked the Upload button in the Arduino IDE. After a few moments, the ESP32-S3 began to run the program. I opened the Serial Monitor (set to 115200 baud) to see the status of the connection.


The output showed that the ESP32-S3 successfully connected to my Wi-Fi network, and the access point was up and running. Here’s what I did to test it:


1. I checked the ESP32_S3_Repeater network on my phone and connected to it using the password 12345678.

2. Once connected, I browsed the internet and tested a few IoT devices like a smart light and a temperature sensor that were out of range before. They connected to the ESP32-S3 repeater without a hitch, and the signal strength was noticeably better.


Step 6: Optimizing the Wi-Fi Repeater for Better Performance


After getting the basic setup working, I wanted to optimize my ESP32-S3 repeater for the best performance:


- Positioning: I placed the ESP32-S3 in a spot where it had a strong signal from my main router. This way, it could effectively extend the coverage without losing too much speed.

- Channel Adjustment: I modified the channel in the code to avoid interference with nearby Wi-Fi networks. Choosing a less crowded channel made a noticeable difference in stability.

- Power Supply: I used a 5V/2A USB adapter to ensure that the ESP32-S3 received enough power, especially since it was running continuously.


Troubleshooting Along the Way


As with any DIY project, I hit a few bumps in the road. Here are some common issues I encountered and how I fixed them:


- ESP32-S3 Not Connecting to Wi-Fi: At first, I couldn’t get the ESP32-S3 to connect to my Wi-Fi. It turned out that my router was set to WPA3 encryption, which isn’t always supported by the ESP32-S3. Switching the router to WPA2 solved this.

- Low Signal Strength: I found that placing the ESP32-S3 closer to the router significantly improved signal quality. Walls and metal objects can interfere, so positioning is key.

- Device Fails to Connect to Repeater: If my devices didn’t connect to the repeater, a quick restart of the ESP32-S3 usually did the trick. It’s important to ensure the repeater is running smoothly.


The Results: A Stable and Extended IoT Network


After setting up and tweaking my ESP32-S3 Wi-Fi repeater, I was impressed by how much better my IoT devices performed. The ESP32-S3 effectively extended the range of my home network, ensuring that my smart devices stayed connected even in areas with weaker signals.


This project was a fun and practical way to use the ESP32-S3’s capabilities, and it saved me from having to invest in additional networking equipment. Plus, it gave me the flexibility to adjust the setup as my needs change.


Conclusion: Empowering My IoT Projects with DIY Solutions


Turning an ESP32-S3 into a Wi-Fi repeater is a great way to improve connectivity for your IoT devices without breaking the bank. Whether you're a fellow tinkerer like me or just looking for a simple solution to extend your Wi-Fi range, this project is a rewarding way to make the most of your ESP32-S3.


I hope this guide helps you boost your own IoT network and sparks your next DIY project. Happy building!

Touchless Hand Sanitizer Dispenser with Arduino Uno R3


Hello, fellow tech enthusiasts! Today, I'm going to guide you through the process of building a touchless hand sanitizer dispenser using the Arduino Uno R3 microcontroller. In the wake of the COVID-19 pandemic, hand hygiene has become crucial, and touchless solutions are in high demand. With this project, we aim to create a simple and efficient way to sanitize hands without the need for physical contact.


In this tutorial, we'll cover the necessary components, the setup process, and the complete code required to bring this touchless hand sanitizer dispenser to life. So, let's dive in and get started!



Part 1: Components Required


Before we begin, let's take a look at the components we'll need for this project:


1. Arduino Uno R3: The Arduino Uno R3 is a popular microcontroller board that serves as the brains of our dispenser. It's equipped with an ATmega328P microcontroller and provides various digital and analog input/output pins.


2. Ultrasonic Sensor (HC-SR04): The HC-SR04 is an affordable and reliable ultrasonic sensor that measures distances using sound waves. We'll use it to detect when a user's hand is in front of the dispenser.


3. Servo Motor: A servo motor allows us to control the motion of the dispenser mechanism. It'll be responsible for triggering the release of the hand sanitizer.


4. Liquid Pump: To dispense the hand sanitizer, we'll need a small liquid pump. Make sure to choose a pump suitable for your sanitizer container and compatible with the Arduino's voltage levels.


5. Power Supply: You'll need a suitable power supply to run the Arduino board, motor, and sensor. A 9V battery or a USB power source should suffice.


6. Hand Sanitizer Container: Find a suitable container to hold your hand sanitizer. Ensure it's easy to refill and has a suitable opening for the liquid pump.


7. Jumper Wires: To connect the various components together, you'll need male-to-male jumper wires.


With these components in hand, we can move on to the setup process.



Part 2: Setting up the Hardware


Before we delve into the coding aspect, let's assemble the hardware components to build our touchless hand sanitizer dispenser.


1. Mounting the Ultrasonic Sensor:

Start by mounting the HC-SR04 ultrasonic sensor on the top of your dispenser. Position it facing downwards, so it detects the presence of hands below. Secure it using adhesive or by creating a custom mounting bracket.


2. Connecting the Ultrasonic Sensor:

Connect the VCC pin of the sensor to the 5V pin on the Arduino board. Next, connect the GND pin to any ground pin on the Arduino. Finally, connect the Trigger and Echo pins of the sensor to any digital pins on the Arduino, making sure to note down the pin numbers for later use.


3. Connecting the Servo Motor:

Connect the signal wire of the servo motor to any digital pin on the Arduino. Additionally, connect the power and ground wires of the servo motor to the 5V and GND pins on the Arduino, respectively.


4. Connecting the Liquid Pump:

The connections for the liquid pump may vary depending on the specific pump you're using. Typically, you'll need to connect the positive and negative terminals of the pump to a suitable power source. Make sure to connect the ground of the power source to the Arduino's GND pin to establish a common ground.


With the hardware setup complete, we can move on to the coding part in the next section.



Part 3: Writing the Arduino Code


Now that we have our hardware set up, it's time to write the code that will control our touchless hand sanitizer dispenser. We'll be using the Arduino programming language, which is based on C/C++.


1. Setting up the Libraries:

Before we begin writing the code, we need to install a couple of libraries that will help us interface with the ultrasonic sensor and servo motor. Open the Arduino IDE (Integrated Development Environment), go to "Sketch" -> "Include Library" -> "Manage Libraries," and search for the following libraries:

   

   - NewPing: This library provides easy-to-use functions for the ultrasonic sensor.

   - Servo: The Servo library allows us to control the servo motor's movement.

   

Install these libraries, and once completed, we can proceed to write our code.


2. Initializing the Libraries and Variables:

Let's start by including the required libraries and declaring the necessary variables. Copy and paste the following code at the beginning of your Arduino sketch:


#include <NewPing.h>

#include <Servo.h>


#define TRIGGER_PIN 2

#define ECHO_PIN 3


#define SERVO_PIN 4

#define PUMP_PIN 5


#define MAX_DISTANCE 20 // Maximum distance in centimeters to trigger the sanitizer


NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

Servo servo;


int pumpDelay = 1000; // Delay for the sanitizer pump activation (in milliseconds)


In this code snippet, we include the necessary libraries, define the pins for the ultrasonic sensor (TRIGGER_PIN and ECHO_PIN), servo motor (SERVO_PIN), and liquid pump (PUMP_PIN). We also set the maximum distance (MAX_DISTANCE) at which the sensor will trigger the sanitizer. The `pumpDelay` variable determines the duration of the sanitizer pump activation.


3. Setting Up the Arduino Setup() Function:

The `setup()` function is called once when the Arduino board powers up. It initializes the necessary settings and pin modes. Insert the following code inside the `setup()` function:


void setup() {

  Serial.begin(9600); // Initialize serial communication (for debugging)


  servo.attach(SERVO_PIN); // Attach the servo to the specified pin


  pinMode(PUMP_PIN, OUTPUT); // Set the pump pin as an output

  digitalWrite(PUMP_PIN, LOW); // Initially turn off the pump

}


In this snippet, we set up the serial communication for debugging purposes. We attach the servo to the specified pin using the `attach()` function and set the liquid pump pin as an output using `pinMode()`. We also ensure that the pump is initially turned off by setting the pin's state to LOW using `digitalWrite()`.


4. Implementing the Arduino Loop() Function:

The `loop()` function runs continuously after the `setup()` function completes. We'll include our main code logic here. Replace the existing `loop()` function with the following code:


void loop() {

  int distance = sonar.ping_cm(); // Measure the distance in centimeters


  if (distance > 0 && distance <= MAX_DISTANCE) {

    activateSanitizer(); // Call the function to activate the sanitizer

  }


  delay(50); // Small delay between sensor readings for stability

}


In this code block, we use the `sonar.ping_cm()` function from the NewPing library to measure the distance detected by the ultrasonic sensor. If the measured distance is within the acceptable range (0 to MAX_DISTANCE), we call the `activateSanitizer()` function to trigger the sanitizer mechanism. We also include a small delay of 50 milliseconds to stabilize the sensor readings



Part 4: Completing the Arduino Code


5. Implementing the activateSanitizer() Function:

Now, let's write the `activateSanitizer()` function that controls the servo motor and the liquid pump. Add the following code outside of the `setup()` and `loop()` functions:


void activateSanitizer() {

  Serial.println("Hand detected! Activating sanitizer...");


  servo.write(90); // Rotate the servo to the desired angle (adjust as needed)

  delay(pumpDelay); // Wait for the specified pump activation delay

  digitalWrite(PUMP_PIN, HIGH); // Turn on the sanitizer pump

  delay(pumpDelay); // Keep the pump active for the specified duration

  digitalWrite(PUMP_PIN, LOW); // Turn off the sanitizer pump

  servo.write(0); // Return the servo to its initial position


  Serial.println("Sanitizer dispensed successfully!");

}


In this function, we first print a message to the serial monitor indicating that a hand has been detected. We then use `servo.write()` to rotate the servo motor to a specific angle (e.g., 90 degrees) to trigger the sanitizer release mechanism. After the specified `pumpDelay`, we turn on the liquid pump by setting the `PUMP_PIN` to HIGH. We keep the pump active for the duration of `pumpDelay` and then turn it off by setting the `PUMP_PIN` to LOW. Finally, we return the servo to its initial position (e.g., 0 degrees) using `servo.write()`. We print another message to the serial monitor to indicate the successful dispensing of sanitizer.


6. Uploading the Code to Arduino Uno R3:

Congratulations! You've completed the code for your touchless hand sanitizer dispenser. It's time to upload it to your Arduino Uno R3. Make sure you've selected the correct board and port under the "Tools" menu in the Arduino IDE. Connect your Arduino board to your computer using a USB cable, and click the "Upload" button in the Arduino IDE to upload the code.


7. Testing the Touchless Hand Sanitizer Dispenser:

Once the code is successfully uploaded, disconnect your Arduino board from your computer and power it using the chosen power supply (e.g., 9V battery). Place your hand in front of the ultrasonic sensor, and if everything is set up correctly, the dispenser should trigger the sanitizer release. Adjust the angles and delays in the code as needed to achieve the desired functionality.



Part 5: Enhancements and Additional Features


Welcome back to the second part of our tutorial on building a touchless hand sanitizer dispenser using Arduino Uno R3. In this section, we'll explore some enhancements and additional features to make our dispenser more user-friendly and efficient. Let's get started!


1. Adding LED Indicators:

LEDs can be used to provide visual feedback, indicating the status of the dispenser. For example, you can add a green LED to indicate that the dispenser is ready for use and a red LED to indicate when the sanitizer is being dispensed. Here's how to incorporate LED indicators into our code:


Add the following lines of code at the beginning, after the variable declarations:


   #define GREEN_LED_PIN 6

   #define RED_LED_PIN 7


   void setup() {

     // ...


     pinMode(GREEN_LED_PIN, OUTPUT); // Set the green LED pin as an output

     pinMode(RED_LED_PIN, OUTPUT); // Set the red LED pin as an output

   }


Now, update the `activateSanitizer()` function to include LED control:


   void activateSanitizer() {

     // ...


     digitalWrite(GREEN_LED_PIN, LOW); // Turn off the green LED

     digitalWrite(RED_LED_PIN, HIGH); // Turn on the red LED


     // ...


     digitalWrite(GREEN_LED_PIN, HIGH); // Turn on the green LED

     digitalWrite(RED_LED_PIN, LOW); // Turn off the red LED

   }


In this example, we assume that the green LED is connected to pin 6 and the red LED is connected to pin 7. Modify these pin assignments based on your setup. The LEDs are initially turned off (LOW) in the `setup()` function. When the sanitizer is activated, the green LED turns off, and the red LED turns on. Once the dispensing process is complete, the green LED turns on, and the red LED turns off.


2. Adding a Buzzer for Auditory Feedback:

Another useful addition to our dispenser is a buzzer that provides auditory feedback when the sanitizer is dispensed. Here's how to incorporate a buzzer into our code:


Add the following line of code at the beginning, after the LED pin declarations:


   #define BUZZER_PIN 8


   void setup() {

     // ...


     pinMode(BUZZER_PIN, OUTPUT); // Set the buzzer pin as an output

   }


Update the `activateSanitizer()` function to include buzzer control:


   void activateSanitizer() {

     // ...


     digitalWrite(BUZZER_PIN, HIGH); // Turn on the buzzer

     delay(500); // Buzz for 500 milliseconds (adjust as needed)

     digitalWrite(BUZZER_PIN, LOW); // Turn off the buzzer


     // ...

   }


In this example, we assume that the buzzer is connected to pin 8. Adjust the pin assignment according to your setup. The buzzer is turned on using `digitalWrite(BUZZER_PIN, HIGH)`, and after a brief delay, it's turned off using `digitalWrite(BUZZER_PIN, LOW)`. Modify the delay duration to control the buzzer's buzzing length.


3. Implementing a Refill Indicator:

It's essential to know when the sanitizer container needs to be refilled. To implement a refill indicator, we can utilize the concept of weight sensing. By measuring the weight of the sanitizer container, we can determine its fill level. Here's how to add a refill indicator:


   - Mount a load cell (such as an HX711)


on a stable platform and connect it to the Arduino board. Follow the load cell's datasheet for wiring instructions.


   - Install the HX711 library in the Arduino IDE by going to "Sketch" -> "Include Library" -> "Manage Libraries" and searching for "HX711." Install the library and include it at the beginning of your code:


     #include <HX711.h>


   - Define the necessary pins for the load cell and create an instance of the HX711 class:


     #define LOADCELL_DOUT_PIN 9

     #define LOADCELL_SCK_PIN 10


     HX711 scale;


     void setup() {

       // ...


       scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);

     }


   - Update the `loop()` function to measure the weight and provide a refill indication:


     void loop() {

       // ...


       int weight = scale.read(); // Read the weight from the load cell


       if (weight < 1000) {

         digitalWrite(REFILL_LED_PIN, HIGH); // Turn on the refill indicator LED

       } else {

         digitalWrite(REFILL_LED_PIN, LOW); // Turn off the refill indicator LED

       }


       // ...

     }


In this example, we assume that the refill indicator LED is connected to pin `REFILL_LED_PIN`. Adjust the pin assignment accordingly. The code reads the weight from the load cell using `scale.read()`. If the weight falls below a certain threshold (here, 1000 grams), the refill indicator LED is turned on. Otherwise, it's turned off.


4. Optional: Incorporating a Motion Sensor:

To conserve power and provide an enhanced user experience, we can add a motion sensor to activate the dispenser only when someone approaches. Here's how to include a motion sensor in our project:


   - Choose a suitable motion sensor (e.g., PIR sensor) and connect it to an appropriate digital pin on the Arduino board. Refer to the sensor's datasheet for wiring instructions.


   - Define the pin for the motion sensor and create a variable to track motion status:


     #define MOTION_SENSOR_PIN 11


     bool isMotionDetected = false;


     void setup() {

       // ...


       pinMode(MOTION_SENSOR_PIN, INPUT); // Set the motion sensor pin as an input

     }


   - Update the `loop()` function to check for motion before activating the sanitizer:


     void loop() {

       // ...


       isMotionDetected = digitalRead(MOTION_SENSOR_PIN); // Check the motion sensor status


       if (isMotionDetected && distance > 0 && distance <= MAX_DISTANCE) {

         activateSanitizer(); // Call the function to activate the sanitizer

       }


       // ...

     }


In this code snippet, we assume that the motion sensor is connected to pin `MOTION_SENSOR_PIN`. Modify the pin assignment according to your setup. The code uses `digitalRead()` to check the status of the motion sensor. If motion is detected and the hand is within the specified distance, the sanitizer is activated.



Part 6: Assembling the Touchless Hand Sanitizer Dispenser


Welcome to the final part of our tutorial on building a touchless hand sanitizer dispenser using Arduino Uno R3. In this section, we'll discuss the physical assembly of the dispenser and provide some closing remarks. Let's get started!


1. Mounting the Components:

   Now that we have our hardware setup and the code implemented, it's time to assemble the physical components of the dispenser. Here are some general steps to guide you:


   - Find a suitable enclosure or housing for your dispenser. It should be large enough to accommodate the Arduino board, ultrasonic sensor, servo motor, liquid pump, and any additional components.


   - Mount the Arduino board securely inside the enclosure using screws or mounting brackets.


   - Attach the ultrasonic sensor to the top of the enclosure, facing downwards. Ensure it has a clear line of sight to detect hand movements.


   - Position the servo motor and liquid pump in a way that allows the sanitizer to be dispensed effectively. You may need to experiment with different angles and positions to achieve optimal results.


   - Connect the necessary wires from the components to the Arduino board. Make sure the connections are secure and well-organized to avoid any interference or loose connections.


   - Place the hand sanitizer container in a convenient location within the enclosure. Ensure that it is easily accessible for refilling purposes.


   - Consider adding labels or markings to guide users on where to place their hands for sanitizer dispensing.


2. Powering the Dispenser:

 Choose an appropriate power supply for your dispenser based on the voltage and current requirements of the components. You can use a 9V battery or a USB power source, depending on your preference and availability. Connect the power supply to the Arduino board and ensure that it powers up correctly.


3. Testing and Calibration:

Once the physical assembly is complete, test the dispenser by placing your hand in front of the sensor. Verify that the sanitizer is dispensed properly and all the indicators (LEDs, buzzer, etc.) are functioning as expected. Fine-tune the angles, distances, and timings in the code if necessary to achieve optimal performance.


4. Refining and Customizing:

Feel free to customize the appearance of your dispenser by adding additional design elements, such as graphics or labels. You can also explore using different types of sensors or actuators to enhance its functionality further. The possibilities are endless!


Congratulations on successfully building your touchless hand sanitizer dispenser using Arduino Uno R3! By combining the power of hardware and software, you've created a convenient and hygienic solution for promoting hand hygiene.


Remember, this project serves as a starting point, and you can always expand and improve upon it. Consider integrating additional features, such as data logging, wireless connectivity, or smartphone integration, to make it even more versatile and connected.


We hope you enjoyed this tutorial and found it informative. Don't forget to share your creations with others and inspire fellow makers in the community. Keep exploring, learning, and using your technical skills to make a positive impact in the world.


Stay safe, stay curious, and happy tinkering!



Future improvements


Here are a few suggestions for future improvements and enhancements to the touchless hand sanitizer dispenser:


1. Smart Connectivity: Consider adding wireless connectivity, such as Wi-Fi or Bluetooth, to the dispenser. This would allow you to monitor the sanitizer levels, track usage statistics, and receive notifications for refills or maintenance needs. You could also implement remote control or automation features through a mobile app or web interface.


2. Touchless Activation: Explore alternative methods for touchless activation. For example, you could incorporate gesture recognition or proximity sensors to detect hand movements without physical contact. This would enhance the user experience and improve the overall hygiene of the dispenser.


3. User Interface: Integrate a user interface to provide visual feedback and control options. This could include an LCD screen or a touch panel to display important information like sanitizer levels, dispenser status, or instructions for use. It could also allow users to adjust settings or select different sanitizer options.


4. Sanitizer Dispensing Options: Expand the dispenser's functionality by incorporating multiple sanitizer dispensing options. For instance, you could have different nozzles or settings for foam-based sanitizers or different sanitizer strengths. This would cater to varying user preferences and requirements.


5. Automatic Refilling: Implement an automatic refilling system to ensure a continuous supply of sanitizer. This could involve sensors to detect the sanitizer level in the container and automatically trigger a refill process when it falls below a certain threshold. It would save time and effort in manual refilling.


6. Data Analytics: Collect and analyze usage data to gain insights into hand hygiene patterns, peak usage times, or areas of high demand. This information could be valuable for facilities management, hygiene audits, or identifying areas for improvement in public health initiatives.


7. Integration with Access Control Systems: Integrate the dispenser with access control systems, such as RFID or biometric systems, to ensure that sanitizer is dispensed before entering specific areas. This would reinforce hygiene practices and help maintain a sanitized environment.


8. Energy Efficiency: Optimize power consumption by implementing sleep modes or power management techniques when the dispenser is not in use. This would prolong battery life, reduce electricity costs, and make the dispenser more environmentally friendly.


Remember, these suggestions are meant to inspire you to explore and innovate further with your touchless hand sanitizer dispenser project. Adapt and customize them according to your specific needs and creativity. Good luck with your future improvements!


Indoor Air Quality Monitor with ESP32 and BME680 Sensor

In this guide, I will explain how to build an indoor air quality monitor using the ESP32 microcontroller and the BME680 sensor. We will be utilizing the power of the ESP32 to monitor various parameters of air quality, such as temperature, humidity, pressure, and gas levels. The BME680 sensor is a versatile and highly accurate sensor that combines all these capabilities into a single compact module.


Part 1: Getting started


In this blog post, I will walk you through the entire process of setting up the hardware, writing the code, and deploying the project. By the end, you will have a fully functional air quality monitor that can provide you with valuable insights into the air quality in your indoor environment. So let's get started!


Hardware Setup:


To begin with, let's gather all the necessary components for this project. Here's a list of what you'll need:


1. ESP32 Development Board: The ESP32 is a powerful microcontroller with built-in Wi-Fi and Bluetooth capabilities. It will serve as the brain of our air quality monitor.

2. BME680 Sensor: The BME680 sensor is a popular environmental sensor module that measures temperature, humidity, pressure, and gas levels.

3. Breadboard and Jumper Wires: These will help us connect the components together.

4. Micro USB Cable: This will be used to power the ESP32 development board.


Now that we have all the components, let's move on to the hardware setup:


Step 1: Connect the BME680 Sensor to the ESP32


Start by placing the ESP32 development board on the breadboard. Ensure that it is firmly seated. Next, connect the BME680 sensor to the ESP32 using jumper wires. Make the following connections:


- Connect the VCC pin of the BME680 sensor to the 3.3V pin on the ESP32.

- Connect the GND pin of the BME680 sensor to the GND pin on the ESP32.

- Connect the SDA pin of the BME680 sensor to the SDA pin on the ESP32.

- Connect the SCL pin of the BME680 sensor to the SCL pin on the ESP32.


Ensure that the connections are secure and there are no loose wires.


Step 2: Power the ESP32 Development Board


Take the micro USB cable and connect it to the USB port of the ESP32 development board. The other end of the cable can be connected to a USB power source, such as a computer or a USB wall adapter. This will provide power to the ESP32 board.


Part 2: Software Setup and Coding


Title: Building an Advanced Indoor Air Quality Monitor with ESP32 and BME680 Sensor


Software Setup:


Now that we have our hardware set up, let's move on to the software setup. In this section, we will install the necessary libraries and set up the development environment for programming the ESP32.


Step 1: Install Arduino IDE


To program the ESP32, we will be using the Arduino IDE. If you haven't installed it already, you can download it from the official Arduino website (https://www.arduino.cc/en/software) and follow the installation instructions specific to your operating system.


Step 2: Install ESP32 Board Support


Once the Arduino IDE is installed, we need to add support for the ESP32 development board. Open the Arduino IDE and navigate to "File" > "Preferences". In the "Additional Boards Manager URLs" field, enter the following URL:


https://dl.espressif.com/dl/package_esp32_index.json


Click "OK" to save the preferences. Then, navigate to "Tools" > "Board" > "Boards Manager". Search for "esp32" and click on the "esp32 by Espressif Systems" option. Click "Install" to install the ESP32 board support.


Step 3: Select ESP32 Board and Port


Connect the ESP32 development board to your computer using the micro USB cable. In the Arduino IDE, navigate to "Tools" > "Board" and select "ESP32 Dev Module" from the list of available boards.


Next, navigate to "Tools" > "Port" and select the port to which the ESP32 board is connected. The port should have "ESP32" mentioned in its name.


With the software setup complete, let's move on to writing the code for our air quality monitor.


Coding:


In this section, we will write the code that will allow the ESP32 to read data from the BME680 sensor and transmit it over a network connection. We will be using the BME680 library, which provides an easy-to-use interface for interacting with the sensor.


Step 1: Install BME680 Library

In the Arduino IDE, navigate to "Sketch" > "Include Library" > "Manage Libraries". In the Library Manager, search for "BME680" and click on the "BME680 by Bosch Sensortec" option. Click "Install" to install the BME680 library.


Step 2: Open a New Sketch

In the Arduino IDE, navigate to "File" > "New" to open a new sketch.


Step 3: Write the Code

Copy and paste the following code into the Arduino IDE:


#include <Wire.h>

#include <Adafruit_Sensor.h>

#include <Adafruit_BME680.h>


Adafruit_BME680 bme;


void setup() {

  Serial.begin(9600);

  while (!Serial);


  if (!bme.begin(0x76)) {

    Serial.println("Could not find a valid BME680 sensor, check wiring!");

    while (1);

  }


  Serial.println("Air Quality Monitor");

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

}


void loop() {

  if (!bme.performReading()) {

    Serial.println("Failed to perform reading!");

    return;

  }


  float temperature = bme.temperature;

  float humidity = bme.humidity;

  float pressure = bme.pressure / 100.0;

  float gas = bme.gas_resistance / 1000.0;


  Serial.print("Temperature: ");

  Serial.print(temperature);

  Serial.println(" °C");


  Serial.print("Humidity: ");

  Serial.print(humidity);

  Serial.println(" %");


  Serial


.print("Pressure: ");

  Serial.print(pressure);

  Serial.println(" hPa");


  Serial.print("Gas Resistance: ");

  Serial.print(gas);

  Serial.println(" KOhms");


  delay(5000);

}


This code initializes the BME680 sensor and continuously reads temperature, humidity, pressure, and gas resistance values from the sensor. It then prints the values to the serial monitor. The delay of 5000 milliseconds (5 seconds) between readings ensures that the sensor is not polled too frequently.


Step 4: Upload the Code

Click on the "Upload" button in the Arduino IDE to compile and upload the code to the ESP32 board. You should see the status messages in the bottom panel of the IDE.


Once the code is successfully uploaded, open the serial monitor by navigating to "Tools" > "Serial Monitor" or by pressing "Ctrl+Shift+M". Set the baud rate to 9600 to match the value specified in the code.


Part 3: Interpreting Sensor Readings and Enhancing Functionality


Interpreting Sensor Readings:

Now that we have our code uploaded and the sensor readings displayed on the serial monitor, let's dive into interpreting the sensor readings and understanding the air quality in our indoor environment.


1. Temperature:

The temperature reading provides information about the ambient temperature in degrees Celsius. It can help us monitor temperature variations and ensure that the indoor environment is within a comfortable range.


2. Humidity:

The humidity reading indicates the amount of moisture in the air as a percentage. Higher humidity levels can contribute to discomfort and potential mold growth, while lower humidity levels can lead to dryness and respiratory problems. It's important to maintain an optimal humidity level for a healthy indoor environment.


3. Pressure:

The pressure reading gives us an idea of the atmospheric pressure in hectopascals (hPa). Monitoring pressure levels can be useful for predicting weather patterns and detecting changes in air pressure that may affect the indoor environment.


4. Gas Resistance:

The gas resistance reading measures the resistance of the gas sensor in kilohms (KOhms). It provides an indication of the air quality in terms of volatile organic compounds (VOCs) and other gases present in the environment. Higher gas resistance values may indicate poorer air quality, while lower values may indicate better air quality.


By monitoring these sensor readings, we can gain insights into the air quality in our indoor environment and take appropriate measures to maintain a healthy living or working space.


Enhancing Functionality:

While the current code provides basic functionality by displaying sensor readings on the serial monitor, we can enhance the functionality of our air quality monitor by incorporating additional features. Let's explore a few possibilities:


1. Displaying Readings on an LCD:

Instead of relying on the serial monitor, we can connect an LCD display to the ESP32 and show the sensor readings in real-time. This allows for a more convenient and user-friendly interface.


2. Adding Wi-Fi Connectivity:

By integrating Wi-Fi capabilities, we can transmit the sensor readings to a web server or a cloud platform. This enables remote monitoring and data visualization, providing access to air quality information from anywhere with an internet connection.


3. Implementing Data Logging:

To analyze air quality trends over time, we can incorporate data logging functionality. By storing the sensor readings in a file or a database, we can generate graphs and perform statistical analysis to gain deeper insights into air quality patterns.


4. Setting Thresholds and Alerts:

To ensure prompt action in case of deteriorating air quality, we can set threshold values for each parameter. If any reading exceeds the defined thresholds, the system can trigger alerts through notifications, email, or even audible alarms.


These are just a few ideas to enhance the functionality of our air quality monitor. Depending on your requirements and creativity, you can further customize and expand the capabilities of your project.


Part 4: Adding Wi-Fi Connectivity and Data Transmission


Adding Wi-Fi Connectivity:


In this section, we will enhance our air quality monitor by adding Wi-Fi connectivity to transmit sensor readings to a web server. This will enable remote monitoring and data visualization, providing a convenient way to access air quality information from anywhere with an internet connection.


Step 1: Include Required Libraries

To add Wi-Fi functionality, we need to include the necessary libraries. Add the following lines of code at the beginning of your sketch, before the setup() function:


#include <WiFi.h>

#include <HTTPClient.h>


Step 2: Set Up Wi-Fi Credentials

In the setup() function, we need to configure the Wi-Fi connection. Replace the existing setup() function with the following code:


void setup() {

  Serial.begin(9600);

  while (!Serial);


  if (!bme.begin(0x76)) {

    Serial.println("Could not find a valid BME680 sensor, check wiring!");

    while (1);

  }


  Serial.println("Air Quality Monitor");

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


  // Connect to Wi-Fi network

  WiFi.begin("Your_SSID", "Your_Password");


  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);

    Serial.println("Connecting to Wi-Fi...");

  }


  Serial.println("Connected to Wi-Fi!");

  Serial.print("IP Address: ");

  Serial.println(WiFi.localIP());

}


Replace "Your_SSID" and "Your_Password" with the credentials of your Wi-Fi network. This code connects the ESP32 to the Wi-Fi network and displays the assigned IP address on the serial monitor.


Step 3: Transmit Sensor Readings to a Web Server

To transmit the sensor readings to a web server, add the following code inside the loop() function, after printing the sensor readings:


  // Create an HTTPClient object

  HTTPClient http;


  // Construct the URL for the web server

  String url = "http://your-web-server.com/air-quality-update?temperature=";

  url += temperature;

  url += "&humidity=";

  url += humidity;

  url += "&pressure=";

  url += pressure;

  url += "&gas=";

  url += gas;


  // Send the HTTP GET request

  http.begin(url);

  int httpResponseCode = http.GET();


  // Check for successful response

  if (httpResponseCode == 200) {

    Serial.println("Data transmitted successfully!");

  } else {

    Serial.print("Error in HTTP GET request. Error code: ");

    Serial.println(httpResponseCode);

  }


  // Close the connection

  http.end();


  delay(5000);


Replace "http://your-web-server.com/air-quality-update" with the URL or endpoint where you want to send the sensor readings. This code constructs the URL with the sensor readings as query parameters and sends an HTTP GET request to the web server. It then checks the response code and displays the appropriate message on the serial monitor.


Make sure to adapt the server-side code to receive the GET request and store the sensor readings in your desired format or database.


Step 4: Upload the Updated Code

Upload the updated code to the ESP32 board by clicking on the "Upload" button in the Arduino IDE.


Now, the ESP32 will connect to your Wi-Fi network and transmit the sensor readings to the specified web server at regular intervals.


Part 5: Conclusion and Further Enhancements


Conclusion:

Congratulations! You have successfully built an advanced indoor air quality monitor using the ESP32 microcontroller and the BME680 sensor. Throughout this project, we covered the hardware setup, software setup, coding, interpreting sensor readings, and enhancing the functionality of the air quality monitor. By incorporating Wi-Fi connectivity, we enabled remote monitoring and data transmission to a web server, providing access to air quality information from anywhere.


With this air quality monitor, you can now gain valuable insights into the temperature, humidity, pressure, and gas levels in your indoor environment. This information can help you make informed decisions about ventilation, air purification, and overall comfort in your living or working space.


Further Enhancements:

While we have covered a range of features and enhancements in this project, there are still plenty of opportunities for further customization and improvements. Here are a few ideas to take your air quality monitor to the next level:


1. Mobile App Integration:

Develop a mobile app that can connect to the ESP32 via Wi-Fi and display real-time sensor readings. This provides a more intuitive and user-friendly interface, allowing users to monitor air quality on their smartphones.


2. Data Visualization:

Instead of just transmitting sensor readings to a web server, create a visually appealing dashboard to display historical data and trends. Graphs, charts, and analytics can provide a more comprehensive view of air quality patterns over time.


3. Machine Learning and Predictive Analysis:

Utilize machine learning algorithms to analyze the sensor data and predict future air quality trends. This can help identify potential issues in advance and take preventive measures to maintain a healthy environment.


4. Integration with Smart Home Systems:

Integrate your air quality monitor with existing smart home systems such as Amazon Alexa or Google Home. This allows you to control ventilation systems, air purifiers, or other smart devices based on the air quality readings.


Remember, the possibilities are endless when it comes to customization and expanding the functionality of your air quality monitor. Feel free to explore additional features that align with your specific needs and interests.


I hope you enjoyed this technical blog post and found it helpful in your journey of building an advanced indoor air quality monitor. Happy tinkering!