Nipun Jayasena

Engineering, Tech Projects & Solutions

Featured Work & Updates

How to Connect ESP32 with OpenAI ChatGPT API for Smart IoT Projects (Step-by-Step Guide)


Artificial Intelligence (AI) and the Internet of Things (IoT) are transforming modern technology. By connecting powerful microcontrollers like the ESP32 with cloud-based AI engines like OpenAI (ChatGPT API), you can create truly intelligent hardware projects that analyze sensors, generate natural language responses, and automate complex tasks.
💡 In this guide: You will learn how the ESP32 communicates with ChatGPT via REST APIs, how to manage JSON responses, and how to structure your Arduino C++ code for seamless integration.

Why Combine ESP32 with Artificial Intelligence?

Traditional IoT projects rely on static conditional logic (e.g., if temperature > 30°C then turn on fan). By embedding AI via APIs, your ESP32 can:

  • Analyze complex multi-sensor environmental data.
  • Provide voice or text responses based on real-time context.
  • Process image input (using ESP32-CAM) for smart vision systems.
  • Perform predictive maintenance for industrial equipment.

Prerequisites & Hardware Needed

  • ESP32 Development Board (ESP32-WROOM-32 or ESP32-CAM)
  • Arduino IDE with ESP32 Board Manager installed
  • OpenAI API Key (from platform.openai.com)
  • Active Wi-Fi Connection
  • ArduinoJson & HTTPClient Libraries

Step-by-Step Integration Overview

1. Obtaining Your OpenAI API Key

First, log in to your OpenAI account dashboard, navigate to the API Keys section, and generate a new secret API key. Store this key securely, as it will be authorized inside your ESP32 HTTP headers.

2. Preparing the JSON Payload

OpenAI's Chat Completion endpoint expects a specific JSON format using HTTP POST requests. Here is the structure needed:

{ "model": "gpt-3.5-turbo", "messages": [ {"role": "user", "content": "Analyze temperature 34C and humidity 80%. Provide a short status."} ], "max_tokens": 60 }

3. C++ Code Snippet for ESP32 (HTTP Client)

Below is a minimal code snippet showing how the HTTP POST request is structured in Arduino C++ for ESP32:

#include <WiFi.h> #include <HTTPClient.h> #include <ArduinoJson.h> const char* ssid = "YOUR_WIFI_SSID"; const char* password = "YOUR_WIFI_PASSWORD"; const char* apiKey = "YOUR_OPENAI_API_KEY"; void sendToChatGPT(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", String("Bearer ") + apiKey); StaticJsonDocument<500> doc; doc["model"] = "gpt-3.5-turbo"; doc.createNestedArray("messages").add().createNestedObject()["content"] = prompt; String requestBody; serializeJson(doc, requestBody); int httpResponseCode = http.POST(requestBody); if(httpResponseCode > 0) { String response = http.getString(); Serial.println("Response from AI:"); Serial.println(response); } else { Serial.print("Error Code: "); Serial.println(httpResponseCode); } http.end(); } }

Potential AI + IoT Applications

  1. Smart Home Voice Assistants: Custom voice-activated devices tailored for localized automation.
  2. Predictive Plant Care: Soil moisture analysis combined with weather forecasts processed by AI to optimize watering schedules.
  3. Automated Diagnostics: Monitoring PC hardware metrics or automotive sensor signals and receiving real-time troubleshooting steps.

Conclusion

Integrating ESP32 with AI services opens up endless possibilities for modern embedded engineering. As edge devices become more powerful, combining local sensor collection with cloud AI processing will be a core standard in modern IoT design.