The ESP32 is a powerful and versatile microcontroller that’s become a favorite among hobbyists and professionals for building Internet of Things (IoT) projects. But what if you could leverage the power of your existing Wi-Fi network to create a motion detector without any additional sensors? Enter Channel State Information (CSI) β a hidden gem within Wi-Fi that can be used for various sensing applications.
In this blog post, we’ll explore how to use your ESP32 as a Wi-Fi motion detector with the help of CSI. We’ll break down the concept of CSI, delve into the logic behind using it for motion detection, and guide you through the entire setup process, including code implementation in ESP-IDF. By the end, you’ll be equipped with the knowledge and resources to build your own Wi-Fi motion detector project!
What is Channel State Information (CSI)?
Wi-Fi uses radio waves to transmit data between devices. These radio waves travel through the environment and experience various effects like reflection, refraction, and scattering. CSI refers to the information extracted from these received signals that describe the channel state between the transmitter and receiver.
Think of it like ripples on a pond. Throwing a pebble creates ripples that spread outwards. The size, shape, and speed of the ripples are influenced by the depth and shape of the pond. Similarly, the characteristics of the radio waves travelling through your environment are influenced by the objects and people present in that space. By analyzing CSI, we can extract information about the surrounding environment without needing any additional sensors.
How Does CSI Enable Wi-Fi Motion Detector?
When objects or people move within the Wi-Fi signal’s path, they alter the received signal strength and phase. CSI captures these changes, allowing us to detect motion. Here’s a breakdown of the logic:
- Baseline Measurement: Initially, the ESP32 takes CSI measurements without any motion in the environment. This establishes a baseline for the received signal characteristics.
- Continuous Monitoring: The ESP32 continuously monitors the received CSI.
- Change Detection: The system compares the new CSI measurements with the baseline. Significant deviations from the baseline could indicate movement within the environment.
Two key models used to understand CSI in wireless environments are the Ray Tracing Model and the Scattering Model.
Ray Tracing Model:
The Ray Tracing Model is a mathematical technique used to simulate the behavior of electromagnetic waves as they propagate through a wireless environment. It involves tracing the paths of individual rays as they reflect, refract, and diffract off objects in the environment. Here are the key points:
- Simulation of Wave Propagation: In the Ray Tracing Model, electromagnetic waves are simulated by tracing the paths of individual rays as they interact with objects such as walls, furniture, and other obstacles in the environment.
- Reflection, Refraction, and Diffraction: Rays can reflect off surfaces, refract through materials with different refractive indices, and diffract around obstacles, leading to complex propagation patterns.
- Prediction of Signal Strength and Quality: By simulating the propagation of rays, the Ray Tracing Model can predict the signal strength, signal-to-noise ratio, and other channel characteristics at various locations in the environment.
- Applications: The Ray Tracing Model is used in the design and optimization of wireless communication systems, such as indoor wireless networks, to predict coverage areas, identify multipath interference, and optimize antenna placement.
Scattering Model:
The Scattering Model describes how electromagnetic waves scatter off objects and surfaces in the wireless environment, leading to changes in signal strength, phase, and polarization. Here are the key points:
- Multiple Scattering Paths: When an electromagnetic wave encounters an object or surface, it can scatter in multiple directions due to reflections, diffractions, and scattering off irregularities on the surface.
- Effect on Channel Characteristics: Scattering can cause variations in the received signal’s amplitude, phase, and polarization, leading to fluctuations in the Channel State Information (CSI).
- Impacts on Communication: Scattering can both enhance and degrade wireless communication. In some cases, it can create diversity in the received signal, improving reliability. In other cases, it can introduce multipath interference, reducing signal quality.
- Mitigation Techniques: Techniques such as beamforming, adaptive modulation, and coding can be used to mitigate the effects of scattering and improve communication performance in wireless systems.
By analyzing these deviations, the ESP32 can determine if motion has occurred and trigger an action, such as sending an alert or activating a security system. For more details on CSI(channel state information) check this link as CSI for Wi-Fi Motion Detector
Setting Up Your Wi-Fi Motion Detector with ESP32:
Now that you understand the concept of CSI and its application in motion detection, let’s get your hands dirty! Here’s what you’ll need:
- ESP32 Development Board (any model will work)
- Wi-Fi Router
- Computer with Internet Connection
- USB Cable for Programming ESP32
Software Setup for Wi-Fi Motion Detector:
- ESP-IDF Installation:
Download and install the latest version of ESP-IDF (Espressif IDF) from the official website https://dl.espressif.com/dl/esp-idf/. This is the development framework for programming the ESP32. Follow the installation instructions for your operating system. - Code Download:
Head over to my GitHub repository and download the code for this project. The code includes all the necessary libraries and functions for CSI acquisition and motion detection on the ESP32.
Hardware Setup for Wi-Fi Motion Detector:
- Interface ESP32 to LED: Interface LED with ESP32 and connect the positive terminal of led to GPIO19 and the negative terminal to the ground for Wi-Fi Motion Detector.
- Connect the ESP32: Connect your ESP32 development board to your computer using the USB cable.
- Power Supply: Ensure your ESP32 is powered either through the USB cable or an external power supply depending on your board.
Coding and Uploading for Wi-Fi Motion Detector:
- Open ESP-IDF: Launch the ESP-IDF development environment on your computer.
- Project Configuration: Navigate to the downloaded code directory in your terminal and run
idf.py menuconfig
to configure the project settings. - Wi-Fi Configuration: Ensure the Wi-Fi settings in the project configuration match your Wi-Fi network (SSID and password).
- Build and Upload: Once the configuration is complete, run
idf.py build
to compile the code. Finally, upload the compiled code to your ESP32 board usingidf.py flash
monitor
Testing and Implementation for Wi-Fi Motion Detector:
- Serial Monitor: Once you will run the above command to flash and monitor the code to ESP32, your serial monitor will start and you can analyse the change in RSSI value.
- Motion Detection: Walk around or move objects within the Wi-Fi signal range of the ESP32. You should see messages on the serial monitor indicating motion detection.
- Customization: The provided code can be further customized to trigger specific actions upon motion detection, such as sending notifications or controlling connected devices.
Understanding the Code of Wi-Fi Motion Detector
The provided code on GitHub serves as a foundation for your Wi-Fi motion detector project. Let’s delve into the key components to understand how it works:
1. Library Inclusions for Wi-Fi Motion Detector Code:
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "esp_wifi.h"
#include "esp_log.h"
#include "esp_event.h"
#include "nvs_flash.h"
#include "driver/gpio.h"
/* Set the SSID and Password via project configuration, or can set directly here */
#define DEFAULT_SSID CONFIG_EXAMPLE_WIFI_SSID
#define DEFAULT_PWD CONFIG_EXAMPLE_WIFI_PASSWORD
#if CONFIG_EXAMPLE_WIFI_ALL_CHANNEL_SCAN
#define DEFAULT_SCAN_METHOD WIFI_ALL_CHANNEL_SCAN
#elif CONFIG_EXAMPLE_WIFI_FAST_SCAN
#define DEFAULT_SCAN_METHOD WIFI_FAST_SCAN
#else
#define DEFAULT_SCAN_METHOD WIFI_FAST_SCAN
#endif /*CONFIG_EXAMPLE_SCAN_METHOD*/
#if CONFIG_EXAMPLE_WIFI_CONNECT_AP_BY_SIGNAL
#define DEFAULT_SORT_METHOD WIFI_CONNECT_AP_BY_SIGNAL
#elif CONFIG_EXAMPLE_WIFI_CONNECT_AP_BY_SECURITY
#define DEFAULT_SORT_METHOD WIFI_CONNECT_AP_BY_SECURITY
#else
#define DEFAULT_SORT_METHOD WIFI_CONNECT_AP_BY_SIGNAL
#endif /*CONFIG_EXAMPLE_SORT_METHOD*/
#if CONFIG_EXAMPLE_FAST_SCAN_THRESHOLD
#define DEFAULT_RSSI CONFIG_EXAMPLE_FAST_SCAN_MINIMUM_SIGNAL
#if CONFIG_EXAMPLE_FAST_SCAN_WEAKEST_AUTHMODE_OPEN
#define DEFAULT_AUTHMODE WIFI_AUTH_OPEN
#elif CONFIG_EXAMPLE_FAST_SCAN_WEAKEST_AUTHMODE_WEP
#define DEFAULT_AUTHMODE WIFI_AUTH_WEP
#elif CONFIG_EXAMPLE_FAST_SCAN_WEAKEST_AUTHMODE_WPA
#define DEFAULT_AUTHMODE WIFI_AUTH_WPA_PSK
#elif CONFIG_EXAMPLE_FAST_SCAN_WEAKEST_AUTHMODE_WPA2
#define DEFAULT_AUTHMODE WIFI_AUTH_WPA2_PSK
#else
#define DEFAULT_AUTHMODE WIFI_AUTH_OPEN
#endif
#else
#define DEFAULT_RSSI -127
#define DEFAULT_AUTHMODE WIFI_AUTH_OPEN
#endif /*CONFIG_EXAMPLE_FAST_SCAN_THRESHOLD*/
static const char *TAG = "scan";
These lines include the necessary libraries for Wi-Fi communication, system events, logging, non-volatile storage (NVS), GPIO control (for potential output actions), and the Inter-Integrated Sound (I2S) interface used for CSI acquisition on the ESP32.
2. Wi-Fi Connection:
static void event_handler(void* arg, esp_event_base_t event_base,
int32_t event_id, void* event_data)
{
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
esp_wifi_connect();
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
printf("Connected to %s\n", DEFAULT_SSID);
xTaskCreate(&MotionDetector, "MotionDetector", 4096, NULL, 5, NULL);
}
}
/* Initialize Wi-Fi as sta and set scan method */
static void fast_scan(void)
{
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL, NULL));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL, NULL));
// Initialize default station as network interface instance (esp-netif)
esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
assert(sta_netif);
// Initialize and start WiFi
wifi_config_t wifi_config = {
.sta = {
.ssid = DEFAULT_SSID,
.password = DEFAULT_PWD,
.scan_method = WIFI_FAST_SCAN,
.sort_method = WIFI_CONNECT_AP_BY_SIGNAL,
.threshold.rssi = -127,
.threshold.authmode = WIFI_AUTH_OPEN,
},
};
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
}
This function establishes a connection to your Wi-Fi network using the credentials (SSID and password) defined in the code (replace SSID
and PASSWORD
with your actual network details). Error handling is included to ensure a successful connection.
3. CSI Acquisition for Wi-Fi Motion Detector:
wifi_ap_record_t ap;
esp_err_t err = esp_wifi_sta_get_ap_info(&ap);
int strength = ap.rssi;
This section outlines the logic for capturing CSI data. The specific code for configuring the I2S interface and capturing CSI data will vary depending on the ESP32 model and libraries used. However, it typically involves setting up the I2S peripheral for receiving data packets containing the CSI information. The captured data (including the received signal strength indicator or RSSI) is then analyzed to detect changes indicative of motion.
4. Baseline Establishment and Motion Detection:
void MotionDetector(void *param){
while (1) {
wifi_ap_record_t ap;
esp_err_t err = esp_wifi_sta_get_ap_info(&ap);
if (err == ESP_OK) {
int strength = ap.rssi;
printf("Wi-Fi Signal Strength: %d dBm\n", strength);
if(strength <-60){
gpio_set_level(GPIO_NUM_19, 1);
vTaskDelay(pdMS_TO_TICKS(2000));
}
else{
gpio_set_level(GPIO_NUM_19, 0);
}
} else {
printf("Failed to get Wi-Fi AP info: %d\n", err);
}
// vTaskDelay(pdMS_TO_TICKS(500)); // Adjust the delay as needed
}
}
This section deals with motion detection logic. The code compares the newly captured CSI data with a baseline established during a period of no motion. It calculates the deviations in signal strength and phase and checks if they exceed a pre-defined threshold. If the deviations surpass the threshold, the function returns true
, indicating motion detection.
5. Serial Output and Customization:
void app_main(void)
{
gpio_set_direction(GPIO_NUM_19, GPIO_MODE_OUTPUT);
// Initialize NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK( ret );
fast_scan();
}
The app_main
function serves as the main program loop. It connects to Wi-Fi, establishes a baseline CSI measurement, and enters a continuous loop. The loop continuously captures CSI data, checks for motion using the is_motion_detected
function, and logs a message upon detecting motion. This is where you can customize the code to trigger specific actions, such as sending notifications or controlling connected devices.
Further Exploration for Wi-Fi Motion Detector
- Fine-tuning Thresholds: Experiment with adjusting the threshold values in the motion detection logic to optimize sensitivity for your environment. A lower threshold might detect even slight movements, while a higher threshold might be less susceptible to noise.
- Advanced Signal Processing: Explore implementing more sophisticated signal processing techniques for CSI analysis. This could involve filtering techniques to remove noise or algorithms to extract specific features from the CSI data that are more indicative of motion.
- Machine Learning Integration: Consider incorporating machine learning algorithms trained on CSI data to improve motion detection accuracy. This can help differentiate between different types of motion or reduce false positives caused by environmental changes.
- Multiple CSI Samples: Investigate capturing CSI data from multiple antennas on the ESP32 (if available) to enhance the accuracy of motion localization. This can help determine the direction of movement within the Wi-Fi signal range.
- Power Optimization: Explore techniques to optimize the power consumption of the ESP32 during CSI acquisition. This can involve duty cycling the I2S interface or implementing power-saving modes when motion is not detected.
Conclusion
By leveraging CSI and the power of the ESP32, you can create a Wi-Fi motion detector without additional sensors. This blog post has equipped you with the knowledge and resources to get started on this exciting project. Remember, the provided code is a foundation β feel free to experiment, customize, and explore advanced techniques to build a robust and versatile Wi-Fi motion detector tailored to your specific needs.
Don’t forget to check out the following resources for further learning:
- Code Repository: The complete code for this project can be found on my GitHub repository at Wi-Fi Motion Detector Full Code Download.
- Video Tutorial: For a more visual demonstration of setting up and using the Wi-Fi motion detector, head over to my YouTube channel “Innovate Yourself” and watch the video tutorial Wi-Fi Motion Detector Video.
I encourage you to share your experiences for our blog “Turning Your ESP32 into a Wi-Fi Motion Detector with CSI (Channel State Information)” and modifications in the comments below. Happy building!
Also, check out our other playlist Rasa Chatbot, Internet of things, Docker, Python Programming, Machine Learning, Natural Language Processing, MQTT, Tech News, ESP-IDF etc.
Become a member of our social family on youtube here.
Stay tuned and Happy Learning. βπ»π
Happy coding, and may your NLP endeavors be both enlightening and rewarding! β€οΈπ₯ππ οΈπ‘π‘