Project Description
This project demonstrates how to build a Smart Environmental Monitor using a Carenuity C3-Mini microcontroller, a DHT22 temperature and humidity sensor, and OpenAI's GPT-3.5 API. The system collects real-time environmental data, computes statistical metrics (average, min, max, and heat index), and sends the data to an AI service for analysis. The AI provides actionable insights such as trends, anomalies, and recommendations, making this project ideal for IoT enthusiasts, environmental monitoring, and smart home applications.
IntroductionEnvironmental monitoring is essential for smart homes, agriculture, and industrial applications. In this project, we’ll create a system that collects and analyzes temperature and humidity data using AI. This integration enables smarter, data-driven decisions for climate control and environmental optimization.
Hardware Components- Carenuity C3-Mini (POWERFUL ESP32-based microcontroller) – For Wi-Fi connectivity and data processing.
Connect the DHT22 sensor to the ESP32:
- VCC → 3.3V
- GND → GND
- Data → GPIO 6
Open the Arduino IDE and install the following libraries via the Library Manager:
- DHT by Adafruit
- ArduinoJson by Benoit Blanchon
- WiFi (included with ESP32 core)
- HTTPClient (included with ESP32 core)
- Copy and paste the provided code into Arduino IDE.
Replace placeholders with actual private credentials:
- SSID: Your Wi-Fi network name.
- Password: Your Wi-Fi password.
For the AI analysis, create an account with Open Ai and generate your API key
- API Key: Your OpenAI API key, For analyzing sensor data and generating insights..
Connect the ESP32 to your computer using a USB cable.
- Select the correct ESP32 board (LOLIN C3) and port.
- Upload the code to the ESP32.
- Open the Serial Monitor (Ctrl+Shift+M) to view real-time sensor data and AI-generated insights.
- Ensure the ESP32 is connected to Wi-Fi and successfully sending data to OpenAI.
After every 10 readings, the system will send a prompt like this to OpenAI:
Analyze the following statistical data:
Temperature (Avg/Min/Max): 25.3°C / 24.1°C / 26.5°C
Humidity (Avg/Min/Max): 60.5% / 58.0% / 62.0%
Heat Index: 27.1°C
Provide insights into trends, anomalies, and any recommendations.
Code ExplanationThe Arduino code reads temperature and humidity from a DHT22 sensor, calculates statistical data (average, min, max, and heat index), and sends the information to an AI service via an HTTP request.
1. Included Libraries#include <DHT.h>
#include <ArduinoJson.h>
#include <WiFi.h>
#include <HTTPClient.h>
DHT.h
→ For interfacing with the DHT22 temperature & humidity sensor.ArduinoJson.h
→ For creating and handling JSON data.WiFi.h
→ For connecting to a Wi-Fi network (ESP32 is used).HTTPClient.h
→ For sending HTTP POST requests to an external API.
#define DHTPIN 6 // Pin where the DHT22 is connected
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
- Defines the DHT22 sensor connected to pin 6.
DHT dht(DHTPIN, DHTTYPE);
→ Creates a DHT sensor object.
const char* ssid = "Your SSID"; // WiFi SSID
const char* password = "YOUR PASSWORD"; // WiFi Password
- WiFi Credentials → Connects ESP32 to the Wi-Fi network.
// Arrays to store the last 10 readings
float temperatureReadings[10];
float humidityReadings[10];
int readingIndex = 0;
- Arrays to store the last 10 temperature and humidity readings.
readingIndex
keeps track of the current position in the array.
void setup() {
Serial.begin(115200); // Start serial communication
dht.begin(); // Initialize DHT sensor
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
- Starts the Serial Monitor at 115200 baud rate.
- Initializes the DHT sensor.
- Connects to the Wi-Fi network and waits until connected.
void loop() {
// Read data from DHT22
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Check if any reads failed and exit early (to try again).
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Store the readings in the arrays
temperatureReadings[readingIndex] = temperature;
humidityReadings[readingIndex] = humidity;
readingIndex++;
// After 10 readings, calculate statistics and heat index
if (readingIndex >= 10) {
calculateAndSendStatistics();
readingIndex = 0; // Reset the index
}
// Delay before the next reading
delay(5000); // Adjust the delay as needed
}
- Reads temperature and humidity values.
- Checks if the sensor read failed (NaN check).
- Stores the values in arrays and increments the index.
When 10 readings are collected:
- Calls
calculateAndSendStatistics()
to process the data. - Resets the index to 0.
- When 10 readings are collected:Calls
calculateAndSendStatistics()
to process the data.Resets the index to 0. - Delays for 5 seconds before the next reading.
void calculateAndSendStatistics() {
// Calculate average, min, max, and mode for temperature and humidity
float tempSum = 0, humiditySum = 0;
float tempMin = temperatureReadings[0], tempMax = temperatureReadings[0];
float humidityMin = humidityReadings[0], humidityMax = humidityReadings[0];
for (int i = 0; i < 10; i++) {
tempSum += temperatureReadings[i];
humiditySum += humidityReadings[i];
if (temperatureReadings[i] < tempMin) tempMin = temperatureReadings[i];
if (temperatureReadings[i] > tempMax) tempMax = temperatureReadings[i];
if (humidityReadings[i] < humidityMin) humidityMin = humidityReadings[i];
if (humidityReadings[i] > humidityMax) humidityMax = humidityReadings[i];
}
float tempAvg = tempSum / 10;
float humidityAvg = humiditySum / 10;
// Calculate heat index
float heatIndex = calculateHeatIndex(tempAvg, humidityAvg);
Computes:
- Average temperature and humidity.
- Minimum and maximum values.
- Heat Index using
calculateHeatIndex()
. - Computes:Average temperature and humidity.Minimum and maximum values.Heat Index using
calculateHeatIndex()
.
// Create a JSON document to store the statistical data
StaticJsonDocument<500> doc;
doc["temperature_avg"] = tempAvg;
doc["temperature_min"] = tempMin;
doc["temperature_max"] = tempMax;
doc["humidity_avg"] = humidityAvg;
doc["humidity_min"] = humidityMin;
doc["humidity_max"] = humidityMax;
doc["heat_index"] = heatIndex;
// Convert the JSON document to a string
String payload;
serializeJson(doc, payload);
- Stores the statistics in a JSON object.
// Create the prompt for the AI service
String prompt = "Analyze the following statistical data: \n";
prompt += "Temperature (Avg/Min/Max): " + String(tempAvg, 2) + "°C / " + String(tempMin, 2) + "°C / " + String(tempMax, 2) + "°C\n";
prompt += "Humidity (Avg/Min/Max): " + String(humidityAvg, 2) + "% / " + String(humidityMin, 2) + "% / " + String(humidityMax, 2) + "%\n";
prompt += "Heat Index: " + String(heatIndex, 2) + "°C\n";
prompt += "Provide insights into trends, anomalies, and any recommendations.";
// Send the prompt to the AI service
sendToAI(prompt);
}
- Constructs an AI query prompt.
- Calls
sendToAI()
to transmit the request.
float calculateHeatIndex(float temperature, float humidity) {
// Heat index formula (simplified)
float heatIndex = 0.5 * (temperature + 61.0 + ((temperature - 68.0) * 1.2) + (humidity * 0.094));
return heatIndex;
}
- Computes Heat Index using a simplified formula.
void sendToAI(String prompt) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin("https://api.openai.com/v1/chat/completions");
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", "Bearer YOUR_API_KEY"); // Replace with your API key
- Establishes an HTTP connection.
- Adds API Key (security issue: should not be hardcoded).
StaticJsonDocument<400> doc;
doc["model"] = "gpt-3.5-turbo";
JsonArray messages = doc.createNestedArray("messages");
JsonObject systemMessage = messages.createNestedObject();
systemMessage["role"] = "system";
systemMessage["content"] = "You are a helpful assistant.";
JsonObject userMessage = messages.createNestedObject();
userMessage["role"] = "user";
userMessage["content"] = prompt;
- Prepares the JSON payload for OpenAI chat completions API.
int httpResponseCode = http.POST(requestBody);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("Response: " + response);
} else {
Serial.println("Error on sending POST: " + String(httpResponseCode));
}
}
}
- Sends the HTTP POST request and prints the response.
Insights:
15:47:55.544 -> "message": {
15:47:55.544 -> "role": "assistant",
15:47:55.544 -> "content": "Based on the statistical data provided:\n\n1. Temperature: The average temperature is 30.31°C, with a slight variation between the minimum (30.30°C) and maximum (30.40°C) temperatures. This indicates a relatively stable temperature range.\n\n2. Humidity: The average humidity is 74.71%, with a narrow range between the minimum (74.60%) and maximum (74.80%) values. This suggests a consistent level of humidity.\n\n3. Heat Index: The heat index is calculated to be 26.55°C, which is lower than the average temperature. This indicates that even though the temperature is high, the heat index makes it feel slightly cooler due to the humidity level.\n\nInsights:\n- The temperature and humidity levels seem to be fairly consistent with minimal fluctuations, indicating stable weather conditions.\n- The heat index is lower than the actual temperature, which suggests that the humidity is influencing how warm it feels, making it slightly more comfortable despite the high temperature.\n\nRecommendations:\n- Despite the relatively stable conditions, it is important to stay hydrated and take necessary precautions to prevent dehydration and heat-related illnesses.\n- Consider using fans or air conditioning to maintain a comfortable indoor environment.\n- Monitor weather forecasts for any potential changes in temperature or humidity levels.\n\nOverall, the data suggests stable and slightly humid conditions with a lower perceived temperature due to the heat index. Stay informed about weather updates and continue to take care during hot and humid conditions.",
15:47:55.544 -> "refusal": null
15:47:55.544 -> },
ApplicationThis project has a wide range of applications across various industries, including:
- Smart Homes – Optimizes indoor climate by monitoring temperature and humidity.
- Agriculture – Ensures ideal environmental conditions for crop growth.
- Industrial IoT – Maintains optimal temperature and humidity levels in factories and storage facilities.
- Research – Collects and analyzes environmental data for scientific studies and experiments.
This project showcases the potential of IoT and AI integration in environmental monitoring. By leveraging OpenAI GPT-3.5, we can transform raw sensor data into actionable insights, making monitoring systems smarter and more efficient. Whether you're a hobbyist or professional, this project is an excellent foundation for AI-assisted IoT applications.
Comments
Please log in or sign up to comment.