- Introduction
- Requirements
- Setup
- Usage
- Troubleshooting
- WebServer with API Endpoints
- Index Page
- Relay Control
- Additional Functionalities
- Project Images
- Contributing
- Acknowledgements
- Changelog
- License
This project integrates an ESP32 device with temperature and humidity sensors (DHT21, AHT10, SHTC3) using C# and the nanoFramework for development. It features MQTT client capabilities for real-time remote data communication and a WebServer component that provides RESTful API endpoints for sensor data access and device control via HTTP requests. The system is ideal for IoT applications requiring flexible communication and interaction interfaces.
Note: Only one sensor is active at a time. The sensor (DHT21, AHT10, or SHTC3) must be selected during the initial setup, and they do not work simultaneously.
Visit our demo portal at: iot.unrealbg.com
I acknowledge that the code may not be perfect and there are certainly areas that can be improved. I am a self-taught programmer, and coding is my hobby. I welcome any constructive criticism and feedback.
- ESP32 development board
- DHT21, AHT10, or SHTC3 temperature and humidity sensor
- MQTT broker (e.g., Mosquitto)
-
The required nanoFramework firmware version depends on the NuGet packages used in this project.
-
To ensure compatibility, use the firmware version that matches the latest tested state of this repository.
-
The last tested firmware version for this project was 1.12.4.14.
-
You can check your current firmware version using the Device Explorer in the nanoFramework extension for Visual Studio or by running:
nanoff --platform esp32 --target <YOUR_ESP32_TARGET> --serialport <YOUR_COM_PORT> --list
-
If needed, update your firmware to the version used in this project:
nanoff --platform esp32 --target <YOUR_ESP32_TARGET> --serialport <YOUR_COM_PORT> --masserase --update --fwversion 1.12.4.14
-
Important: Replace <YOUR_ESP32_TARGET> with the correct target for your device (e.g., ESP32_WROOM_32, ESP32_S3, ESP32_C3). You can find the available targets by running:
nanoff --platform esp32 --listtargets
-
Also, replace <YOUR_COM_PORT> with the actual serial port where your ESP32 device is connected (e.g., COM31 on Windows or /dev/ttyUSB0 on Linux/macOS).
-
If you decide to use a newer firmware version, you must also update the corresponding NuGet packages in your project to ensure compatibility. Check for updates in Visual Studio's NuGet Package Manager and make sure all dependencies align with the firmware version you are using.
-
For detailed firmware update instructions, visit the nanoFramework documentation.
This project has been tested and confirmed to work with the following hardware:
- ESP32-S3
- ESP32 Wroom32 DevKit
- ESP32-WROOM-32 DevKit (38 Pins)
- ESP-WROOM-32 ESP-32S
- Wemos/Lolin D32 ESP32
- ESP32-C3 (known compatibility issues)
- AHT10
- AHT20 + BMP280
- SHTC3
- DHT21
If you test the project with other hardware, feel free to contribute feedback!
-
NanoFramework Installation:
Install the C# nanoFramework on your ESP32 device. Detailed instructions are available here. -
Sensor Connection:
Connect the DHT21, AHT10, or SHTC3 sensor to your ESP32 device as per the sensor's documentation. Select the sensor in the code during setup. -
MQTT Broker Setup:
Set up an MQTT broker (like Mosquitto) on your network. Note down the hostname and port number. -
Code Configuration:
In the code, configure the necessary settings in theDeviceSettings
,MqttSettings
, andWiFiSettings
classes:- DeviceSettings: Set values for
DeviceName
,Location
, andSensorType
. - MqttSettings: Provide the
broker address
,username
, andpassword
for your MQTT broker. - Wi-Fi Settings: Enter the
ssid
andpassword
for your Wi-Fi network.
These settings are defined in dedicated classes and should be modified according to your environment and setup requirements.
- DeviceSettings: Set values for
-
Code Deployment:
Compile and upload the code to your ESP32 device.
Once the setup is complete, the ESP32 device will start publishing temperature and humidity data from the selected sensor (DHT21, AHT10, or SHTC3) to an MQTT topic. Subscribe to this topic to receive real-time updates. The system also supports publishing custom messages to the MQTT topic.
-
Bootloop Prevention:
If the device repeatedly enters a bootloop, ensure that the correct GPIO pins are configured for your sensor(s) and relay. Verify the pin assignments in the code (e.g., inBaseSensorService
,AhtSensorService
, andRelayService
) match your hardware setup. Incorrect pin assignments can cause improper initialization, leading to boot issues. -
MQTT Connection Issues:
Ensure the MQTT broker hostname and port number are correctly set in the code. -
Sensor Data Accuracy:
If temperature and humidity readings are inaccurate, verify the sensor connections and calibrations.
This project includes a web server that serves API endpoints for structured HTTP request handling. It allows for remote sensor data retrieval and device control via a RESTful interface.
Note: For optimal web server performance, it is recommended to use ESP devices with more memory, such as ESP32-S3. The project has been tested and works without issues on ESP32-S3, thanks to its increased storage and processing resources.
- API Endpoints: API endpoints for interacting with the DHT21, AHT10, and SHTC3 sensors and device control.
- Real-Time Data Access: Fetch real-time temperature and humidity data.
- Device Control: Endpoints for controlling the ESP32 device functionalities.
-
Temperature Data:
- Endpoint:
/api/temperature
- Method:
GET
- Description: Returns the current temperature reading from the selected sensor in JSON format.
- Endpoint:
-
Humidity Data:
- Endpoint:
/api/humidity
- Method:
GET
- Description: Returns the current humidity reading in JSON format.
- Endpoint:
-
Complete Sensor Data:
- Endpoint:
/api/data
- Method:
GET
- Description: Returns both temperature and humidity readings along with the sensor type in a structured JSON format.
- Endpoint:
An index page has been added for a user-friendly display of sensor data through a simple web interface. It dynamically updates the temperature, humidity, date, time, and sensor type using JavaScript.
The index page provides a clean and responsive UI for real-time monitoring:
- Displays temperature and humidity readings.
- Shows the current date, time, and sensor type.
The project now includes a relay control feature accessible via the web interface. A button has been added to the index page to allow users to toggle the relay state between ON and OFF. The button’s label and color dynamically update based on the current relay state.
- "Turn On": Green button appears when the relay is off.
- "Turn Off": Red button appears when the relay is on.
You can control the relay using the following API endpoint:
-
Toggle Relay
- Endpoint:
/api/toggle-relay
- Method:
POST
- Description: Toggles the relay state between ON and OFF. The response returns the updated relay state (
isRelayOn
).
- Endpoint:
-
Check Relay Status
- Endpoint:
/api/relay-status
- Method:
GET
- Description: Returns the current state of the relay (ON or OFF) in JSON format.
- Endpoint:
The web interface has been updated with a new Relay Control button. This button will dynamically update based on the state of the relay:
- Turn On: Green button displayed when the relay is off.
- Turn Off: Red button displayed when the relay is on.
<button id="relayButton" class="btn-on" onclick="toggleRelay()">Loading...</button>
async function toggleRelay() {
const response = await fetch('/api/toggle-relay', { method: 'POST' });
const data = await response.json();
updateRelayButton(data.isRelayOn);
}
function updateRelayButton(isRelayOn) {
const relayButton = document.getElementById('relayButton');
if (isRelayOn) {
relayButton.textContent = 'Turn Off';
relayButton.className = 'btn-off';
} else {
relayButton.textContent = 'Turn On';
relayButton.className = 'btn-on';
}
}
You can control a relay module to manage connected devices based on sensor data or MQTT commands. This enables automated environmental control or remote power management.
In addition to the DHT21 and AHT10 sensors, the project now supports the SHTC3 sensor, offering flexibility in sensor choice based on precision and calibration needs.
Contributions are welcome! Please follow these steps to contribute:
- Fork the repository.
- Create a new branch (
git checkout -b feature-branch
). - Make your changes.
- Commit your changes (
git commit -m 'Add new feature'
). - Push to the branch (
git push origin feature-branch
). - Open a Pull Request.
- nanoFramework
- Mosquitto MQTT
- Special thanks to everyone who contributed to this project.
- Sensor Services:
- Introduced
BaseSensorService
to centralize sensor reading, error handling, and resource management. - Updated AHT10, AHT20+BMP280, DHT21, and SHTC3 sensor services to inherit from
BaseSensorService
.
- Introduced
- MQTT Client:
- Improved connection stability with dynamic ClientId generation, locking to prevent duplicate connection attempts, and exponential backoff with jitter.
- Network & Internet:
- Refactored
ConnectionService
with proper locking and enhanced IP validation. - Improved
InternetConnectionService
with resource cleanup and stop-signal checks.
- Refactored
- Web Server & Relay:
- Enhanced
WebServerService
andRelayService
with thread-safe operations and proper resource disposal.
- Enhanced
- Added support for the AHT20+BMP280 sensor.
- Added support for the SHTC3 sensor.
- Improved MQTT connection stability.
- Initial release with support for DHT21 and AHT10 sensors.
This project is licensed under the MIT License. See the LICENSE file for details.