Quick answer: to build an ESP32 voice assistant without a computer, connect an INMP441 I2S microphone and a MAX98357A I2S amplifier with a small speaker to the ESP32, add a push button, and upload the sketch below. While you hold the button the ESP32 records your voice. When you let go it sends the recording to OpenAI's speech-to-text model, asks Claude for a short answer, turns the answer into speech with OpenAI's voice model and plays it through the speaker.
Ever wondered what happens inside a smart speaker? In this project you build your own: a little desk assistant called Pip. Hold the button, ask "How far away is the Moon?", let go, and a few seconds later Pip answers out loud. An RGB LED shows what it is doing: red while it listens, blue while it thinks and green while it speaks. Add the kit's 1602 LCD and the answer scrolls across the screen too. Once uploaded, it runs on its own from any USB power supply: no computer, no phone, no browser.
Our AI desk assistant capstone borrows your computer: the browser listens and the computer's voice reads the answer. Here the ESP32 does it all by itself, with its own microphone and speaker. That means real sound handling on a small board without extra memory, which is what makes this lesson advanced.
What you need
- ESP32 board, expansion board, USB cable, push button, RGB LED, 3 resistors of 220 Ω, breadboard and jumper wires. All of them are in the EEMENTOR ESP32 IoT Starter Kit. Optional: the kit's 1602 LCD, a 10 kΩ potentiometer, one more 220 Ω resistor and a 100 µF capacitor.
- INMP441 I2S MEMS microphone module (not in the kit)
- MAX98357A I2S amplifier module, from Adafruit or a compatible board (not in the kit)
- A small speaker, 4 to 8 Ω, about 3 W, ideally round and up to 40 mm across so it fits the printed case (not in the kit)
- A 2.4 GHz Wi-Fi network, and a 5 V USB phone charger to power the assistant on your desk
- API keys for Claude (Anthropic) and OpenAI, set up by an adult (see Step 2)
- A soldering iron for the header pins of the two modules, and an adult to help with it
- Optional: the printed desk case from the 3D printing box below
New to the ESP32? Do Set up the ESP32 in the Arduino IDE first, so the board, the driver and the port already work.
Safety and privacy: the assistant only records while you hold the button, and only for a few seconds. Every question goes over the internet: your voice to OpenAI, the text to Anthropic for Claude's answer, and the answer back to OpenAI to be spoken. So never say anything private, such as passwords, addresses or full names, and tell people nearby when you use it. An adult must own the two API accounts, set a low spending limit and keep the keys secret. Claude can make mistakes, so check important facts with a trusted adult or a good book.
Step 1: Solder the modules and wire everything
Both audio modules usually come with loose header pins: solder them on with an adult's help, short side through the board. Unplug the USB cable before you change any wiring.
The microphone and the amplifier both talk to the ESP32 over I2S (say "eye-squared-ess"), a bus made for digital sound: a bit clock (BCLK or SCK), a word select (WS or LRC) for left or right, and a data line (SD or DIN) that carries the sound as numbers. The ESP32 has two I2S units, one for each module.

