#include <Wire.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <vector>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* apiKey = "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";
String apiUrl = "https://api.openai.com/v1/chat/completions";
String finalPayload = "";
bool initialPrompt = true;
bool gettingResponse = false;
HTTPClient http;
std::vector<String> I2Cdevices;
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println("Connected");
http.begin(apiUrl);
Wire.begin(); // Initialize I2C communication
Serial.println("\nI2C Scanner");
Serial.println("Scanning I2C devices...");
scanI2C();
}
void loop() {
if (Serial.available() > 0) {
String userInput = Serial.readStringUntil('\n');
userInput.trim();
if (userInput.equalsIgnoreCase("What is the sensor?")) {
chatGptCall();
}
}
}
void scanI2C() {
byte error, address;
for (address = 1; address < 127; address++ ) {
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0) {
Serial.print(F("I2C device found at address 0x"));
if (address < 16)
Serial.print(F("0"));
Serial.print(address, HEX);
if (address >= 0x68 && address <= 0x6b) {
Serial.print(F(" PCF8573 MPU6050"));
I2Cdevices.push_back("PCF8573");
I2Cdevices.push_back("MPU6050");
Serial.println();
}
}
Serial.print("Found ");
Serial.print(I2Cdevices.size());
Serial.println(" device(s) on the I2C bus.");
}
}
void chatGptCall() {
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", "Bearer " + String(apiKey));
String payload = "The sensor could be: ";
for (size_t i = 0; i < I2Cdevices.size(); ++i) {
payload += I2Cdevices[i];
if (i != I2Cdevices.size() - 1)
payload += ", ";
}
finalPayload = "{\"model\": \"gpt-3.5-turbo\",\"messages\": [{\"role\": \"user\", \"content\": \"" + payload + "\"}]}";
gettingResponse = true;
while (gettingResponse) {
int httpResponseCode = http.POST(finalPayload);
if (httpResponseCode == 200) {
String response = http.getString();
DynamicJsonDocument jsonDoc(1024);
deserializeJson(jsonDoc, response);
String outputText = jsonDoc["choices"][0]["message"]["content"];
outputText.remove(outputText.indexOf('\n'));
Serial.println("CHATGPT: " + outputText);
} else {
Serial.printf("Error %i \n", httpResponseCode);
Serial.println("Trying again");
if (httpResponseCode == 429) {
delay(5000);
}
}
gettingResponse = false;
}
}