#include <LiquidCrystal.h> // Include the LiquidCrystal library
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h> // Install ArduinoJson library via Arduino Library Manager
// Define the LCD pins
const int rs = 2; // Register Select
const int en = 3; // Enable
const int d4 = 4; // Data 4
const int d5 = 5; // Data 5
const int d6 = 12; // Data 6
const int d7 = 13; // Data 7
// Initialize the LCD with the above-defined pins
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
const char* ssid = "Your_SSID";
const char* password = "Your_Password";
const char* openaiApiKey = "b453666eb3d04c1fa7c608375d88f7fc";
void setup() {
Serial.begin(115200);
delay(10);
// Connect to Wi-Fi
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Read the text input from Arduino Uno
String inputText = "Hello ChatGPT, reply with only one word";
Serial.println("Received input: " + inputText);
// Initialize JSON parser
DynamicJsonDocument jsonDocument(1024); // Increase the buffer size as needed
jsonDocument["model"] = "gpt-3.5-turbo";
// Define the chat messages
JsonArray messages = jsonDocument.createNestedArray("messages");
// Add system message
JsonObject systemMessage = messages.createNestedObject();
systemMessage["role"] = "system";
systemMessage["content"] = "You are a helpful home automation assistant.";
// Add user message (you can modify this part to read user input from Arduino Uno)
JsonObject userMessage = messages.createNestedObject();
userMessage["role"] = "user";
userMessage["content"] = inputText; // You can replace this with the user's input
// Create an HTTPClient object
HTTPClient http;
// Build the API request
String apiUrl = "https://artificialintelligence.openai.azure.com/openai/deployments/test/chat/completions?api-version=2023-05-15";
http.begin(apiUrl);
http.addHeader("Content-Type", "application/json");
String authHeader = "Bearer ";
authHeader = openaiApiKey;
http.addHeader("api-key",authHeader);
// Serialize the JSON request body
String requestBody;
serializeJson(jsonDocument, requestBody);
// Make the HTTP POST request
http.setTimeout(15000);
int httpCode = http.POST(requestBody);
Serial.println(httpCode);
if (httpCode == 200) {
// Parse the JSON response
const String& response = http.getString();
Serial.println(response);
deserializeJson(jsonDocument, response);
// Extract the "content" field from the JSON response
String content = jsonDocument["choices"]["message"]["content"].as<String>();
String content1 = "Hello";
Serial.println("Replied");
lcd.begin(16, 2);
// Print a message to the LCD
lcd.setCursor(0, 0);
lcd.print(content);
} else {
Serial.println("HTTP request failed");
lcd.begin(16, 2);
// Print a message to the LCD
lcd.setCursor(0, 0);
lcd.print("Failed");
}
http.end();
}
void loop() {
// Your code here
}