Wi-Fi Signal Strength Mapper using ESP32

Hey there, fellow DIY enthusiasts! Today, I'll walk you through an exciting project: building an ESP32 Wi-Fi Signal Strength Mapper. This little device will help you map the Wi-Fi signal strength in different areas of your home or workspace, allowing you to find the best spots for strong and stable connectivity. It's a perfect blend of programming and electronics, leveraging the powerful capabilities of the ESP32. Let’s dive right into it!


Before we get started, make sure you have the following components:


- ESP32 development board (any model with Wi-Fi capability)

- Micro USB cable for programming the ESP32

- Laptop/PC with the Arduino IDE installed

- Breadboard and jumper wires (optional for testing)

- OLED Display (128x64 I2C) (optional, for displaying signal strength in real-time)

  

Step 1: Setting Up the Arduino IDE for ESP32


If you haven't set up the Arduino IDE to program the ESP32, follow these steps:


1. Open the Arduino IDE.

2. Go to File > Preferences.

3. In the Additional Boards Manager URLs field, paste the following link:

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

4. Go to Tools > Board > Boards Manager, search for "ESP32", and install the ESP32 by Espressif Systems package.

5. Select your ESP32 board from Tools > Board > ESP32 Dev Module.


Step 2: Understanding Wi-Fi Signal Strength Mapping


The ESP32 has a built-in Wi-Fi library that allows it to scan nearby networks and measure their RSSI (Received Signal Strength Indicator) values. The RSSI is a measure of the power level that a device receives from a Wi-Fi access point (AP). In simpler terms, it tells you how strong or weak the Wi-Fi signal is in a particular spot.


RSSI Range Interpretation:


- -30 dBm to -50 dBm: Excellent signal

- -51 dBm to -60 dBm: Good signal

- -61 dBm to -70 dBm: Fair signal

- -71 dBm to -90 dBm: Weak signal

- Below -90 dBm: Extremely poor or no signal


Step 3: Writing the Code


Now, let's write the code that will scan nearby Wi-Fi networks, read their RSSI values, and display the results either through the serial monitor or on an OLED display. If you don't have an OLED, you can skip the display part.


#include <WiFi.h>

#include <Wire.h>

#include <Adafruit_GFX.h>

#include <Adafruit_SSD1306.h>


// Define OLED display width and height

#define SCREEN_WIDTH 128

#define SCREEN_HEIGHT 64


// Define the OLED reset pin (if required)

#define OLED_RESET -1


// Create an OLED display object

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);


void setup() {

    // Initialize serial communication

    Serial.begin(115200);

    

    // Initialize the OLED display

    if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {

        Serial.println("OLED display failed to initialize");

        while (true);

    }


    display.clearDisplay();

    display.setTextSize(1);

    display.setTextColor(SSD1306_WHITE);

    display.setCursor(0, 0);

    display.println("Wi-Fi Signal Mapper");

    display.display();

    

    // Start Wi-Fi in station mode

    WiFi.mode(WIFI_STA);

    WiFi.disconnect();

    delay(100);

}


void loop() {

    Serial.println("Scanning for Wi-Fi networks...");

    int numberOfNetworks = WiFi.scanNetworks();

    

    display.clearDisplay();

    display.setCursor(0, 0);

    display.println("Scanning...");

    display.display();

    delay(500);


    for (int i = 0; i < numberOfNetworks; i++) {

        // Print each network's SSID and RSSI to the serial monitor

        Serial.print("Network: ");

        Serial.println(WiFi.SSID(i));

        Serial.print("Signal strength (RSSI): ");

        Serial.print(WiFi.RSSI(i));

        Serial.println(" dBm");


        // Display SSID and RSSI on OLED (if available)

        display.setCursor(0, (i * 10) + 10);

        display.print(WiFi.SSID(i).substring(0, 10)); // Display first 10 characters of SSID

        display.print(": ");

        display.print(WiFi.RSSI(i));

        display.print(" dBm");

        display.display();

        delay(500);

    }

    

    // Wait before scanning again

    delay(5000);

}


Step 4: Uploading the Code to the ESP32


1. Connect your ESP32 to your computer using the USB cable.

2. Select the correct Port and Board under the Tools menu.

3. Click the Upload button (right arrow icon) in the Arduino IDE.

4. Once the upload is complete, open the Serial Monitor (Tools > Serial Monitor) to see the Wi-Fi networks and their RSSI values.


Step 5: Testing the Mapper


Now that the code is running on the ESP32, it's time to test it out!


- Serial Monitor Output: As you move around with the ESP32, you will see the list of detected Wi-Fi networks and their corresponding RSSI values in the Serial Monitor. Note how the RSSI changes as you move closer or further from the Wi-Fi access point.


- OLED Display Output: If you're using an OLED display, it will show the SSID of the nearby networks and their signal strengths in dBm. This makes it even easier to visualize the strength of each network as you move around.


Step 6: Using the Mapper for Site Surveys


Now that you have a working Wi-Fi signal strength mapper, you can use it to:


- Find the Best Wi-Fi Spots: Walk around your space to identify areas with strong Wi-Fi signals.

- Identify Dead Zones: Map out areas where the signal drops or is too weak to use.

- Optimize Router Placement: Use the RSSI values to help find the best place to position your router for optimal coverage.


Optional: Adding Data Logging


If you want to take this project a step further, you could add data logging to store the Wi-Fi signal strength values with timestamps in a microSD card or even send the data to a Google Sheet using the ESP32's Wi-Fi capabilities. That way, you can create a comprehensive map of your Wi-Fi signal strength over time!


Conclusion


And there you have it! A fully functional ESP32 Wi-Fi Signal Strength Mapper. This project is a great way to learn about Wi-Fi protocols, RSSI, and the ESP32's capabilities. Plus, it's super practical for everyday use in optimizing your home or office Wi-Fi setup.


I hope you found this tutorial helpful. Happy building, and see you in the next project!


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!