Paul Ruiz
Published © Apache-2.0

Connecting an ESP8266 to Gemini

A quick example of connecting an ESP8266 to the Gemini AI API.

BeginnerProtip1 hour617
Connecting an ESP8266 to Gemini

Things used in this project

Hardware components

ESP8266 ESP-12E
Espressif ESP8266 ESP-12E
×1

Software apps and online services

Google Gemini

Story

Read more

Code

ESP32 to Gemini Code

Arduino
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>

const String ssid = "wifi ssid";
const String password = "wifi password";
const String API_key = "Gemini API Key";

void setupWifi() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print("...");
  }
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);

  WiFi.mode(WIFI_STA);
  WiFi.disconnect();

  while (!Serial) ;

  setupWifi();
}

void makeGeminiRequest(String input) {

  WiFiClientSecure client;
  client.setInsecure();
  HTTPClient http;

  if (http.begin(client, "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=" + API_key)) {
    http.addHeader("Content-Type", "application/json");
    String payload = String("{\"contents\": [{\"parts\":[{\"text\":\"" + input + "\"}]}]}");

    int httpCode = http.POST(payload);

    if (httpCode == HTTP_CODE_OK) {
      String payload = http.getString();

      Serial.println("Payload: " + payload);

      DynamicJsonDocument doc(2048);
      deserializeJson(doc, payload);
      String responseText = doc["candidates"][0]["content"]["parts"][0]["text"];

      Serial.print("Response: ");
      Serial.println(responseText);
    } else {
      Serial.println("Failed to reach Gemini");
    }

    http.end();
  } else {
    Serial.print("Unable to connect\n");
  }
}

void loop() {
    if (Serial.available() > 0) {
      String sentence = Serial.readStringUntil('\n'); // Read until newline character

      Serial.print("You entered: ");
      Serial.println(sentence);
      makeGeminiRequest(sentence);
      Serial.println("Enter another sentence:"); // Prompt for another sentence
  }
}

Credits

Paul Ruiz
22 projects • 90 followers
Sr. Developer Relations Engineer @ Google DeepMind. IoT and mobile developer. Formally robotics.
Contact

Comments

Please log in or sign up to comment.