#include <WiFi.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <NetworkClientSecure.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Fonts/TomThumb.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
const char* ssid = "Wokwi-GUEST";
const char* password = "";
String question;
String NovaResposta;
// HTML web page
WebServer server(80);
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
#Campos{
height: 450px;
width: 450px;
margin-left: auto;
margin-right: auto;
background-color: rgb(214, 214, 214);
border-radius: 2em;
text-align: center;
filter: drop-shadow(3px 7px 2px gray);
}
#Perguntas{
height: 35px;
border-radius: 25em;
border: 2px solid white;
width: 245px;
font-family: Arial black;
font-style: italic;
}
#Envi{
border: 2px solid white;
height: 35px;
width: 35px;
border-radius: 25em;
color: white;
font-family: Arial, Helvetica, sans-serif;
font-weight: 900;
font-style: italic;
background-color: rgb(54, 245, 37);
text-align: center;
opacity: 0.55;
scale: 1.1;
position: relative;
left: 5px;
}
#EnviVoice{
border: 2px solid white;
height: 35px;
width: 35px;
border-radius: 25em;
color: white;
font-family: Arial, Helvetica, sans-serif;
font-weight: 900;
font-style: italic;
background-color: red;
text-align: center;
scale: 1.1;
position: relative;
left: 12px;
}
#MsgIcon{
font-size: 15px;
scale: 1.2;
position: relative;
top: 2px;
}
#Mic{
scale: 1.1;
}
.PartesDoChat{
position: relative;
top: 75px;
filter: drop-shadow(3px 4px 2px gray);
}
#resultSpeak {
position: relative;
display: block;
width: 280px;
color: black;
margin-left: auto;
margin-right: auto;
font-weight: 500;
position: relative;
top: 95px;
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 1.2em;
filter: drop-shadow(3px 4px 2px gray);
margin-top: 40px;
}
</style>
</head>
<body>
<div id="Campos">
<br>
<br>
<br>
<br>
<br>
<br>
<input class="PartesDoChat" placeholder="FAÇA UMA PERGUNTA" type="text" id="Perguntas" onkeydown="verificar()" onkeypress="verificar()" onkeyup="verificar()">
<button id="Envi" class="PartesDoChat" onclick="SendQuestion()" disabled><i class="material-icons" id="MsgIcon"></i></button>
<button id="EnviVoice" class="PartesDoChat" ><i id="Mic" class="fa fa-microphone"></i></button><br>
<div id="resultSpeak"></div>
</div><br>
<label id="Novo"></label>
<script>
function verificar(){
var question = document.getElementById("Perguntas").value;
if(question == ""){
document.getElementById("Envi").style.opacity = "0.55";
document.getElementById("Envi").disabled = true;
}else{
document.getElementById("Envi").style.opacity = "1.0";
document.getElementById("Envi").disabled = false;
}
}
function SendQuestion(){
var question = document.getElementById("Perguntas").value;
var QuestionS = new XMLHttpRequest();
QuestionS.open("GET", "/Question?value="+question, true);
QuestionS.send();
document.getElementById("Perguntas").value = "";
document.getElementById("Envi").style.opacity = "0.55";
document.getElementById("Envi").disabled = true;
}
var speakBtn = document.querySelector('#EnviVoice');
var resultSpeaker = document.querySelector('#resultSpeak');
if (window.SpeechRecognition || window.webkitSpeechRecognition) {
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
var myRecognition = new SpeechRecognition();
speakBtn.addEventListener('click', function () {
try {
myRecognition.start();
resultSpeaker.innerHTML = "Fale a mensagem.";
document.getElementById("EnviVoice").style.backgroundColor = "rgb(54, 245, 37)";
} catch (erro) {
alert('erro:' + erro.message);
}
}, false);
myRecognition.addEventListener('result', function (evt) {
var resultSpeak = evt.results[0][0].transcript;
console.log(resultSpeak);
resultSpeaker.innerHTML = resultSpeak;
var question = document.getElementById("Perguntas").value;
var QuestionS = new XMLHttpRequest();
if(resultSpeaker.innerHTML.startsWith("Qual") || resultSpeaker.innerHTML.startsWith("Quais")
||resultSpeaker.innerHTML.startsWith("qual") || resultSpeaker.innerHTML.startsWith("quais")
||resultSpeaker.innerHTML.startsWith("Quem") || resultSpeaker.innerHTML.startsWith("O que")
||resultSpeaker.innerHTML.startsWith("quem") || resultSpeaker.innerHTML.startsWith("o que")
||resultSpeaker.innerHTML.startsWith("Porque") || resultSpeaker.innerHTML.startsWith("Por que")
||resultSpeaker.innerHTML.startsWith("porque") || resultSpeaker.innerHTML.startsWith("por que")
||resultSpeaker.innerHTML.startsWith("Quanto") || resultSpeaker.innerHTML.startsWith("Quantos")
||resultSpeaker.innerHTML.startsWith("quanto") || resultSpeaker.innerHTML.startsWith("quantos")
||resultSpeaker.innerHTML.startsWith("quanta") || resultSpeaker.innerHTML.startsWith("quantas")
||resultSpeaker.innerHTML.startsWith("Quanta") || resultSpeaker.innerHTML.startsWith("Quantas")
||resultSpeaker.innerHTML.startsWith("É") || resultSpeaker.innerHTML.startsWith("é")){
QuestionS.open("GET", "/Question?value="+resultSpeak+"?", true);
QuestionS.send();
}else{
QuestionS.open("GET", "/Question?value="+resultSpeak, true);
QuestionS.send();
}
// resultSpeaker.innerHTML = "invalido";
setTimeout(limpar,5000);
function limpar(){
resultSpeaker.innerHTML = "";
clearTimeout(limpar);
}
document.getElementById("EnviVoice").style.backgroundColor = "red";
if (resultSpeak.match(/buscar por/)) {
resultSpeaker.innerHTML = 'Redirecionando...';
setTimeout(function(){
var resultado = resultSpeak.split('buscar por');
window.location.href = 'https://www.google.com.br/search?q=' + resultado[1];
},100);
}
}, false);
myRecognition.addEventListener('error', function (evt) {
document.getElementById("EnviVoice").style.backgroundColor = "red";
resultSpeaker.innerHTML = 'Uso do microfone não foi autorizado neste navegador.';
setTimeout(limpar,5000);
function limpar(){
resultSpeaker.innerHTML = "";
clearTimeout(limpar);
}
}, false);
} else {
resultSpeaker.innerHTML = 'Seu navegador não suporta essa tecnoligia.';
}
var resp = ""; // Armazena a última resposta para comparação
setInterval(function () {
const reqResp = new XMLHttpRequest();
reqResp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
const novaResp = reqResp.responseText; // Obtém a nova resposta do servidor
// Verifica se a resposta é diferente da anterior
if (novaResp !== resp) {
resp = novaResp; // Atualiza a resposta armazenada
let voice = new SpeechSynthesisUtterance(resp);
speechSynthesis.speak(voice); // Fala a nova resposta
}
}
};
reqResp.open('GET', '/respostas', true);
reqResp.send();
}, 1000);
</script>
</body>
</html>
)rawliteral";
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32-S3!");
if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.display();
delay(2000); // Pause for 2 seconds
// Clear the buffer
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println(WiFi.localIP());
server.on("/", HTTP_GET, []() {
String page = index_html;
page.replace("%QUESTION%", String(question));
server.send(200, "text/html", page);
});
server.on("/Question", HTTP_GET, []() {
if (server.hasArg("value")) {
question = server.arg("value");
Serial.println("Pergunta: " + question);
NetworkClientSecure client;
client.setInsecure(); // Ignorar validação SSL
HTTPClient https;
if (https.begin(client, "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=AQ.Ab8RN6Jmgj0_oZ5U46cAAYP6dSCcLtSyNiOm-BkWw-3Q6cIF7w")) {
// Adiciona os cabeçalhos
https.addHeader("Content-Type", "application/json");
String payload =
"{"
"\"contents\": [{\"parts\": [{\"text\": \"" + question + "\"}]}],"
"\"generationConfig\": {"
"\"temperature\": 0.7,"
"\"topK\": 40,"
"\"topP\": 0.8,"
"\"maxOutputTokens\": 256,"
"\"stopSequences\": []"
"}"
"}";
// Faz a solicitação POST
int httpCode = https.POST(payload);
if (httpCode > 0) {
if (httpCode == HTTP_CODE_OK) {
String response = https.getString();
JsonDocument filter;
JsonDocument doc;
deserializeJson(doc, response);
Serial.println(response);
String resposta = doc["candidates"][0]["content"]["parts"][0]["text"].as<String>();
delay(1000);
Serial.println(resposta);
NovaResposta = resposta;
server.send(200, "application/json", response);
} else {
Serial.printf("Erro: Código HTTP %d\n", httpCode);
server.send(httpCode, "text/plain", "Erro na solicitação à API da OpenAI");
}
} else {
Serial.printf("Erro ao enviar a solicitação: %s\n", https.errorToString(httpCode).c_str());
server.send(500, "text/plain", "Erro interno no servidor");
}
https.end();
} else {
Serial.println("Falha ao iniciar a conexão HTTPS");
server.send(500, "text/plain", "Erro ao conectar à API da OpenAI");
}
} else {
server.send(400, "text/plain", "Parâmetro 'value' não fornecido");
}
});
server.on("/respostas", HTTP_GET, [](){
server.send(200, "text/plain", String(NovaResposta).c_str());
});
server.begin();
display.clearDisplay();
display.setTextSize(1); // Draw 2X-scale text
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println(WiFi.localIP());
display.display();
}
void loop() {
if(Serial.available()){
question = Serial.readString()+"Responda resumidamente";
Serial.println("Pergunta: " + question);
NetworkClientSecure client;
client.setInsecure(); // Ignorar validação SSL
HTTPClient https;
if (https.begin(client, "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash-lite:generateContent?key=AQ.Ab8RN6Jmgj0_oZ5U46cAAYP6dSCcLtSyNiOm-BkWw-3Q6cIF7w")) {
// Adiciona os cabeçalhos
https.addHeader("Content-Type", "application/json");
String payload =
"{"
"\"contents\": [{\"parts\": [{\"text\": \"" + question + "\"}]}],"
"\"generationConfig\": {"
"\"temperature\": 0.7,"
"\"topK\": 40,"
"\"topP\": 0.8,"
"\"maxOutputTokens\": 512,"
"\"stopSequences\": []"
"}"
"}";
// Faz a solicitação POST
int httpCode = https.POST(payload);
if (httpCode > 0) {
if (httpCode == HTTP_CODE_OK) {
String response = https.getString();
JsonDocument filter;
JsonDocument doc;
deserializeJson(doc, response);
//Serial.println(response);
String resposta = doc["candidates"][0]["content"]["parts"][0]["text"].as<String>();
delay(1000);
Serial.println(resposta);
NovaResposta = resposta;
if(resposta.length() > 168){
for(int i = 0; i < resposta.length(); i++){
display.clearDisplay();
display.setTextSize(1); // Draw 2X-scale text
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, -i);
display.println(resposta);
display.display();
delay(85);
}
}else{
display.clearDisplay();
display.setTextSize(1); // Draw 2X-scale text
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println(resposta[i]);
display.display();
}
} else {
Serial.printf("Erro: Código HTTP %d\n", httpCode);
}
} else {
Serial.printf("Erro ao enviar a solicitação: %s\n", https.errorToString(httpCode).c_str());
}
https.end();
} else {
Serial.println("Falha ao iniciar a conexão HTTPS");
}
}
}
Loading
esp32-s3-devkitc-1
esp32-s3-devkitc-1
Loading
ssd1306
ssd1306
Loading
ssd1306
ssd1306