G2: ESP32 Smart Study Desk - shalan/CSCE4301-WiKi GitHub Wiki

Submitted By:

GitHub Repository:

Abstract:

The Smart Study Desk is a comprehensive Internet of Things (IoT) solution engineered to optimize productivity and physical comfort in academic and professional environments. Leveraging the ESP32 microcontroller's dual-core processing capabilities, the system actively manages workspace conditions. The final implementation features automated lighting control based on ambient lux levels, an active cooling system utilizing a DC fan triggered by thermal thresholds, and a "Focus Enforcer" module that utilizes presence detection to ensure study session adherence. Furthermore, the system employs Wi-Fi telemetry to log performance metrics to an SQL server, visualizing data through a custom web dashboard.

Introduction & Background:

Problem Statement:

In an era defined by remote work, environmental stressors significantly reduce cognitive performance. Our research identified three primary friction points:

  • Visual Strain: Inconsistent lighting leads to eye fatigue.
  • Thermal Discomfort: High temperatures cause drowsiness; manual fan adjustment breaks concentration.
  • Behavioral Drift: Without accountability, users take frequent, unmonitored breaks.

Project Objectives:

  • Automation: Eliminate manual adjustments for lights and cooling.
  • Enforcement: Provide behavioral nudges (buzzer alerts) when study schedules are violated.
  • Analytics: Provide data-driven insights into study habits via a cloud dashboard.

Proposed Components:

Controller (ESP32) LDR Module Sound Sensor
PIR Motion Sensor DHT22 (Climate) Actuators (Relay)
Active Buzzer LCD Display (I2C) Speaker Module

System Architecture:

High-Level Design:

The system utilizes a star topology where the ESP32-WROOM-32 serves as the central node, managing sensors, actuators, and Wi-Fi telemetry simultaneously.

System Block Diagram:

graph TD;
    subgraph Sensors [Input Sensors]
        direction LR
        DHT[DHT22 Temp]
        LDR[LDR Light]
        PIR[PIR Motion]
    end

    subgraph Controller [Processing]
        ESP32[ESP32 Controller]
    end

    subgraph Actuators [Output Devices]
        direction LR
        Relay[Lamp]
        Fan[DC Fan]
        Buzzer[Active Buzzer]
        LCD[LCD Display]
    end

    subgraph Cloud [Telemetry]
        Web[Web Dashboard]
    end

    %% Wiring
    DHT --> ESP32
    LDR --> ESP32
    PIR --> ESP32

    ESP32 --> Relay
    ESP32 --> Fan
    ESP32 --> Buzzer
    ESP32 --> LCD

    %% Wireless - Direct to Dashboard
    ESP32 -. Wi-Fi .-> Web

Software Stack

  • Framework: ESP-IDF v5.5.1
  • Language: C (ESP32 FreeRTOS)
  • Build System: CMake + Ninja
  • Communication Protocols:   - WiFi (Station mode)   - HTTP Server (Web dashboard)   - I2C (LCD communication)   - PWM/LEDC (Fan control)

Hardware Implementation:

Component Selection Analysis:

  • Controller (ESP32): Selected over Arduino Uno due to its dual-core architecture (allowing Wi-Fi tasks to run on Core 0 while sensor logic runs on Core 1) and higher clock speed (240MHz).
  • Temperature Sensor (DHT22): Selected over DHT11 for its wider range (-40 to 80°C) and better accuracy (±0.5°C).
  • Motion Sensor (HC-SR501 PIR): Configured in "Repeat Trigger" mode to maintain a HIGH signal as long as the user is moving slightly.

Software Logic:

The system logic is divided into three concurrent state machines. The flowchart below illustrates the decision loop, including the data logging to the SQL server.

Control Logic Flowchart:

