#include
#include
#include
#include
int led0 = 15;
int led1 = 4;
// WiFi credentials
const char* ssid = "";
const char* password = "";
const char* apiKey = "";
// Create WebServer object on port 80
WebServer server(80);
// HTML content to be served
const char index_html[] PROGMEM = R"rawliteral(
DFRobot Chatbot
DFRobot Beetle ESP32 C3 Chatbot
SubmitToggle Debug Panel
Debug Panel
)rawliteral";
// Function to process the user question and get the response
String processQuestion(String question) {
Serial.print("User Question: ");
Serial.println(question); // Print the user question
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin("https://openrouter.ai/api/v1/chat/completions");
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", String("Bearer ") + apiKey);
StaticJsonDocument<512> jsonDoc;
jsonDoc["model"] = "deepseek/deepseek-r1-distill-llama-70b"; // deepseek/deepseek-r1-distill-llama-70b //openai/gpt-4o-mini-2024-07-18
JsonArray messages = jsonDoc.createNestedArray("messages");
JsonObject systemMessage = messages.createNestedObject();
systemMessage["role"] = "system";
systemMessage["content"] = "Answer the user's question concisely and informatively.";
JsonObject userMessage = messages.createNestedObject();
userMessage["role"] = "user";
userMessage["content"] = question;
String requestBody;
serializeJson(jsonDoc, requestBody);
Serial.println("Sending HTTP POST request...");
int httpResponseCode = http.POST(requestBody);
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String response = http.getString();
Serial.print("HTTP Response: ");
Serial.println(response);
StaticJsonDocument<1024> responseDoc;
DeserializationError error = deserializeJson(responseDoc, response);
if (!error) {
String assistantResponse = responseDoc["choices"][0]["message"]["content"].as();
Serial.print("Assistant Response: ");
Serial.println(assistantResponse); // Print the assistant response
Serial1.println(assistantResponse);
return response; // Return entire API response
} else {
return "Failed to parse JSON response.";
}
}
return "WiFi not connected!";
}
void setup() {
// Start Serial Monitor
Serial.begin(115200);
Serial1.begin(9600, SERIAL_8N1, /*rx =*/17, /*tx =*/16);
pinMode(led0, OUTPUT);
pinMode(led1, OUTPUT);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("
Connected to WiFi");
// Print ESP32 Local IP Address
Serial.print("ESP32 IP Address: ");
Serial.println(WiFi.localIP());
// Serve HTML content
server.on("/", HTTP_GET, []() {
server.send_P(200, "text/html", index_html);
});
// Handle POST request from the web page
server.on("/getQuestion", HTTP_POST, []() {
if (server.hasArg("plain")) {
String body = server.arg("plain");
Wio 終端代碼 :
將以下代碼上傳到 Wio 終端,從 Beetle 獲取數(shù)據(jù)并在屏幕上打印出來。
#include
#include// Include the graphics library (this includes the sprite functions)
// Create a SoftwareSerial object on pins 2 (RX) and 3 (TX)
SoftwareSerial mySerial(2, 3); // RX, TX
// Initialize the TFT screen
TFT_eSPI tft = TFT_eSPI(); // Create object "tft"
// Screen dimensions
#define SCREEN_WIDTH 320
#define SCREEN_HEIGHT 240
void setup() {
Serial.begin(115200);
mySerial.begin(9600);
// Initialize the TFT screen
tft.begin();
tft.setRotation(3); // Set the screen orientation (1 for landscape mode)
tft.fillScreen(TFT_BLACK); // Clear the screen with black color
tft.setTextColor(TFT_WHITE); // Set text color to white
tft.setTextSize(2); // Set text size
// Print initial message to the screen
tft.drawString("Waiting for data...", 10, 10);
}
void loop() {
while (mySerial.available()) {
String str = mySerial.readString(); // Read the incoming data as a string
str.trim();
Serial.println(str);
// Clear the screen and display the new data with text wrapping
tft.fillScreen(TFT_BLACK); // Clear the screen with black color
printWrappedText(str, 10, 10, SCREEN_WIDTH - 20, 2);
mySerial.println("initialization done.");
}
}
// Function to print wrapped text on the screen
void printWrappedText(String str, int x, int y, int lineWidth, int textSize) {
tft.setCursor(x, y);
tft.setTextSize(textSize);
int cursorX = x;
int cursorY = y;
int spaceWidth = tft.textWidth(" ");
int maxLineWidth = lineWidth;
String word;
for (int i = 0; i < str.length(); i++) {
if (str[i] == ' ' || str[i] == '
') {
int wordWidth = tft.textWidth(word);
if (cursorX + wordWidth > maxLineWidth) {
cursorX = x;
cursorY += tft.fontHeight();
}
tft.drawString(word, cursorX, cursorY);
cursorX += wordWidth + spaceWidth;
if (str[i] == '
') {
cursorX = x;
cursorY += tft.fontHeight();
}
word = "";
} else {
word += str[i];
}
}
if (word.length() > 0) {
int wordWidth = tft.textWidth(word);
if (cursorX + wordWidth > maxLineWidth) {
cursorX = x;
cursorY += tft.fontHeight();
}
tft.drawString(word, cursorX, cursory);
}
}
串行終端響應(yīng):
然后在 Web 瀏覽器中打開 IP 地址。
接下來,輸入提示符。
您可以在 Wio 終端屏幕中看到響應(yīng)。
如果您想查看整個(gè) API 響應(yīng),只需按網(wǎng)站上的 Debug log 按鈕即可。這將顯示完整的 API 響應(yīng)以進(jìn)行調(diào)試。
評論