| From | To |
|---|---|
| INMP441 SCK | ESP32 GPIO 26 |
| INMP441 WS | ESP32 GPIO 25 |
| INMP441 SD | ESP32 GPIO 34 |
| INMP441 VDD | ESP32 3V3 (never 5 V) |
| INMP441 GND and L/R | GND (the blue rail) |
| MAX98357A LRC | ESP32 GPIO 14 |
| MAX98357A BCLK | ESP32 GPIO 27 |
| MAX98357A DIN | ESP32 GPIO 13 |
| MAX98357A Vin | 5 V (the red rail, from the ESP32's 5V or VIN pin) |
| MAX98357A GND | GND (the blue rail) |
| MAX98357A GAIN and SD | Not connected |
| Speaker | The amplifier's + and − screw terminal |
| Push button | One leg to GPIO 32, the other to GND |
| RGB LED red, green, blue legs | Each through a 220 Ω resistor to GPIO 21, 22 and 33 |
| RGB LED longest leg (common) | GND |
| Optional 1602 LCD | RS 19, E 23, D4–D7 to 18, 17, 16, 4, wired exactly as in the AI chat buddy on the LCD |
GPIO 34 is input-only, perfect for the microphone's data. The INMP441 must get 3.3 V: 5 V is above its limit and can damage it. The amplifier gets 5 V for more speaker power. If the speaker crackles at loud moments, put the kit's 100 µF capacitor across the amplifier's Vin and GND, long leg to Vin.
Step 2: Get the two API keys (adults only)
OpenAI hears and speaks: it turns your voice into text and the answer into speech. Claude, made by Anthropic, reads your question and writes the answer. Both charge a small amount per question and both accounts must belong to an adult, so ask a parent or teacher to do this step.
-
For Claude: create an account at console.anthropic.com, add a small amount of credit and set a low monthly spend limit. Under API keys, create a key. It starts with
sk-ant-. -
For OpenAI: create an account at platform.openai.com, add a small amount of credit, set a low monthly budget and create a new secret key under API keys. It starts with
sk-. - Make new keys just for this project. A key is like a password and a credit card in one: keep it out of photos and shared code, and delete it when you are done.
Step 3: Set up the Arduino IDE
- In Boards Manager, install or update esp32 by Espressif Systems to version 3 or newer. It includes I2S, Wi-Fi and HTTPS.
- In Library Manager, install ArduinoJson by Benoit Blanchon (version 7). If you use the LCD, check that LiquidCrystal is installed too.
- Choose Tools → Board → esp32 → ESP32 Dev Module and your board's port.
Step 4: Add the secrets tab
Save a new sketch as voice_desk_assistant, then use the arrow at the right of the tabs to add a New Tab called secrets.h. Paste this in and let the adult type in the Wi-Fi details and the two keys. In their own tab, they stay out of the main sketch you show and share.
// secrets.h: your Wi-Fi details and the two API keys. An adult should fill this tab in.
// Never photograph this tab, never share it, and remove the keys before you post your sketch online.
#pragma once
const char* WIFI_NAME = "YOUR_WIFI_NAME"; // 2.4 GHz Wi-Fi only
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
const char* CLAUDE_KEY = "YOUR_ANTHROPIC_API_KEY"; // starts with sk-ant-
const char* OPENAI_KEY = "YOUR_OPENAI_API_KEY"; // starts with sk-Step 5: Upload the assistant sketch
Paste this into the main tab and upload it. It is long, but split into clear parts: status light, LCD, sounds, recording and the three trips to the cloud.
// Smart desk assistant that hears you and talks back (EEMENTOR STEM)
// Hold the button and speak, then let go. The ESP32 sends your voice to OpenAI (speech -> text),
// asks Claude for a short answer and speaks it through the MAX98357A amplifier and the speaker.
// No computer needed once it is uploaded: a USB power supply and Wi-Fi are enough.
// Board: classic ESP32 (Tools > Board > esp32 > ESP32 Dev Module). It works without PSRAM.
// Library: ArduinoJson by Benoit Blanchon. I2S, Wi-Fi, HTTPClient and LiquidCrystal come with the IDE.
// Put your Wi-Fi details and the two API keys in the secrets.h tab.
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <ESP_I2S.h>
#include <LiquidCrystal.h>
#include "secrets.h"
// ---------- settings ----------
const char* CLAUDE_MODEL = "claude-opus-5-5"; // writes the answer
const char* HEAR_MODEL = "gpt-transcribe"; // speech -> text
const char* VOICE_MODEL = "gpt-audio-1.5"; // text -> speech
const char* VOICE = "marin";
const int VOLUME = 50; // 0 to 100: a 3 W speaker is loud, start low
const int MIC_GAIN = 4; // the INMP441 is quiet: make it louder
const int MAX_HALF_SECONDS = 10; // longest question: 10 x 0.5 s = 5 s (if the memory allows)
const int MEMORY_TURNS = 3; // remembers the last 3 questions and answers
const bool USE_LCD = true; // false if you have not connected the 1602 LCD
const char* PERSONALITY = "You are Pip, a friendly desk assistant that a young maker built with an ESP32. "
"You hear the user through a small microphone and a speaker reads your answer aloud, so write for the ear. "
"Answer in one to three short sentences, at most 45 words, in plain, friendly English that a ten-year-old understands. "
"No lists, headings, symbols, emoji or links, and write numbers the way you would say them. "
"Be kind, honest and encouraging, and keep everything suitable for children. "
"You can't look things up: if a question needs live information such as the time, the weather or the news, say so. "
"If you are not sure, say that too. Never ask for personal details such as a full name, address, school or passwords. "
"If the user seems upset or in danger, gently tell them to talk to a trusted adult. "
"The question was turned from speech into text, so if it looks garbled, ask them to say it again.";
const char* READ_ALOUD = "You are the voice of a friendly desk assistant. Read the user's message aloud exactly as written, "
"in a warm, clear voice at a natural pace. Do not answer it, add to it or change it.";
// ---------- pins ----------
const int MIC_SCK = 26, MIC_WS = 25, MIC_SD = 34; // INMP441 microphone (GPIO 34 is input-only: perfect for SD)
const int AMP_BCLK = 27, AMP_LRC = 14, AMP_DIN = 13;// MAX98357A amplifier
const int BUTTON = 32; // push button to GND
const int LED_R = 21, LED_G = 22, LED_B = 33; // RGB LED (common cathode), each colour through 220 ohms
LiquidCrystal lcd(19, 23, 18, 17, 16, 4); // optional 1602 LCD: RS, E, D4, D5, D6, D7
const int RATE = 16000; // microphone: 16 000 samples a second, 16 bits each
I2SClass mic(I2S_NUM_0);
I2SClass speaker(I2S_NUM_1);
uint32_t speakerRate = 24000;
// The recording is kept in half-second blocks, because a board without PSRAM has no single free
// piece of memory big enough for 5 seconds of sound (160 000 bytes).
const size_t BLOCK = RATE; // 16 000 bytes = 8 000 samples = 0.5 s
uint8_t* blocks[MAX_HALF_SECONDS];
int blockCount = 0;
size_t soundLen = 0; // bytes of sound recorded
String history[2 * MEMORY_TURNS]; // question, answer, question, answer...
int historyCount = 0;
// ---------- status light ----------
void led(int r, int g, int b) { analogWrite(LED_R, r); analogWrite(LED_G, g); analogWrite(LED_B, b); }
void ledReady() { led(0, 12, 0); } // dim green: press the button to talk
void ledListening() { led(255, 0, 0); } // red: recording
void ledThinking() { led(0, 0, 255); } // blue: waiting for the AI
void ledSpeaking() { led(0, 255, 0); } // green: talking
// ---------- LCD ----------
String lines[40]; // the answer, wrapped into 16-character lines
int lineCount = 0, lineShown = 0;
unsigned long lastPage = 0;
String plain(const String& s) { // the LCD only knows plain letters: swap curly quotes, drop the rest
String out;
for (unsigned int i = 0; i < s.length(); i++) {
uint8_t c = s[i];
if (c >= 32 && c < 127) out += (char)c;
else if (c == 0xE2 && i + 2 < s.length()) {
uint8_t d = s[i + 2];
out += (d == 0x98 || d == 0x99) ? '\'' : (d == 0x9C || d == 0x9D) ? '"' : ' ';
i += 2;
} else if (c >= 0xC0) out += ' '; // first byte of another special letter
}
return out;
}
void show(const String& top, const String& bottom) {
if (!USE_LCD) return;
lineCount = 0; // stop paging through an old answer
lcd.clear();
lcd.print(plain(top).substring(0, 16));
lcd.setCursor(0, 1);
lcd.print(plain(bottom).substring(0, 16));
}
void startPages(const String& text) { // word-wrap the answer so it can scroll on the LCD
if (!USE_LCD) return;
String t = plain(text), line;
lineCount = 0;
int i = 0;
while (i < (int)t.length() && lineCount < 40) {
int sp = t.indexOf(' ', i);
if (sp < 0) sp = t.length();
String word = t.substring(i, sp).substring(0, 16);
if (line.length() && line.length() + 1 + word.length() > 16) { lines[lineCount++] = line; line = ""; }
line += (line.length() ? " " : "") + word;
i = sp + 1;
}
if (line.length() && lineCount < 40) lines[lineCount++] = line;
lineShown = -2;
lastPage = 0;
}
void nextPage() { // shows two new lines every 2 seconds, then starts again
if (!USE_LCD || lineCount == 0 || millis() - lastPage < 2000) return;
lastPage = millis();
lineShown += 2;
if (lineShown >= lineCount) lineShown = 0;
lcd.clear();
lcd.print(lines[lineShown]);
if (lineShown + 1 < lineCount) { lcd.setCursor(0, 1); lcd.print(lines[lineShown + 1]); }
}
// ---------- sounds ----------
void beep(int freq, int ms) {
const int N = 240;
int16_t buf[N];
long total = (long)speakerRate * ms / 1000, done = 0;
while (done < total) {
int n = min((long)N, total - done);
for (int i = 0; i < n; i++) buf[i] = (int16_t)(4000 * VOLUME / 100 * sin(2 * PI * freq * (done + i) / speakerRate));
speaker.write((uint8_t*)buf, n * 2);
done += n;
}
memset(buf, 0, sizeof(buf)); // a moment of silence so the amplifier doesn't click
speaker.write((uint8_t*)buf, sizeof(buf));
}
void errorBeeps() { for (int i = 0; i < 3; i++) { beep(300, 150); delay(80); } }
// ---------- the button ----------
bool pressed() { // LOW for 20 ms in a row: a real press, not noise
for (int i = 0; i < 3; i++) { if (digitalRead(BUTTON) == HIGH) return false; delay(10); }
return true;
}
// ---------- recording while the button is held ----------
// The INMP441 sends 32-bit numbers on the left or the right half of each I2S frame, depending on its L/R pin.
// The sketch reads both halves and keeps the side that has sound on it.
void record() {
int32_t frames[512]; // 256 frames: left, right, left, right...
long sum[2] = {0, 0};
for (int i = 0; i < 6; i++) { // throw away old sound (and the beep), and find the microphone's side
size_t got = mic.readBytes((char*)frames, sizeof(frames)) / 4;
for (size_t k = 0; k + 1 < got; k += 2) { sum[0] += abs(frames[k] >> 16); sum[1] += abs(frames[k + 1] >> 16); }
}
int side = sum[1] > sum[0] ? 1 : 0;
size_t room = blockCount * BLOCK;
unsigned long released = 0;
soundLen = 0;
while (soundLen < room) {
if (digitalRead(BUTTON) == HIGH) { // let go for 30 ms: the question is finished
if (!released) released = millis();
else if (millis() - released > 30) return;
} else released = 0;
size_t got = mic.readBytes((char*)frames, sizeof(frames)) / 8;
for (size_t k = 0; k < got && soundLen < room; k++) {
int32_t v = (frames[2 * k + side] >> 16) * MIC_GAIN; // 24-bit sound -> 16 bits, a bit louder
int16_t s = constrain(v, -32768, 32767);
uint8_t* p = blocks[soundLen / BLOCK] + soundLen % BLOCK;
p[0] = s & 0xFF; // WAV files store the low byte first
p[1] = (s >> 8) & 0xFF;
soundLen += 2;
}
}
beep(500, 80); // memory full: "stopped listening"
}
void writeWavHeader(uint8_t* h, uint32_t dataLen) {
uint32_t v;
memcpy(h, "RIFF", 4); v = dataLen + 36; memcpy(h + 4, &v, 4);
memcpy(h + 8, "WAVEfmt ", 8); v = 16; memcpy(h + 16, &v, 4);
uint16_t pcm = 1, ch = 1, bits = 16, align = 2;
memcpy(h + 20, &pcm, 2); memcpy(h + 22, &ch, 2);
v = RATE; memcpy(h + 24, &v, 4); v = RATE * 2; memcpy(h + 28, &v, 4);
memcpy(h + 32, &align, 2); memcpy(h + 34, &bits, 2);
memcpy(h + 36, "data", 4); memcpy(h + 40, &dataLen, 4);
}
// The upload is built on the fly, piece by piece, while it is sent:
// form header + WAV header + the sound blocks + form end. Nothing big is copied.
class Upload : public Stream {
public:
String head, tail;
uint8_t wav[44];
size_t pos = 0, total = 0;
using Stream::readBytes;
int available() override { return total - pos; }
int peek() override { return -1; }
int read() override { char c; return readBytes(&c, 1) == 1 ? (uint8_t)c : -1; }
size_t write(uint8_t) override { return 0; }
size_t readBytes(char* buf, size_t len) override {
size_t done = 0;
const size_t a = head.length(), b = a + 44, c = b + soundLen;
while (done < len && pos < total) {
const uint8_t* src;
size_t n;
if (pos < a) { src = (const uint8_t*)head.c_str() + pos; n = a - pos; }
else if (pos < b) { src = wav + (pos - a); n = b - pos; }
else if (pos < c) { size_t off = pos - b; src = blocks[off / BLOCK] + off % BLOCK; n = min(BLOCK - off % BLOCK, c - pos); }
else { src = (const uint8_t*)tail.c_str() + (pos - c); n = total - pos; }
n = min(n, len - done);
memcpy(buf + done, src, n);
done += n;
pos += n;
}
return done;
}
};
// ---------- 1. speech -> text (OpenAI) ----------
int hearStatus = 0; // 200 = OK, anything else = the error code
String hear() {
const char* B = "----eementorDeskPip24";
Upload body;
body.head = String("--") + B + "\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\n" + HEAR_MODEL + "\r\n" +
"--" + B + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"question.wav\"\r\n" +
"Content-Type: audio/wav\r\n\r\n";
body.tail = String("\r\n--") + B + "--\r\n";
writeWavHeader(body.wav, soundLen);
body.total = body.head.length() + 44 + soundLen + body.tail.length();
WiFiClientSecure client;
client.setInsecure();
HTTPClient http;
http.setTimeout(30000);
http.begin(client, "https://api.openai.com/v1/audio/transcriptions");
http.addHeader("Authorization", String("Bearer ") + OPENAI_KEY);
http.addHeader("Content-Type", String("multipart/form-data; boundary=") + B);
hearStatus = http.sendRequest("POST", &body, body.total);
String response = http.getString();
http.end();
if (hearStatus != 200) { Serial.printf("Hearing error %d: %s\n", hearStatus, response.c_str()); return ""; }
JsonDocument filter;
filter["text"] = true;
JsonDocument answer;
DeserializationError err = deserializeJson(answer, response, DeserializationOption::Filter(filter));
if (err) { Serial.printf("Hearing: strange answer (%s)\n", err.c_str()); return ""; }
String text = answer["text"] | "";
text.trim();
return text;
}
// ---------- 2. question -> answer (Claude), with a short memory ----------
void remember(const String& question, const String& answer) {
if (historyCount == 2 * MEMORY_TURNS) { // full: forget the oldest question and answer
for (int i = 2; i < historyCount; i++) history[i - 2] = history[i];
historyCount -= 2;
}
history[historyCount++] = question;
history[historyCount++] = answer;
}
String ask(const String& question) {
JsonDocument request;
request["model"] = CLAUDE_MODEL;
request["max_tokens"] = 1000; // room for a little thinking and a short answer
request["output_config"]["effort"] = "low"; // quick answers
request["fallbacks"] = "default"; // if this model declines, another one may answer
request["system"] = PERSONALITY;
JsonArray msgs = request["messages"].to<JsonArray>();
for (int i = 0; i < historyCount; i++) { // the last few turns, so it can follow the conversation
JsonObject m = msgs.add<JsonObject>();
m["role"] = (i % 2 == 0) ? "user" : "assistant";
m["content"] = history[i];
}
JsonObject m = msgs.add<JsonObject>();
m["role"] = "user";
m["content"] = question;
String body;
serializeJson(request, body);
request.clear();
WiFiClientSecure client;
client.setInsecure();
HTTPClient http;
http.setTimeout(60000);
http.begin(client, "https://api.anthropic.com/v1/messages");
http.addHeader("content-type", "application/json");
http.addHeader("x-api-key", CLAUDE_KEY);
http.addHeader("anthropic-version", "2026-10-21");
http.addHeader("anthropic-beta", "server-side-fallback-2026-07-01");
int status = http.POST(body);
String response = http.getString();
http.end();
if (status != 200) {
Serial.printf("Claude error %d: %s\n", status, response.c_str());
if (status == 401) return "Please check my Claude API key.";
if (status == 400 && response.indexOf("credit") >= 0) return "My Claude account has no credit left.";
if (status == 429) return "Too many questions. Please wait a minute.";
if (status == 529 || status == 503) return "The A I is busy. Please try again.";
if (status < 0) return "I have no internet connection.";
return "Sorry, I could not reach the A I.";
}
JsonDocument filter;
filter["stop_reason"] = true;
filter["content"][0]["type"] = true;
filter["content"][0]["text"] = true;
JsonDocument answer;
DeserializationError err = deserializeJson(answer, response, DeserializationOption::Filter(filter));
if (err) { Serial.printf("Claude: strange answer (%s)\n", err.c_str()); return "Sorry, I got a strange answer."; }
if (answer["stop_reason"] == "refusal") return "Sorry, I can't help with that one.";
String text = "";
for (JsonObject block : answer["content"].as<JsonArray>())
if (block["type"] == "text") text += block["text"].as<String>(); // skip the thinking blocks
text.trim();
if (!text.length()) return "Sorry, I got an empty answer.";
remember(question, text);
return text;
}
// ---------- 3. text -> speech (OpenAI), played while it downloads ----------
// The answer is a WAV file in Base64 inside a JSON reply, about a megabyte for 15 seconds of speech:
// far too big for the ESP32's memory. So the sketch never keeps it. It reads the reply a few hundred
// bytes at a time, finds "data", turns every 4 Base64 letters back into 3 bytes of sound and sends
// the samples straight to the amplifier.
WiFiClient* net;
uint8_t inBuf[512];
int inLen = 0, inPos = 0;
int nextChar() { // the next byte of the reply, or -1 at the end
if (inPos >= inLen) {
unsigned long start = millis();
while (!net->available()) {
if (!net->connected() || millis() - start > 15000) return -1;
delay(1);
}
inLen = net->read(inBuf, sizeof(inBuf));
inPos = 0;
if (inLen <= 0) return -1;
}
return inBuf[inPos++];
}
int b64(int c) {
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
return -1; // '=' and anything else
}
// The WAV player: first the header (how to play it), then the samples
uint8_t wavHead[256];
size_t wavHeadLen = 0;
bool playing = false;
uint16_t wavChannels = 1;
uint8_t frame[4];
int frameLen = 0;
int16_t out[256];
int outLen = 0;
void playSample(uint8_t b) {
frame[frameLen++] = b;
if (frameLen < 2 * wavChannels) return; // wait for a whole frame (2 bytes, or 4 in stereo)
frameLen = 0;
int16_t s = (int16_t)(frame[0] | (frame[1] << 8)); // left channel only
out[outLen++] = (int32_t)s * VOLUME / 100;
if (outLen == 256) { speaker.write((uint8_t*)out, sizeof(out)); outLen = 0; }
}
bool headerReady() { // walk through the WAV chunks: "fmt " says how, "data" starts the sound
if (wavHeadLen < 12) return false;
if (memcmp(wavHead, "RIFF", 4) || memcmp(wavHead + 8, "WAVE", 4)) return false;
size_t pos = 12;
uint32_t rate = 0;
uint16_t bits = 0;
while (pos + 8 <= wavHeadLen) {
uint32_t size;
memcpy(&size, wavHead + pos + 4, 4);
if (!memcmp(wavHead + pos, "fmt ", 4)) {
if (pos + 24 > wavHeadLen) return false;
memcpy(&wavChannels, wavHead + pos + 10, 2); memcpy(&rate, wavHead + pos + 12, 4); memcpy(&bits, wavHead + pos + 22, 2);
}
if (!memcmp(wavHead + pos, "data", 4)) {
if (bits != 16 || wavChannels < 1 || wavChannels > 2 || rate < 8000 || rate > 48000) {
Serial.printf("Voice: can't play this sound (%u Hz, %u channels, %u bits)\n", rate, wavChannels, bits);
wavChannels = 0;
return true;
}
if (rate != speakerRate && speaker.configureTX(rate, I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO)) speakerRate = rate;
playing = true;
ledSpeaking();
for (size_t i = pos + 8; i < wavHeadLen; i++) playSample(wavHead[i]); // sound that came with the header
return true;
}
if (size > sizeof(wavHead)) return false; // a big chunk we don't need: give up below
pos += 8 + size + (size & 1);
}
return false;
}
void soundByte(uint8_t b) {
if (playing) { playSample(b); return; }
if (wavChannels == 0) return; // unplayable: ignore the rest
if (wavHeadLen < sizeof(wavHead)) wavHead[wavHeadLen++] = b;
if (!headerReady() && wavHeadLen == sizeof(wavHead)) { Serial.println("Voice: not a WAV file"); wavChannels = 0; }
}
bool speak(const String& text) {
JsonDocument request;
request["model"] = VOICE_MODEL;
request["modalities"][0] = "text";
request["modalities"][1] = "audio";
request["audio"]["voice"] = VOICE;
request["audio"]["format"] = "wav";
JsonArray msgs = request["messages"].to<JsonArray>();
JsonObject sys = msgs.add<JsonObject>();
sys["role"] = "system";
sys["content"] = READ_ALOUD;
JsonObject user = msgs.add<JsonObject>();
user["role"] = "user";
user["content"] = text;
String body;
serializeJson(request, body);
WiFiClientSecure client;
client.setInsecure();
HTTPClient http;
http.setTimeout(60000);
http.useHTTP10(true); // a plain stream, so the sketch can read the reply as it arrives
http.begin(client, "https://api.openai.com/v1/chat/completions");
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", String("Bearer ") + OPENAI_KEY);
int status = http.POST(body);
if (status != 200) { Serial.printf("Voice error %d: %s\n", status, http.getString().substring(0, 300).c_str()); http.end(); return false; }
net = http.getStreamPtr();
inLen = inPos = 0;
wavHeadLen = 0; playing = false; wavChannels = 1; frameLen = 0; outLen = 0;
// 1. find "data" : " in the reply
const char* key = "\"data\"";
int matched = 0, c;
bool found = false;
while (!found && (c = nextChar()) >= 0) {
if (c == key[matched]) { if (++matched < 6) continue; }
else { matched = (c == '"') ? 1 : 0; continue; }
matched = 0;
do c = nextChar(); while (c == ' ' || c == '\n' || c == '\r' || c == '\t');
if (c != ':') continue;
do c = nextChar(); while (c == ' ' || c == '\n' || c == '\r' || c == '\t');
found = (c == '"');
}
// 2. decode the Base64 letters until the closing quote, and play the sound as it comes
uint32_t bitsIn = 0;
int bitCount = 0;
size_t letters = 0;
while (found && (c = nextChar()) >= 0 && c != '"') {
if (c == '\\') c = nextChar(); // JSON may write "/" as "\/"
int v = b64(c);
if (v < 0) continue;
letters++;
bitsIn = (bitsIn << 6) | v;
bitCount += 6;
if (bitCount >= 8) { bitCount -= 8; soundByte((bitsIn >> bitCount) & 0xFF); }
}
http.end();
if (outLen) speaker.write((uint8_t*)out, outLen * 2);
int16_t quiet[256] = {0};
speaker.write((uint8_t*)quiet, sizeof(quiet));
if (!playing) { Serial.printf("Voice: no sound in the reply (%u letters)\n", (unsigned)letters); return false; }
return true;
}
void say(const String& text) {
Serial.println("Pip: " + text);
if (!speak(text)) errorBeeps(); // no voice: check the OpenAI key and the Serial Monitor
}
// ---------- Wi-Fi ----------
bool online() {
if (WiFi.status() == WL_CONNECTED) return true;
WiFi.reconnect();
for (int i = 0; i < 40 && WiFi.status() != WL_CONNECTED; i++) delay(250);
return WiFi.status() == WL_CONNECTED;
}
void setup() {
Serial.begin(115200);
pinMode(BUTTON, INPUT_PULLUP);
pinMode(LED_R, OUTPUT); pinMode(LED_G, OUTPUT); pinMode(LED_B, OUTPUT);
led(0, 0, 40);
if (USE_LCD) { lcd.begin(16, 2); show("Hello! I'm Pip", "Connecting..."); }
speaker.setPins(AMP_BCLK, AMP_LRC, AMP_DIN);
if (!speaker.begin(I2S_MODE_STD, speakerRate, I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO)) Serial.println("Speaker (I2S) did not start");
mic.setPins(MIC_SCK, MIC_WS, -1, MIC_SD);
if (!mic.begin(I2S_MODE_STD, RATE, I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO)) Serial.println("Microphone (I2S) did not start");
WiFi.mode(WIFI_STA);
WiFi.setSleep(false); // answers come back faster
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
for (int i = 0; i < 60 && WiFi.status() != WL_CONNECTED; i++) { delay(500); Serial.print("."); }
bool ok = WiFi.status() == WL_CONNECTED;
Serial.println(ok ? " connected" : " not connected yet: check secrets.h (2.4 GHz only)");
// Memory for the recording, half a second at a time. Keep about 80 KB free for the secure connections.
while (blockCount < MAX_HALF_SECONDS && ESP.getFreeHeap() > 80000 + BLOCK && ESP.getMaxAllocHeap() > BLOCK) {
blocks[blockCount] = (uint8_t*)malloc(BLOCK);
if (!blocks[blockCount]) break;
blockCount++;
}
Serial.printf("Longest question: %.1f s, free memory left: %u bytes\n", blockCount / 2.0, (unsigned)ESP.getFreeHeap());
if (ok && blockCount > 0) {
beep(660, 100); beep(880, 100); beep(1320, 150); // ready
show("Hold the button", "and ask me!");
} else {
errorBeeps();
show(ok ? "Out of memory" : "No Wi-Fi", "See Serial Monitor");
}
ledReady();
}
void loop() {
nextPage(); // keep scrolling the last answer on the LCD
if (!pressed()) { delay(10); return; }
ledListening();
show("Listening...", "Let go when done");
beep(1200, 60); // "I'm listening"
delay(60); // let the beep finish before recording
record(); // records until the button is let go
while (digitalRead(BUTTON) == LOW) delay(10); // held longer than the memory allows: wait for the release
if (soundLen < RATE) { // under half a second: probably just a tap
ledReady();
show("Hold the button", "while you talk");
return;
}
ledThinking();
if (!online()) { Serial.println("No Wi-Fi"); show("No Wi-Fi", "Check the router"); errorBeeps(); ledReady(); return; }
show("Thinking...", "");
String question = hear();
if (hearStatus == 401) { say("Please check my Open A I key."); ledReady(); return; }
if (hearStatus != 200) { say("Sorry, I could not reach the speech service."); ledReady(); return; }
if (question.length() < 2) { say("Sorry, I didn't hear anything. Hold the button and try again."); ledReady(); return; }
Serial.println("You: " + question);
show("You said:", question);
String answer = ask(question);
show(answer, answer.length() > 16 ? answer.substring(16) : "");
say(answer);
startPages(answer);
ledReady();
}client.setInsecure() keeps the connection encrypted but skips checking the server's certificate, which is fine for a learning project. For a gadget that runs for years, use client.setCACert() with the server's root certificate.
Step 6: Talk to Pip
- Open the Serial Monitor at 115200 baud and press EN (reset). After "connected" and a line such as
Longest question: 4.0 s, three rising beeps play and the LED glows dim green: Pip is ready. - Hold the button, wait for the beep, and ask a question in a normal voice, 20 to 40 cm from the microphone. Let go when you have finished.
- The LED turns blue while Pip thinks, then green while it speaks. The Serial Monitor shows what it heard ("You: …") and the answer ("Pip: …").
- Ask a follow-up, such as "How long would it take to fly there?". Pip remembers the last three turns, so it knows what "there" means.
- Power it from a USB phone charger instead of the computer. It reconnects to Wi-Fi by itself.
How it works

Listening. While you hold the button, the INMP441 sends 16,000 numbers a second, each a tiny measurement of the air pressure at the microphone. The sketch keeps the top 16 of its 24 bits, makes them four times louder and stores them. The microphone talks on the left or right half of each I2S frame, depending on its L/R pin, so the sketch checks both halves and keeps the one with sound.
Memory without PSRAM. Five seconds of this sound takes 160,000 bytes. The kit's ESP32 has about 320 KB of working memory and no extra PSRAM chip, so once Wi-Fi runs there is never one free piece that big. The sketch uses half-second blocks of 16,000 bytes instead, takes as many as fit while leaving about 80 KB for the secure connections, and reports the result as "Longest question". To upload, a small class called Upload hands HTTPClient the pieces one after another: form header, a 44-byte WAV header, the sound blocks and the form end.

Thinking. OpenAI's gpt-transcribe model sends back your words as text. The sketch passes them to Claude with the last three turns and a system prompt that gives Pip its personality: friendly, honest, at most 45 words, easy to say aloud, no lists or emoji, and safe for children. It also tells Pip to admit it can't look up today's weather or the news instead of guessing. effort is set to low for quick answers, and fallbacks lets another Claude model answer if the first one declines a question.
Speaking. The answer goes to OpenAI's voice model gpt-audio-1.5 with the instruction to read it aloud word for word. The speech comes back as a WAV file in Base64 inside a JSON reply: about a megabyte for a 15-second answer, far more than the ESP32 could hold. So the sketch reads the reply 512 bytes at a time, finds "data", turns every four Base64 letters back into three bytes, reads the WAV header for the sample rate and sends the samples straight to the MAX98357A. The speaker talks while the rest is still arriving, using sound buffers of under 2 KB.
Common errors and fixes
-
Three low beeps at start-up and "No Wi-Fi" on the LCD: check the name and password in
secrets.h(both are case-sensitive). The ESP32 only joins 2.4 GHz networks, and school or hotel networks with a login page don't work. - "Hearing error 401" or Pip says "Please check my Open A I key": the OpenAI key is wrong or was deleted. A 429 error means the account has no credit left or you asked too many questions too fast.
- It always says it didn't hear anything: check that VDD is on 3V3, SD on GPIO 34, and that SCK and WS aren't swapped.
-
It hears the wrong words: speak closer and wait for the beep. Try
MIC_GAIN2 if the sound distorts, 8 if it is very quiet. - No sound from the speaker, not even the beeps: check LRC on 14, BCLK on 27, DIN on 13 and Vin on 5 V. Make sure the speaker wires are screwed in tightly.
-
The ESP32 restarts while Pip speaks, or the sound crackles: the speaker needs more current than the USB port gives. Use a 5 V charger of at least 1 A, add the 100 µF capacitor, or lower
VOLUME. - The answer sounds choppy: the Wi-Fi is too slow. Move closer to the router.
- "Longest question" is short: keep questions brief. A board with PSRAM, like the one in the talking camera glasses, records much longer.
-
The LED stays dark or shows odd colours: the sketch expects a common-cathode LED (longest leg on GND). For a common-anode LED, put that leg on 3V3 and use
255 - valueinled().
FAQ
Can an ESP32 be a voice assistant without a computer?
Yes. With an I2S microphone, an I2S amplifier and a speaker, the ESP32 records your voice, sends it over Wi-Fi to online AI services and plays the spoken answer by itself. The AI runs in the cloud; the ESP32 handles the sound, the button and Wi-Fi.
Does the ESP32 need PSRAM for this project?
No. The sketch records in half-second blocks and plays the answer while it downloads, so the classic ESP32-WROOM-32 in our kit is enough. Questions are limited to a few seconds, which is plenty.
Is the assistant listening all the time?
No. It only records while you hold the button, and sends the recording to OpenAI after you let go. There is no wake word and no recording in the background.
Why does it use both Claude and OpenAI?
Claude writes the answers but works with text, so OpenAI handles the sound: speech to text on the way in, and text to speech on the way out. You need an API key from each company.
How is this different from the AI desk assistant capstone?
The AI desk assistant uses your computer's browser to hear you and your computer's voice to answer, with the ESP32 connected over USB. This project hears and speaks by itself through its own microphone and speaker, so it runs anywhere with Wi-Fi and a USB power supply.