graph TD;
    Start([Start System]) --> Init[Initialize Sensors & WiFi];
    Init --> ReadSensors[Read DHT22, LDR, PIR];

    %% Moved/Reversed Logic: Data sent immediately after reading
    ReadSensors --> UpdateWeb[Send Data to Dashboard];

    %% Light Control Logic
    ReadSensors --> CheckLight{Light < Threshold?};
    CheckLight -- Yes --> LampON[Lamp ON];
    CheckLight -- No --> LampOFF[Lamp OFF];

    %% Temperature Control Logic (Variable Speed)
    ReadSensors --> CheckTemperature{Temp > Threshold?};
    CheckTemperature -- Yes --> CalcPWM[Calc Speed based on Delta T];
    CalcPWM --> FanPWM[Set Fan Speed PWM];
    CheckTemperature -- No --> FanOFF[Fan OFF];

    %% Presence & Focus Logic
    ReadSensors --> CheckPresence{Motion Detected?};
    
    %% User Present
    CheckPresence -- Yes --> LogTime[Increment Session Timer];

    %% User Absent with Idle Check
    CheckPresence -- No --> CheckIdle{Idle Timeout Exceeded?};
    CheckIdle -- Yes --> TimeoutAction[Trigger Buzzer & Log Violation];
    CheckIdle -- No --> Wait[Maintain Current State];

    %% Synchronization & Display
    LogTime & TimeoutAction & Wait --> UpdateDisplay[Update LCD: Show Session Time];
    
    %% Remaining connection from Display to Web (if applicable based on original logic)
    UpdateDisplay --> UpdateWeb;

Data Analytics Dashboard

The web dashboard provides a comprehensive real-time monitoring interface accessible via WiFi through any web browser. The interface features eight responsive status cards displaying current readings for temperature, humidity, light level, motion detection, LED status, buzzer alerts, fan speed percentage, and session time in HH:MM:SS format. Below the status cards, four interactive Chart.js graphs visualize historical data over a 60-second rolling window: a temperature history line chart in red, humidity history line chart in blue, light level history line chart in yellow, and motion events bar chart in green. The dashboard automatically refreshes every 2 seconds to provide live updates without manual page reload, with all data served through a RESTful JSON API endpoint that transmits current sensor values alongside the complete historical data arrays stored in circular buffers, enabling trend analysis and pattern recognition for environmental monitoring and user activity tracking. 7ba7a446-5a7a-4510-81b6-d878961693dc bb4eb2a2-72e8-4c11-9012-d7f073345850 The web dashboard successfully visualizes:

  • Session Duration: Study hours per day.

  • Heatmap: Temperature spikes during study hours.

  • Violations: Log of buzzer triggers due to prolonged absence.

Challenges Faced:

  • The ESP32 had smaller number of pins compared to other micro-controllers we used like the STM32. This made it difficult to connect a number of peripherals and actuators as we have in our project. We initially set up an LCD but had to change to an I2C LCD so that we can use a smaller number of pins.
  • The ESP32 provided only 5V which made it difficult to power the Fan which needed 12V. We opted for an external battery to power our fan.
  • All the I2C LCDs were taken from the CSCE workshop so it took us time until we independently obtain one.

Code Organization

File Structure

Embedded/
├── main/
│   ├── main.c              (648 lines - all functionality)
│   └── CMakeLists.txt
├── build/                  (Generated build artifacts)
├── CMakeLists.txt          (Project configuration)
├── sdkconfig               (ESP-IDF configuration)

Function Organization in main.c

  1. Includes & Defines (Lines 1-65)
  2. DHT22 Functions (Lines 66-96)
  3. I2C & LCD Functions (Lines 97-174)
  4. Fan PWM Functions (Lines 176-239)
  5. WiFi Functions (Lines 242-272)
  6. HTTP Server & HTML (Lines 275-405)
  7. Sensor Task (Lines 448-558)
  8. Main Entry Point (Lines 561-648)

Implementation:

A. Automatic LED Control (Light-based)

