Combining ChatGPT with ESP32 can lead to more interesting applications in the Internet of Things, such as chatbots, voice assistants, and natural language interfaces. Below, I will use the ChatGPT API in ESP32.
-
Register on the OpenAI website and install the necessary libraries on ESP32; -
Create a new project on the OpenAI API and generate an API key; -
Use the API key to authenticate requests to the OpenAI API; -
Send text input to the OpenAI API using HTTP requests and receive responses in JSON format; -
Parse the response and use it to control the ESP32 microcontroller.
Now, I will implement the above steps on ESP32:
1. First, we need to include the necessary libraries so that the ESP32 can communicate over Wi-Fi, make HTTP requests, and parse JSON data.
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
2. Define the network credentials for the Wi-Fi network to which the ESP32 will connect, as well as the OpenAI API key.
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* apiKey = "your_API_KEY";
void setup() {
//
}
Serial.begin(9600);
// Connect to Wi-Fi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Send request to OpenAI API
String inputText = "Hello, ChatGPT!";
String apiUrl = "https://api.openai.com/v1/completions";
String payload = "{\"prompt\":\"" + inputText + "\",\"max_tokens\":100, \"model\": \"text-davinci-003\"}";
HTTPClient http;
http.begin(apiUrl);
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", "Bearer " + String(apiKey));
The inputText string defines the prompt for the API, which in this case is “Hello, ChatGPT!”.
int httpResponseCode = http.POST(payload);
if (httpResponseCode == 200) {
String response = http.getString();
// Parse JSON response
DynamicJsonDocument jsonDoc(1024);
deserializeJson(jsonDoc, response);
String outputText = jsonDoc["choices"][0]["text"];
Serial.println(outputText);
} else {
Serial.printf("Error %i \n", httpResponseCode);
}
http.POST() will return the HTTP code of the response. If it is HTTP 200, we will parse the JSON and print it to the serial port.
void loop() {
//
}
For the complete code, please reply with esp32_chatgpt in the backend of the “Embedded Base” public account to obtain it.

END
→ Follow to avoid getting lost ←