VIETNAM NATIONAL UNIVERSITY, HO CHI MINH CITY
HO CHI MINH CITY UNIVERSITY OF TECHNOLOGY
Faculty of Computer Science and Engineering
Logic Design Project
BUILDING RTOS ON ESP32
Class CC06 - Semester 241
Lecturer: Le Trong Nhan
Student: Nguyen Thien Phuc - 2252645
Pham Tan Phong - 2252612
Ho Chi Minh City, November 2024
Contents
1 About the project 2
1.1 RTOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 MQTT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Mini server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2 Requirement 3
2.1 Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3 Implementing code 3
3.1 Code for control moisture and control relay . . . . . . . . . . . . . . . . . . . 3
3.2 Code for measure temperature and humidity . . . . . . . . . . . . . . . . . . 5
3.3 Code for light sensor detection and control led . . . . . . . . . . . . . . . . . 5
3.4 Code for motion sensor and control fan . . . . . . . . . . . . . . . . . . . . . . 7
3.5 Code for MQTT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.5.1 MQTT Client Configuration . . . . . . . . . . . . . . . . . . . . . . . 7
3.5.2 MQTT Publishers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.5.3 Connection Management . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.5.4 Task Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.5.5 System Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.6 Code for mini server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.6.1 Toggle LED State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.6.2 Retrieve Sensor Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.6.3 Serve the Web Interface . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.6.4 Start Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.7 Additional code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4 Limitations and improvements in the future 12
4.1 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.2 Improvements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
5 Link for source code 12
1 About the project
The project is to implement Real Time Operating System by building an IoT system on
ESP32 for monitoring and controlling various sensors and actuators, including DHT20 for
temperature and humidity, NeoPixel LEDs, an ultrasonic distance sensor, and others, while
interfacing with Adafruit IO for MQTT communication and a local server for control.
1.1 RTOS
A real-time operating system (RTOS) is designed to perform repetitive tasks within strict
time constraints, where timing is a critical factor. RTOS has two primary characteristics:
predictability, which ensures that we can determine in advance how long a task will take,
and determinism, which guarantees that the task will produce the same result every time. If
either of these characteristics fails, such as through delays, incorrect timing, or unpredictable
behavior, the entire system could fail. RTOS is typically used in applications that require
precise task scheduling and low-latency responses, particularly in embedded systems. These
systems are widely used across various industries, including robotics, aerospace, rail, and
automotive.
1.2 MQTT
Message Queuing Telemetry Transport (MQTT) is a widely-used network protocol tailored for
the Internet of Things (IoT). It operates as a highly efficient publish-and-subscribe messaging
system, making it ideal for connecting remote devices due to its minimal code requirements
and low network bandwidth consumption. Today, MQTT has become a key protocol across
numerous industries, including automotive, manufacturing, telecommunications, and the oil
and gas sector.
In this project, MQTT serves as the communication protocol between the Yolo Uno board
and the OhStem server. Through this setup, clients can monitor and manage the sensor
system via the OhStem server. They have access to data from five sensors, which measure
temperature, humidity, soil moisture, light intensity, and distance. In addition, they can
control the system using three switches and a slider.
1.3 Mini server
A miniserver is a small yet powerful server designed to cater to the needs of small businesses,
home offices, or personal use. These servers are more compact than traditional servers,
making them perfect for spaces with limited room. Despite their small size, miniservers offer
reliable computing capabilities for tasks like file sharing, data backup, and recovery. They
are also energy-efficient, which leads to lower operational costs and a smaller environmental
impact. Minisers are versatile, supporting functions such as hosting company documents,
acting as backup servers, and enabling virtualization. Additionally, they are more affordable
than larger server systems, providing a practical and cost-effective server solution for small
businesses and individuals.
Class CC01- Semester 241 Page 2/12
2 Requirement
2.1 Input
The program controls some input:Temperature and Humidity (DHT20) to read temperature and hu-
midity values; Soil Moisture (Analog Pin G1) to read analog values from a soil moisture sensor. Light
Intensity (Analog Pin G2) to read light intensity values. PIR Motion Sensor (Analog Pin G3) to
detects motion. There are tasks to implement the control of input: TaskSoilMoistureAndRelay: reads
soil moisture and toggles the relay. TaskDetectMotion: reads motion and distance to adjust the fan
speed. TaskLightAndLED: Controls NeoPixel LEDs based on light intensity.
2.2 Output
The program also reads the data from input to process and send it to the output. NeoPixel LEDs:
Adjust brightness dynamically based on light intensity or toggle on/off manually via the web inter-
face. Red, Blue, and Green LEDs: Indicate status or debugging information and are toggled via
the web interface. Fan: Modulates speed based on moisture and motion or manual control using
a web slider. Relay: Activates/deactivates external devices like a water pump automatically or via
manual override. LCD Display: Shows real-time temperature, humidity, and system status updates.
MQTT Messaging: Sends sensor readings and device states to a remote broker for monitoring. Web
Interface: Provides live feedback on system states and allows control of LEDs, fan, and relay. Serial
Monitor: Logs sensor data and system events for debugging and diagnostics. There are functions to
implement the control of output: setNeoPixelBrightness(int brightness), toggleNeoPixel(bool state),
setRGBColor(int red, int green, int blue), setFanSpeed(int speed), manualFanControl(int speed) ,
toggleRelay(bool state), updateLCD(float temperature, float humidity, String status), clearLCD(),
publishMQTT(String topic, String message), subscribeMQTT(String topic), sendWebStateUpdate(),
processWebCommands(String command), logToSerial(String message), printSensorData(float temper-
ature, float humidity)
3 Implementing code
3.1 Code for control moisture and control relay
Functionality
• Measure soil moisture using an analog sensor.
• Control a relay based on moisture levels.
Class CC01- Semester 241 Page 3/12
(a) (b)
Figure 1: Caption for the entire figure.
Class CC01- Semester 241 Page 4/12
3.2 Code for measure temperature and humidity
Functionality
• Use a DHT sensor to measure temperature and humidity.
(a)
(b)
Figure 2: Caption for the entire figure.
3.3 Code for light sensor detection and control led
Functionality:
• Detect light levels using an analog sensor.
• Control an LED based on light levels.
Class CC01- Semester 241 Page 5/12
(a)
(b)
Figure 3: Caption for the entire figure.
Class CC01- Semester 241 Page 6/12
3.4 Code for motion sensor and control fan
Functionality
• Detect motion using a PIR sensor.
• Control a fan based on motion detection.
(a)
(b)
Figure 4: Caption for the entire figure.
3.5 Code for MQTT
The system leverages MQTT (Message Queuing Telemetry Transport) to enable communication be-
tween the ESP32 and the Adafruit IO cloud platform. This implementation facilitates remote moni-
toring and control of connected devices. The key aspects of this MQTT implementation are detailed
below:
3.5.1 MQTT Client Configuration
The MQTT client is initialized using the Adafruit MQTT Client class. It connects to the Adafruit IO
server using the following configuration parameters:
• Server Address: AIO SERVER (Adafruit IO broker address).
Class CC01- Semester 241 Page 7/12
• Port: AIO SERVERPORT (Port 1883 is used for non-secure communication).
• Credentials: AIO USERNAME and AIO KEY to authenticate the ESP32 with the Adafruit IO
platform. This setup ensures secure and efficient communication between the ESP32 and the
MQTT broker.
3.5.2 MQTT Publishers
The system defines multiple MQTT publishers to send sensor data to specific feeds on the Adafruit
IO platform. Each publisher is associated with a unique feed corresponding to a particular sensor:
• solid: Soil moisture data.
• humi: Humidity data.
• temp: Temperature data.
• light: Light intensity data.
• pir: Motion detection status.
• dis: Distance measurements.
These publishers continuously transmit sensor readings to their respective feeds, enabling real-time
remote monitoring of environmental parameters.
3.5.3 Connection Management
The system uses a robust connection management routine implemented in the MQTT connect() func-
tion. Key functionalities include:
• Connection Check: The function verifies if the client is already connected to the broker. If
connected, no further action is taken.
• Reconnection Mechanism: If the connection is lost, the system attempts to reconnect up to
three times, with a delay of 10 seconds between attempts. In the event of persistent failure,
the system enters an infinite loop, awaiting a hardware reset. This approach ensures continuous
connectivity and minimal disruption in data transmission.
3.5.4 Task Management
The MQTT-related operations are handled by a dedicated task, TaskMQTT. This task performs the
following functions:
• Periodically reads data from the connected sensors.
• Publishes sensor data to the respective MQTT feeds using the defined publishers.
• Manages the MQTT connection lifecycle, ensuring stable communication with the broker.
3.5.5 System Workflow
• Initialization: The ESP32 connects to a Wi-Fi network and establishes a connection with the
Adafruit IO MQTT broker.
• Data Publishing: Sensor readings, such as temperature, humidity, and light intensity, are pub-
lished to their respective feeds on Adafruit IO.
• Reconnection: If the connection to the MQTT broker is interrupted, the system automatically
retries to re-establish the connection.
Class CC01- Semester 241 Page 8/12
Figure 5: Logic design for MQTT
Figure 6: Ensure connecting MQTT
Class CC01- Semester 241 Page 9/12
Figure 7: Manage MQTT connectivity
3.6 Code for mini server
This code sets up an asynchronous web server to manage HTTP requests and serve resources for a
web-based IoT application. The server facilitates the control of devices and the retrieval of sensor data
through a browser interface.
3.6.1 Toggle LED State
Endpoint: /toggle This endpoint toggles the state of an LED (on/off) connected to the system. When
accessed: The LED’s current state is flipped (from ON to OFF or vice versa). A plain text response
is sent back to the client, indicating the new state (e.g., ”LED ON” or ”LED OFF”). Example:
3.6.2 Retrieve Sensor Data
Endpoint: /getData This endpoint collects data from various sensors connected to the IoT system and
sends it as a JSON response. The JSON object includes:
Class CC01- Semester 241 Page 10/12
• Temperature
• Humidity
• Soil moisture
• Light intensity
• Distance measurements
Example code:
3.6.3 Serve the Web Interface
Endpoint: / Serves the main HTML file (index2.html) to provide a graphical user interface for inter-
acting with the IoT system. The interface includes buttons, sliders, and real-time data displays for
controlling devices and monitoring sensors.
Class CC01- Semester 241 Page 11/12
3.6.4 Start Server
Initializes the asynchronous web server and begins listening for incoming requests. Upon successful
initialization, a confirmation message is displayed in the Serial Monitor, showing the device’s IP address
for access. Example code:
3.7 Additional code
• LED Control: Functions like handleToggleRedLED, handleToggleBlueLED, handleToggleGreen-
LED, and handleTurnOffLED control the color or state of a group of LEDs.
• Fan Control: handleSetFanSpeed adjusts the fan’s speed dynamically using a PWM signal.
• Relay Control: handleToggleRelay toggles the state of a connected relay for powering other
devices or circuits.
• Server Interface: The handleRoot() function is designed to generate and serve a simple, inter-
active control panel in HTML format for managing connected devices.
4 Limitations and improvements in the future
4.1 Limitations
The program has a limit in:
• Code readability:
• Real-time Task Priorities
• Sensor value calibration
• Web Aesthetics
4.2 Improvements
As the limitations of the program can affect the quality of using traffic lights, our group will construct
a better program to avoid encountering those errors mentioned above:
• Use a watchdog timer to monitor and reset the system in case tasks hang or take too long.
• Add a calibration routine that adjusts sensor values based on baseline readings or user input.
• Upgrade the web interface with modern frameworks like Bootstrap, Materialize, or Tailwind
CSS for better design and responsiveness.
5 Link for source code
Link for source code: https://github.com/PhongPham444/RTOS/tree/main
Class CC01- Semester 241 Page 12/12