// LED turns on after 5 seconds of low light (<50%)
if (lightPercentage < 50.0) {
    lowLightSeconds += 1;
    if (lowLightSeconds >= 5 && !ledOn) {
        gpio_set_level(LED_PIN, 1);
        ledOn = true;
    }
} else {
    lowLightSeconds = 0;
    if (ledOn) {
        gpio_set_level(LED_PIN, 0);
        ledOn = false;
    }
}

B. Buzzer Alert System (Motion-based)

// Buzzer activates after 10 seconds of no motion
if (motionDetected) {
    noMotionSeconds = 0;
    if (buzzerOn) {
        gpio_set_level(BUZZER_PIN, 0);
        buzzerOn = false;
        sessionActive = true;
        sessionSeconds = 0;  // Reset session
    }
} else {
    noMotionSeconds += 1;
    if (noMotionSeconds >= buzzerDuration && !buzzerOn) {
        gpio_set_level(BUZZER_PIN, 1);
        buzzerOn = true;
        sessionActive = false;
        sessionSeconds = 0;
        // Display "User Away!" message
    }
}

C. Session Time Tracking

// Timer runs continuously when session is active
// Independent of motion detection
if (sessionActive && !buzzerOn) {
    sessionSeconds += 1;
    lcd_update_session_time(sessionSeconds);
}

D. PWM Fan Control (Temperature-based)

static void fan_set_speed(float temp_celsius) {
    uint32_t duty = 0;
   
    if (temp_celsius < 20.0) {
        duty = 0;  // Fan off
    } else if (temp_celsius < 25.0) {
        // Linear interpolation: 20°C=30%, 25°C=60%
        duty = (uint32_t)(76 + (temp_celsius - 20.0) * 15.3);
    } else if (temp_celsius < 30.0) {
        // 25°C=60%, 30°C=85%
        duty = (uint32_t)(153 + (temp_celsius - 25.0) * 12.75);
    } else if (temp_celsius < 35.0) {
        // 30°C=85%, 35°C=100%
        duty = (uint32_t)(217 + (temp_celsius - 30.0) * 7.6);
    } else {
        duty = 255;  // Fan max
    }
   
    ESP_ERROR_CHECK(ledc_set_duty(FAN_PWM_MODE, FAN_PWM_CHANNEL, duty));
    ESP_ERROR_CHECK(ledc_update_duty(FAN_PWM_MODE, FAN_PWM_CHANNEL));
}

PWM Configuration:

#define FAN_PWM_FREQUENCY      25000   // 25kHz for silent operation
#define FAN_PWM_DUTY_RES       LEDC_TIMER_8_BIT  // 0-255 range

Temperature Zones:

  • < 20°C: OFF (0%)
  • 20-25°C: LOW (30-60%)
  • 25-30°C: MEDIUM (60-85%)
  • 30-35°C: HIGH (85-100%)
  • > 35°C: MAX (100%)

Build Instructions:

# Set up ESP-IDF environment
. $HOME/esp/esp-idf/export.sh  # Linux/Mac
# OR
%USERPROFILE%\esp\esp-idf\export.bat  # Windows

# Configure WiFi credentials in main.c
# Edit WIFI_SSID and WIFI_PASS

# Build project
cd Embedded
idf.py build

# Flash to ESP32
idf.py -p COM9 flash  # Windows
idf.py -p /dev/ttyUSB0 flash  # Linux

# Monitor serial output
idf.py -p COM9 monitor

# Access web dashboard
# Check serial output for IP address
# Open browser: http://<ESP32_IP_ADDRESS>

Future Enhancements & Potential Improvements

  1. Data Logging: SD card storage for historical data
  2. Mobile App: Dedicated smartphone interface
  3. Advanced Automation: Time-based schedules, custom rules
  4. Email/SMS Alerts: Critical threshold notifications
  5. Voice Control: Alexa/Google Home integration

Division of Labor

  • Mahmoud Nour: DHT 22 / I2C LCD / Wifi Connectivity
  • Mohanad Abouserie: PIR / PWM Fan / Buzzer / Dashboard
  • Mohamed Elshemy: LDR / LED / FreeRTOS

Video Demo

Video on Google Drive