#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);
}
}
void loop() {
if (Serial.available() > 0) {
String inputText = Serial.readStringUntil('\n');
// 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 whose name is Alex.You reply in only one word";
// 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);
if (httpCode == 200) {
// Parse the JSON response
const String& response = http.getString();
deserializeJson(jsonDocument, response);
// Extract the "content" field from the JSON response
JsonArray choicesArray = jsonDocument["choices"].as<JsonArray>();
// Access the first object in the "choices" array
JsonObject firstChoice = choicesArray[0].as<JsonObject>();
// Access the "message" object within the first choice
JsonObject messageObject = firstChoice["message"].as<JsonObject>();
// Extract the "content" field from the "message" object
String content = messageObject["content"].as<String>();
content=content+"\n";
// Now, 'content' should contain the value you want
Serial.println(content);
http.end();
}
else{
Serial.println("Failed");
http.end();
}
}
}