/* Anybody Body firmware v3 (Stage 1c, rover) One brain. Any body. The rover drives on four wheels, waves two arms, turns its head, hears with its own microphone, sees with the camera in its head, and answers through its own speaker. Wi-Fi is the bridge to the Anybody brain; Bluetooth stays on for Wi-Fi setup, the tester, and the console. Board Seeed XIAO ESP32S3 Sense (camera, microphone, 8 MB PSRAM) Core "esp32" by Espressif Systems, version 3.x Board: XIAO_ESP32S3 · PSRAM: OPI PSRAM · Partition: Default with spiffs (3MB APP) Library U8g2 by oliver Wiring (GPIO number, XIAO pin name in brackets) Motor driver DRV8833 IN1 -> GPIO1 [D0] IN2 -> GPIO2 [D1] IN3 -> GPIO3 [D2] IN4 -> GPIO4 [D3] OUT1, OUT2 -> both left motors OUT3, OUT4 -> both right motors VCC -> 5V GND -> GND Servo board PCA9685 SDA -> GPIO5 [D4] SCL -> GPIO6 [D5] VCC -> 3V3 GND -> GND V+ terminal -> 5V channel 4 head servo, channel 5 right arm, channel 6 left arm OLED 0.96" SSD1306 I2C SDA, SCL from the PCA9685's second header VCC -> 3V3 GND -> GND RGB LED WS2812B DIN -> GPIO43 [D6] 5V -> 3V3 GND -> GND Touch pad TTP223 I/O -> GPIO44 [D7] VCC -> 3V3 GND -> GND Amp MAX98357A BCLK -> GPIO7 [D8] LRC -> GPIO8 [D9] DIN -> GPIO9 [D10] VIN -> 5V GND -> GND Microphone on the Sense board (PDM, GPIO42 clock, GPIO41 data) Camera on the Sense board's 24-pin socket, long-ribbon OV2640 / OV3660 up in the head Power 4 x AA NiMH (4.8 V) through the battery box switch into the 5V hub Leave the microSD slot empty: it shares D8, D9 and D10 with the amp. Switch the battery off before plugging in USB. Talking over Wi-Fi Hands-free: just speak. The robot starts recording when it hears a voice and sends the turn after about 0.8 s of quiet. It does not listen while it talks, drives, or moves. Hold the touch pad to talk as well, and touch it while the robot talks or drives to stop it. Each turn POSTs [json][jpeg][wav] to /api/bot and reads one JSON event per line back. Bluetooth protocol: Anybody Body Protocol v1, unchanged. Extra commands: drive wheel speeds -100..100, at most 3000 ms, then it stops by itself wifinamepassword join a network and remember it ("wifi name password" also works without spaces in the name) wifi report the Wi-Fi state wifi forget forget the network cam on|off allow or block camera pictures cam flip turn the picture upside down vol 0..100 speaker volume ears auto|touch hands-free listening on, or hold-to-talk only ears <50..5000> voice level that starts a recording (lower hears quieter voices) ears report the mode, the start level, and the room's noise floor Extra events wifi ok wifi fail wifi off heard done drive */ #include #include #include #include #include #include #include #include #include #include #include #include #include "esp_camera.h" #include "roots.h" #define PIN_L1 1 #define PIN_L2 2 #define PIN_R1 3 #define PIN_R2 4 #define PIN_LED 43 #define PIN_TOUCH 44 #define PIN_SDA 5 #define PIN_SCL 6 #define PIN_BCLK 7 #define PIN_LRC 8 #define PIN_DOUT 9 #define PIN_MIC_CLK 42 #define PIN_MIC_DATA 41 #define HEAD_CENTER 90 #define ARM_REST 30 #define PCA_ADDR 0x40 #define CH_HEAD 4 #define CH_ARM 5 #define CH_ARM_L 6 #define DRIVE_MAX 210 #define DRIVE_MAX_MS 3000 #define SERVO_MIN 20 #define SERVO_MAX 160 #define LED_MAX 110 #define MIC_RATE 16000 #define MAX_RECORD_MS 10000 #define MIN_RECORD_MS 400 #define HISTORY_TURNS 4 #define EAR_CHUNK 256 // 16 ms of audio #define EAR_START_CHUNKS 3 // this many loud chunks in a row start a recording #define EAR_PREROLL_MS 300 // audio kept from just before the voice started #define EAR_SILENCE_MS 800 #define EAR_MIN_VOICE_MS 350 #define EAR_REST_MS 700 // after the robot speaks, so the room's echo dies out static const char *SERVER = "https://anybody-brain.pages.dev/api/bot"; static const char *FIRMWARE = "v3.1"; static const char *SERVICE_UUID = "8ebdad55-98c6-4622-93ff-67063ff407ee"; static const char *BODY_UUID = "674ab5d3-427a-4d25-b050-c11e6fe22b45"; static const char *CMD_UUID = "f4bd48ac-536d-4e13-8a00-ab6933a7a63a"; static const char *EVT_UUID = "069c1557-e669-4a98-b6e4-f20487ae3817"; // The body file. The brain reads it each turn and can only use what is listed. static const char BODY_FILE[] = "{\"v\":1,\"name\":\"rover\",\"kind\":\"rover\"," "\"faces\":[\"neutral\",\"happy\",\"sad\",\"surprised\",\"sleepy\",\"love\",\"think\"]," "\"actions\":[" "{\"id\":\"shake\",\"say\":\"shake head for no\"}," "{\"id\":\"look_left\",\"say\":\"turn head left and back\"}," "{\"id\":\"look_right\",\"say\":\"turn head right and back\"}," "{\"id\":\"wave\",\"say\":\"wave the right arm for hello or bye\"}," "{\"id\":\"wave_left\",\"say\":\"wave the left arm\"}," "{\"id\":\"cheer\",\"say\":\"both arms up for yay\"}," "{\"id\":\"dance\",\"say\":\"a short happy dance on the spot\"}," "{\"id\":\"forward\",\"say\":\"roll forward about 20 cm\"}," "{\"id\":\"back\",\"say\":\"roll back about 20 cm\"}," "{\"id\":\"turn_left\",\"say\":\"turn left about a quarter\"}," "{\"id\":\"turn_right\",\"say\":\"turn right about a quarter\"}," "{\"id\":\"spin\",\"say\":\"spin round once\"}" "]," "\"light\":true,\"inputs\":[\"touch\",\"microphone\",\"camera\"],\"limits\":{\"servo_deg\":[20,160],\"drive_ms\":3000}}"; // ---------- display ---------- U8G2_SSD1306_128X64_NONAME_F_HW_I2C oled(U8G2_R0, U8X8_PIN_NONE, PIN_SCL, PIN_SDA); bool oledOk = false; enum Face { F_NEUTRAL, F_HAPPY, F_SAD, F_SURPRISED, F_SLEEPY, F_LOVE, F_THINK }; enum Mode { M_WAIT, M_IDLE, M_LISTEN, M_THINK, M_TALK }; static const char *FACE_NAMES[] = {"neutral", "happy", "sad", "surprised", "sleepy", "love", "think"}; static const int FACE_COUNT = sizeof(FACE_NAMES) / sizeof(FACE_NAMES[0]); Face face = F_NEUTRAL; Mode mode = M_WAIT; uint32_t blinkAt = 3000; uint32_t blinkUntil = 0; uint32_t surpriseUntil = 0; char deviceName[20]; char statusLine[24] = ""; // ---------- servos, on the PCA9685 ---------- bool pcaOk = false; struct Joint { uint8_t channel; float pos; float target; uint32_t movedAt; bool driving; }; Joint head = {CH_HEAD, HEAD_CENTER, HEAD_CENTER, 0, false}; Joint arm = {CH_ARM, ARM_REST, ARM_REST, 0, false}; Joint armL = {CH_ARM_L, 180 - ARM_REST, 180 - ARM_REST, 0, false}; // mirrored: the same move turns the other way void pcaReg(uint8_t reg, uint8_t value) { Wire.beginTransmission(PCA_ADDR); Wire.write(reg); Wire.write(value); Wire.endTransmission(); } void pcaBegin() { Wire.beginTransmission(PCA_ADDR); pcaOk = Wire.endTransmission() == 0; if (!pcaOk) return; pcaReg(0x00, 0x10); // MODE1: sleep, so the prescaler can be set pcaReg(0xFE, 121); // 25 MHz / (4096 × 122) = 50 Hz pcaReg(0x00, 0x20); // awake, register auto-increment delay(1); pcaReg(0x01, 0x04); // MODE2: push-pull outputs } void pcaOff(uint8_t channel, uint16_t off) { if (!pcaOk) return; Wire.beginTransmission(PCA_ADDR); Wire.write(0x06 + 4 * channel); Wire.write(0); Wire.write(0); Wire.write(off & 0xFF); Wire.write(off >> 8); Wire.endTransmission(); } uint16_t ticksFor(float deg) { deg = constrain(deg, (float)SERVO_MIN, (float)SERVO_MAX); float us = 500.0f + deg * (2000.0f / 180.0f); return (uint16_t)(us * 4096.0f / 20000.0f); } void jointBegin(Joint &j) { pcaOff(j.channel, ticksFor(j.pos)); j.movedAt = millis(); j.driving = true; } void jointTick(Joint &j, uint32_t now) { float diff = j.target - j.pos; if (fabsf(diff) > 0.5f) { j.pos += constrain(diff, -4.0f, 4.0f); pcaOff(j.channel, ticksFor(j.pos)); j.movedAt = now; j.driving = true; } else if (j.driving && now - j.movedAt > 600) { pcaOff(j.channel, 0x1000); // full off: the servo relaxes and stops buzzing j.driving = false; } } // ---------- wheels, on the DRV8833 ---------- void send(const String &event); uint32_t driveUntil = 0; bool drivingWheels = false; const char *driveName = nullptr; void sideWrite(uint8_t a, uint8_t b, int speed) { speed = constrain(speed, -DRIVE_MAX, DRIVE_MAX); ledcWrite(a, speed > 0 ? speed : 0); ledcWrite(b, speed < 0 ? -speed : 0); } void wheelsBegin() { uint8_t channel = 2; // channel 0 belongs to the camera clock for (uint8_t pin : {PIN_L1, PIN_L2, PIN_R1, PIN_R2}) ledcAttachChannel(pin, 20000, 8, channel++); sideWrite(PIN_L1, PIN_L2, 0); sideWrite(PIN_R1, PIN_R2, 0); } void drive(int left, int right, uint32_t ms, const char *name = "drive") { ms = min(ms, (uint32_t)DRIVE_MAX_MS); sideWrite(PIN_L1, PIN_L2, left * DRIVE_MAX / 100); sideWrite(PIN_R1, PIN_R2, right * DRIVE_MAX / 100); driveUntil = millis() + ms; drivingWheels = (left || right) && ms; driveName = name; } void stopWheels() { sideWrite(PIN_L1, PIN_L2, 0); sideWrite(PIN_R1, PIN_R2, 0); if (drivingWheels && driveName) send(String("done ") + driveName); drivingWheels = false; } void wheelsTick(uint32_t now) { if (drivingWheels && (int32_t)(now - driveUntil) >= 0) stopWheels(); } // ---------- actions ---------- struct Key { int8_t joint; // 0 head, 1 right arm, 2 left arm (same angles as the right arm), 3 both arms int16_t deg; uint16_t wait; // ms before the next key }; static const Key SHAKE[] = {{0, 60, 200}, {0, 120, 240}, {0, 60, 240}, {0, 120, 240}, {0, HEAD_CENTER, 260}}; static const Key LOOK_LEFT[] = {{0, 40, 900}, {0, HEAD_CENTER, 400}}; static const Key LOOK_RIGHT[] = {{0, 140, 900}, {0, HEAD_CENTER, 400}}; static const Key WAVE[] = {{1, 150, 380}, {1, 110, 220}, {1, 150, 220}, {1, 110, 220}, {1, 150, 220}, {1, ARM_REST, 420}}; static const Key WAVE_LEFT[] = {{2, 150, 380}, {2, 110, 220}, {2, 150, 220}, {2, 110, 220}, {2, 150, 220}, {2, ARM_REST, 420}}; static const Key CHEER[] = {{3, 155, 520}, {0, 70, 0}, {3, 125, 200}, {0, 110, 0}, {3, 155, 260}, {0, HEAD_CENTER, 0}, {3, ARM_REST, 460}}; static const Key DANCE[] = {{0, 65, 0}, {1, 140, 0}, {2, 70, 280}, {0, 115, 0}, {1, 70, 0}, {2, 140, 280}, {0, 65, 0}, {1, 140, 0}, {2, 70, 280}, {0, 115, 0}, {1, 70, 0}, {2, 140, 280}, {0, HEAD_CENTER, 0}, {3, ARM_REST, 420}}; struct Drive { const char *id; int8_t left, right; uint16_t ms; }; static const Drive DRIVES[] = { {"forward", 70, 70, 900}, {"back", -70, -70, 900}, {"turn_left", -65, 65, 420}, {"turn_right", 65, -65, 420}, {"spin", 75, -75, 1500}, }; struct Action { const char *id; const Key *keys; size_t count; }; #define ACTION(name, keys) {name, keys, sizeof(keys) / sizeof(keys[0])} static const Action ACTIONS[] = { ACTION("shake", SHAKE), ACTION("look_left", LOOK_LEFT), ACTION("look_right", LOOK_RIGHT), ACTION("wave", WAVE), ACTION("wave_left", WAVE_LEFT), ACTION("cheer", CHEER), ACTION("dance", DANCE), }; static const int ACTION_COUNT = sizeof(ACTIONS) / sizeof(ACTIONS[0]); const Action *running = nullptr; size_t keyIndex = 0; uint32_t nextKeyAt = 0; // ---------- light ---------- int ledR = 0, ledG = 50, ledB = 140; bool ledCustom = false; uint8_t shownR = 255, shownG = 255, shownB = 255; void ledShow(uint8_t r, uint8_t g, uint8_t b) { if (r == shownR && g == shownG && b == shownB) return; shownR = r; shownG = g; shownB = b; rgbLedWrite(PIN_LED, r, g, b); } // ---------- settings ---------- Preferences prefs; String wifiName, wifiPass; bool camAllowed = true; bool camFlip = false; int volume = 60; // ---------- bluetooth ---------- BLECharacteristic *evtChar = nullptr; volatile bool connected = false; volatile bool dropped = false; volatile bool joined = false; uint32_t lastCommandAt = 0; struct Line { char text[160]; }; QueueHandle_t lines; void queueLine(const char *text) { Line line; strncpy(line.text, text, sizeof(line.text) - 1); line.text[sizeof(line.text) - 1] = 0; xQueueSend(lines, &line, 0); } class ServerEvents : public BLEServerCallbacks { void onConnect(BLEServer *server) override { connected = true; joined = true; } void onDisconnect(BLEServer *server) override { connected = false; dropped = true; } }; class CommandEvents : public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *characteristic) override { String value = String(characteristic->getValue().c_str()); queueLine(value.c_str()); } }; void send(const String &event) { Serial.println(event); if (connected && evtChar) { String out = event.length() > 180 ? event.substring(0, 180) : event; evtChar->setValue((uint8_t *)out.c_str(), out.length()); evtChar->notify(); } } void startBluetooth() { BLEDevice::init(deviceName); BLEDevice::setMTU(247); BLEServer *server = BLEDevice::createServer(); server->setCallbacks(new ServerEvents()); BLEService *service = server->createService(SERVICE_UUID); BLECharacteristic *body = service->createCharacteristic(BODY_UUID, BLECharacteristic::PROPERTY_READ); body->setValue((uint8_t *)BODY_FILE, strlen(BODY_FILE)); BLECharacteristic *command = service->createCharacteristic(CMD_UUID, BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR); command->setCallbacks(new CommandEvents()); evtChar = service->createCharacteristic(EVT_UUID, BLECharacteristic::PROPERTY_NOTIFY); evtChar->addDescriptor(new BLE2902()); service->start(); BLEAdvertising *advertising = BLEDevice::getAdvertising(); advertising->addServiceUUID(SERVICE_UUID); advertising->setScanResponse(true); BLEDevice::startAdvertising(); } // ---------- wi-fi ---------- enum Net { N_OFF, N_JOINING, N_ON, N_FAILED }; Net net = N_OFF; uint32_t joinStartedAt = 0; void joinWifi() { if (!wifiName.length()) { net = N_OFF; return; } WiFi.mode(WIFI_STA); WiFi.setSleep(false); WiFi.begin(wifiName.c_str(), wifiPass.c_str()); net = N_JOINING; joinStartedAt = millis(); strcpy(statusLine, "joining wi-fi"); } void netTick(uint32_t now) { bool up = WiFi.status() == WL_CONNECTED; if (net == N_JOINING && up) { net = N_ON; statusLine[0] = 0; send("wifi ok " + WiFi.localIP().toString()); if (mode == M_WAIT) { mode = M_IDLE; face = F_HAPPY; startAction("wave"); } } else if (net == N_JOINING && now - joinStartedAt > 20000) { net = N_FAILED; strcpy(statusLine, "no wi-fi"); send("wifi fail"); } else if (net == N_ON && !up) { net = N_JOINING; joinStartedAt = now; strcpy(statusLine, "joining wi-fi"); WiFi.reconnect(); } else if (net == N_FAILED && now - joinStartedAt > 60000) { joinWifi(); } } bool online() { return net == N_ON; } // ---------- camera ---------- bool camOk = false; void startCamera() { camera_config_t c = {}; c.ledc_channel = LEDC_CHANNEL_0; c.ledc_timer = LEDC_TIMER_0; c.pin_d0 = 15; c.pin_d1 = 17; c.pin_d2 = 18; c.pin_d3 = 16; c.pin_d4 = 14; c.pin_d5 = 12; c.pin_d6 = 11; c.pin_d7 = 48; c.pin_xclk = 10; c.pin_pclk = 13; c.pin_vsync = 38; c.pin_href = 47; c.pin_sccb_sda = 40; c.pin_sccb_scl = 39; c.sccb_i2c_port = 1; c.pin_pwdn = -1; c.pin_reset = -1; c.xclk_freq_hz = 10000000; // slower clock: the ribbon up to the head is long c.pixel_format = PIXFORMAT_JPEG; c.frame_size = FRAMESIZE_VGA; c.jpeg_quality = 14; c.fb_count = 2; c.fb_location = CAMERA_FB_IN_PSRAM; c.grab_mode = CAMERA_GRAB_LATEST; camOk = psramFound() && esp_camera_init(&c) == ESP_OK; if (camOk) { sensor_t *s = esp_camera_sensor_get(); s->set_vflip(s, camFlip); s->set_hmirror(s, camFlip); } } // ---------- sound ---------- I2SClass mic(I2S_NUM_0); I2SClass speaker(I2S_NUM_1); uint32_t speakerRate = 24000; bool micOk = false, speakerOk = false; uint8_t *recording = nullptr; // WAV: 44-byte header + PCM size_t recordBytes = 0; const size_t RECORD_MAX = 44 + MIC_RATE * 2 * MAX_RECORD_MS / 1000; bool earsAuto = true; int earMin = 400; float noiseFloor = 120; void startSound() { mic.setPinsPdmRx(PIN_MIC_CLK, PIN_MIC_DATA); micOk = mic.begin(I2S_MODE_PDM_RX, MIC_RATE, I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO); speaker.setPins(PIN_BCLK, PIN_LRC, PIN_DOUT); speakerOk = speaker.begin(I2S_MODE_STD, speakerRate, I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO); if (psramFound()) recording = (uint8_t *)ps_malloc(RECORD_MAX); } void put32(uint8_t *p, uint32_t v) { p[0] = v; p[1] = v >> 8; p[2] = v >> 16; p[3] = v >> 24; } void wavHeader(uint8_t *h, uint32_t pcmBytes) { memcpy(h, "RIFF", 4); put32(h + 4, 36 + pcmBytes); memcpy(h + 8, "WAVEfmt ", 8); put32(h + 16, 16); h[20] = 1; h[21] = 0; // PCM h[22] = 1; h[23] = 0; // mono put32(h + 24, MIC_RATE); put32(h + 28, MIC_RATE * 2); h[32] = 2; h[33] = 0; h[34] = 16; h[35] = 0; memcpy(h + 36, "data", 4); put32(h + 40, pcmBytes); } // ---------- commands ---------- int faceIndex(const String &name) { for (int i = 0; i < FACE_COUNT; i++) if (name == FACE_NAMES[i]) return i; return -1; } bool startAction(const String &id) { for (const Drive &d : DRIVES) { if (id == d.id) { drive(d.left, d.right, d.ms, d.id); return true; } } for (int i = 0; i < ACTION_COUNT; i++) { if (id == ACTIONS[i].id) { running = &ACTIONS[i]; keyIndex = 0; nextKeyAt = millis(); return true; } } return false; } void restPose() { running = nullptr; head.target = HEAD_CENTER; arm.target = ARM_REST; armL.target = 180 - ARM_REST; stopWheels(); } void setLight(const String &arg) { if (arg == "off") { ledCustom = true; ledR = ledG = ledB = 0; return; } int r = 0, g = 0, b = 0; if (sscanf(arg.c_str(), "%d %d %d", &r, &g, &b) != 3) return; ledR = constrain(r, 0, 255) * LED_MAX / 255; ledG = constrain(g, 0, 255) * LED_MAX / 255; ledB = constrain(b, 0, 255) * LED_MAX / 255; ledCustom = true; } void wifiCommand(String raw) { String rest = raw.substring(4); if (rest.startsWith("\t") || rest.startsWith(" ")) rest = rest.substring(1); String low = rest; low.trim(); low.toLowerCase(); if (!low.length()) { if (online()) send("wifi ok " + WiFi.localIP().toString()); else send(net == N_JOINING ? "wifi joining" : wifiName.length() ? "wifi fail" : "wifi off"); return; } if (low == "forget") { prefs.remove("ssid"); prefs.remove("pass"); wifiName = wifiPass = ""; WiFi.disconnect(true); net = N_OFF; statusLine[0] = 0; send("wifi off"); return; } int cut = rest.indexOf('\t'); if (cut < 0) cut = rest.indexOf(' '); wifiName = cut < 0 ? rest : rest.substring(0, cut); wifiPass = cut < 0 ? String("") : rest.substring(cut + 1); wifiPass.trim(); prefs.putString("ssid", wifiName); prefs.putString("pass", wifiPass); WiFi.disconnect(); send("ok wifi " + wifiName); joinWifi(); } void handle(String line) { line.trim(); if (!line.length()) return; if (line.startsWith("wifi") && (line.length() == 4 || line[4] == ' ' || line[4] == '\t')) return wifiCommand(line); line.toLowerCase(); int space = line.indexOf(' '); String verb = space < 0 ? line : line.substring(0, space); String arg = space < 0 ? String("") : line.substring(space + 1); arg.trim(); lastCommandAt = millis(); if (verb == "face") { int index = faceIndex(arg); if (index < 0) return send("err face " + arg); face = (Face)index; if (mode == M_WAIT) mode = M_IDLE; send("ok face " + arg); } else if (verb == "do") { if (!startAction(arg)) return send("err do " + arg); send("ok do " + arg); } else if (verb == "state") { if (arg == "idle") mode = M_IDLE; else if (arg == "listen") mode = M_LISTEN; else if (arg == "think") mode = M_THINK; else if (arg == "talk") mode = M_TALK; else return send("err state " + arg); send("ok state " + arg); } else if (verb == "led") { int r, g, b; if (arg != "off" && sscanf(arg.c_str(), "%d %d %d", &r, &g, &b) != 3) return send("err led " + arg); setLight(arg); send(arg == "off" ? "ok led off" : "ok led"); } else if (verb == "stop") { restPose(); mode = M_IDLE; face = F_NEUTRAL; send("ok stop"); } else if (verb == "hello") { send(String("hello ") + deviceName + " " + FIRMWARE); } else if (verb == "body") { Serial.println(BODY_FILE); } else if (verb == "cam") { if (arg == "on" || arg == "off") { camAllowed = arg == "on"; prefs.putBool("cam", camAllowed); } else if (arg == "flip") { camFlip = !camFlip; prefs.putBool("flip", camFlip); if (camOk) { sensor_t *s = esp_camera_sensor_get(); s->set_vflip(s, camFlip); s->set_hmirror(s, camFlip); } } else if (arg.length()) { return send("err cam " + arg); } send(String("ok cam ") + (camOk ? (camAllowed ? "on" : "off") : "missing")); } else if (verb == "drive") { int left = 0, right = 0, ms = 0; if (sscanf(arg.c_str(), "%d %d %d", &left, &right, &ms) != 3 || ms < 0) return send("err drive " + arg); drive(constrain(left, -100, 100), constrain(right, -100, 100), ms); send("ok drive"); } else if (verb == "vol") { volume = constrain(arg.toInt(), 0, 100); prefs.putInt("vol", volume); send("ok vol " + String(volume)); } else if (verb == "ears") { if (arg == "auto" || arg == "touch") { earsAuto = arg == "auto"; prefs.putBool("ears", earsAuto); } else if (arg.length() && isDigit(arg[0])) { earMin = constrain(arg.toInt(), 50, 5000); prefs.putInt("earmin", earMin); } else if (arg.length()) { return send("err ears " + arg); } send(String("ok ears ") + (earsAuto ? "auto " : "touch ") + earMin + " floor " + (int)noiseFloor); } else { send("err unknown " + verb); } } // ---------- drawing ---------- void eyeBox(int cx, int cy, int w, int h) { oled.drawRBox(cx - w / 2, cy - h / 2, w, h, min(7, min(w, h) / 2 - 1)); } void drawEyes(Face f, uint32_t now) { const int ly = 26, lx = 40, rx = 88; bool blink = now < blinkUntil && (f == F_NEUTRAL || f == F_HAPPY || f == F_THINK); if (blink) { oled.drawBox(lx - 11, ly, 22, 3); oled.drawBox(rx - 11, ly, 22, 3); return; } switch (f) { case F_HAPPY: for (int r = 9; r <= 12; r++) { oled.drawCircle(lx, ly + 6, r, U8G2_DRAW_UPPER_LEFT | U8G2_DRAW_UPPER_RIGHT); oled.drawCircle(rx, ly + 6, r, U8G2_DRAW_UPPER_LEFT | U8G2_DRAW_UPPER_RIGHT); } break; case F_SAD: eyeBox(lx, ly + 2, 22, 22); eyeBox(rx, ly + 2, 22, 22); oled.setDrawColor(0); oled.drawTriangle(lx - 13, ly - 10, lx + 13, ly - 10, lx - 13, ly + 2); oled.drawTriangle(rx - 13, ly - 10, rx + 13, ly - 10, rx + 13, ly + 2); oled.setDrawColor(1); break; case F_SURPRISED: oled.drawDisc(lx, ly, 13); oled.drawDisc(rx, ly, 13); oled.setDrawColor(0); oled.drawDisc(lx, ly, 9); oled.drawDisc(rx, ly, 9); oled.setDrawColor(1); oled.drawDisc(lx, ly, 4); oled.drawDisc(rx, ly, 4); break; case F_SLEEPY: oled.drawBox(lx - 11, ly + 3, 22, 4); oled.drawBox(rx - 11, ly + 3, 22, 4); break; case F_LOVE: for (int i = 0; i < 2; i++) { int cx = i ? rx : lx; oled.drawDisc(cx - 5, ly - 3, 6); oled.drawDisc(cx + 5, ly - 3, 6); oled.drawTriangle(cx - 11, ly - 1, cx + 11, ly - 1, cx, ly + 12); } break; case F_THINK: eyeBox(lx + 4, ly - 4, 18, 20); eyeBox(rx + 4, ly - 4, 18, 20); break; default: eyeBox(lx, ly, 22, 26); eyeBox(rx, ly, 22, 26); } } void drawMouth(Face f, uint32_t now) { if (mode == M_TALK) { int h = 3 + (int)(9.0f * (0.5f + 0.5f * sinf(now / 70.0f))); oled.drawRBox(56, 52 - h / 2, 16, h, 3); return; } switch (f) { case F_HAPPY: case F_LOVE: oled.drawCircle(64, 44, 9, U8G2_DRAW_LOWER_LEFT | U8G2_DRAW_LOWER_RIGHT); oled.drawCircle(64, 44, 8, U8G2_DRAW_LOWER_LEFT | U8G2_DRAW_LOWER_RIGHT); break; case F_SAD: oled.drawCircle(64, 60, 8, U8G2_DRAW_UPPER_LEFT | U8G2_DRAW_UPPER_RIGHT); break; case F_SURPRISED: oled.drawCircle(64, 52, 5); break; case F_SLEEPY: oled.drawHLine(60, 52, 8); break; default: oled.drawHLine(58, 52, 12); } } void drawFace(uint32_t now) { if (!oledOk) return; oled.clearBuffer(); if (mode == M_WAIT) { drawEyes(now < surpriseUntil ? F_SURPRISED : F_SLEEPY, now); oled.setFont(u8g2_font_6x10_tr); const char *text = statusLine[0] ? statusLine : deviceName; int w = oled.getStrWidth(text); oled.drawStr((128 - w) / 2, 60, text); if ((now / 600) % 2) oled.drawStr(108, 12, "z"); oled.sendBuffer(); return; } Face shown = now < surpriseUntil ? F_SURPRISED : (mode == M_THINK ? F_THINK : face); drawEyes(shown, now); if (mode == M_LISTEN) { for (int i = 0; i < 5; i++) { int h = 4 + (int)(10.0f * (0.5f + 0.5f * sinf(now / 90.0f + i * 1.3f))); oled.drawBox(44 + i * 9, 58 - h, 5, h); } } else if (mode == M_THINK) { int dots = (now / 350) % 4; for (int i = 0; i < dots; i++) oled.drawDisc(54 + i * 10, 54, 2); } else { drawMouth(shown, now); } oled.sendBuffer(); } // ---------- light patterns ---------- void lightTick(uint32_t now) { float wave = 0.5f + 0.5f * sinf(now / 400.0f); if (mode == M_WAIT) { float b = 0.08f + 0.35f * wave; ledShow(LED_MAX * b, LED_MAX * 0.3f * b, 0); } else if (mode == M_LISTEN) { float b = 0.35f + 0.65f * (0.5f + 0.5f * sinf(now / 120.0f)); ledShow(0, LED_MAX * 0.8f * b, LED_MAX * b); } else if (mode == M_THINK) { float b = 0.25f + 0.75f * wave; ledShow(LED_MAX * 0.6f * b, 0, LED_MAX * b); } else if (mode == M_TALK) { float b = 0.55f + 0.45f * (0.5f + 0.5f * sinf(now / 55.0f)); ledShow(LED_MAX * b, LED_MAX * 0.75f * b, LED_MAX * 0.4f * b); } else { ledShow(ledR, ledG, ledB); } } // ---------- body tick: keeps the face, light, and servos alive during long work ---------- void runActions(uint32_t now) { if (running && now >= nextKeyAt) { const Key &key = running->keys[keyIndex]; if (key.joint == 0) head.target = key.deg; if (key.joint == 1 || key.joint == 3) arm.target = key.deg; if (key.joint == 2 || key.joint == 3) armL.target = 180 - key.deg; nextKeyAt = now + key.wait; if (++keyIndex >= running->count) { send(String("done ") + running->id); running = nullptr; } } } void bodyTick() { uint32_t now = millis(); static uint32_t servoAt = 0, lightAt = 0, drawAt = 0; runActions(now); wheelsTick(now); if (now >= blinkAt) { blinkUntil = now + 140; blinkAt = now + 2500 + random(3500); } if (now - servoAt >= 10) { servoAt = now; jointTick(head, now); jointTick(arm, now); jointTick(armL, now); } if (now - lightAt >= 30) { lightAt = now; lightTick(now); } if (now - drawAt >= 45) { drawAt = now; drawFace(now); } } bool touched() { return digitalRead(PIN_TOUCH) == HIGH; } // ---------- one Wi-Fi turn ---------- String history[HISTORY_TURNS * 2]; int historyCount = 0; void remember(const String &role, const String &text) { if (!text.length()) return; if (historyCount == HISTORY_TURNS * 2) { for (int i = 1; i < historyCount; i++) history[i - 1] = history[i]; historyCount--; } history[historyCount++] = role + "\n" + text; } String jsonText(const String &s) { String out = "\""; for (size_t i = 0; i < s.length(); i++) { char c = s[i]; if (c == '"' || c == '\\') { out += '\\'; out += c; } else if (c == '\n') out += "\\n"; else if ((uint8_t)c < 0x20) out += ' '; else out += c; } return out + "\""; } // Value of "key":"..." in one flat JSON line, with \" \\ \n \uXXXX undone. String field(const String &json, const char *key) { String tag = String("\"") + key + "\":\""; int at = json.indexOf(tag); if (at < 0) return ""; at += tag.length(); String out; while (at < (int)json.length() && json[at] != '"') { char c = json[at++]; if (c != '\\' || at >= (int)json.length()) { out += c; continue; } char e = json[at++]; if (e == 'n') out += '\n'; else if (e == 'u' && at + 4 <= (int)json.length()) { uint32_t cp = strtoul(json.substring(at, at + 4).c_str(), nullptr, 16); at += 4; if (cp >= 0xD800 && cp < 0xDC00 && json.substring(at, at + 2) == "\\u") { uint32_t lo = strtoul(json.substring(at + 2, at + 6).c_str(), nullptr, 16); at += 6; cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00); } if (cp < 0x80) out += (char)cp; else if (cp < 0x800) { out += (char)(0xC0 | cp >> 6); out += (char)(0x80 | (cp & 0x3F)); } else if (cp < 0x10000) { out += (char)(0xE0 | cp >> 12); out += (char)(0x80 | ((cp >> 6) & 0x3F)); out += (char)(0x80 | (cp & 0x3F)); } else { out += (char)(0xF0 | cp >> 18); out += (char)(0x80 | ((cp >> 12) & 0x3F)); out += (char)(0x80 | ((cp >> 6) & 0x3F)); out += (char)(0x80 | (cp & 0x3F)); } } else out += e; } return out; } bool stopTalking = false; bool autoTurn = false; bool readExact(NetworkClient *s, uint8_t *buf, size_t n, uint32_t timeoutMs = 4000) { size_t got = 0; uint32_t last = millis(); while (got < n) { int r = s->read(buf + got, n - got); if (r > 0) { got += r; last = millis(); } else if (!s->connected() && !s->available()) return false; else if (millis() - last > timeoutMs) return false; else { bodyTick(); delay(1); } } return true; } uint32_t le32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; } // Streams a 16-bit WAV from a URL to the speaker. Touching the pad stops it. void playUrl(const String &url) { if (!speakerOk || !url.length()) return; HTTPClient http; NetworkClientSecure tls; NetworkClient plain; http.useHTTP10(true); bool secure = url.startsWith("https://"); if (secure) tls.setCACert(ROOT_CAS); bool began = secure ? http.begin(tls, url) : http.begin(plain, url); if (!began || http.GET() != 200) { send("err audio"); http.end(); return; } NetworkClient *s = http.getStreamPtr(); uint8_t h[12]; if (!readExact(s, h, 12) || memcmp(h, "RIFF", 4) || memcmp(h + 8, "WAVE", 4)) { http.end(); return; } uint32_t rate = 24000; uint16_t channels = 1, bits = 16; for (;;) { uint8_t c[8]; if (!readExact(s, c, 8)) { http.end(); return; } uint32_t size = le32(c + 4); if (!memcmp(c, "fmt ", 4)) { uint8_t f[40]; size_t n = min(size, sizeof(f)); if (!readExact(s, f, n)) { http.end(); return; } for (size_t skip = size - n; skip; skip--) s->read(); channels = f[2] | f[3] << 8; rate = le32(f + 4); bits = f[14] | f[15] << 8; } else if (!memcmp(c, "data", 4)) { break; } else { uint8_t junk[64]; for (uint32_t left = size + (size & 1); left;) { size_t n = min(left, sizeof(junk)); if (!readExact(s, junk, n)) { http.end(); return; } left -= n; } } } if (bits != 16) { http.end(); return; } if (rate != speakerRate) { speaker.configureTX(rate, I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO); speakerRate = rate; } static int16_t buf[512]; bool wasTouched = touched(); uint32_t last = millis(); while (!stopTalking) { int r = s->read((uint8_t *)buf, sizeof(buf)); if (r <= 0) { if (!s->connected() && !s->available()) break; if (millis() - last > 4000) break; bodyTick(); delay(1); continue; } last = millis(); int samples = r / 2; int out = 0; for (int i = 0; i < samples; i += channels) buf[out++] = (int32_t)buf[i] * volume / 100; speaker.write((uint8_t *)buf, out * 2); bodyTick(); bool now = touched(); if (now && !wasTouched) stopTalking = true; wasTouched = now; } http.end(); } void handleEvent(const String &json) { String t = field(json, "t"); if (t == "heard") { String text = field(json, "text"); if (!text.length()) { if (!autoTurn) face = F_SAD; // a hands-free turn with no words was just room noise mode = M_IDLE; return; } send("heard " + text); remember("user", text); } else if (t == "act") { String kind = field(json, "kind"), value = field(json, "value"); if (kind == "face") { int i = faceIndex(value); if (i >= 0) face = (Face)i; } else if (kind == "do") { startAction(value); } else if (kind == "led") { setLight(value); } } else if (t == "say") { String text = field(json, "text"); remember("assistant", text); if (stopTalking) return; mode = M_TALK; playUrl(field(json, "audio")); mode = M_THINK; } else if (t == "error") { send("err server " + field(json, "message")); } } void talkTurn(size_t pcmBytes) { mode = M_THINK; stopTalking = false; bodyTick(); camera_fb_t *frame = nullptr; if (camOk && camAllowed) { camera_fb_t *stale = esp_camera_fb_get(); // the buffer may hold an older picture if (stale) esp_camera_fb_return(stale); frame = esp_camera_fb_get(); } String meta = String("{\"body\":") + BODY_FILE + ",\"lang\":\"auto\",\"history\":["; for (int i = 0; i < historyCount; i++) { int cut = history[i].indexOf('\n'); meta += String(i ? "," : "") + "{\"role\":\"" + history[i].substring(0, cut) + "\",\"content\":" + jsonText(history[i].substring(cut + 1)) + "}"; } meta += "]}"; size_t jpegBytes = frame ? frame->len : 0; size_t wavBytes = 44 + pcmBytes; size_t total = 4 + meta.length() + 4 + jpegBytes + wavBytes; uint8_t *body = (uint8_t *)ps_malloc(total); if (!body) { if (frame) esp_camera_fb_return(frame); send("err memory"); mode = M_IDLE; return; } uint8_t *p = body; put32(p, meta.length()); p += 4; memcpy(p, meta.c_str(), meta.length()); p += meta.length(); put32(p, jpegBytes); p += 4; if (frame) { memcpy(p, frame->buf, jpegBytes); p += jpegBytes; esp_camera_fb_return(frame); } wavHeader(recording, pcmBytes); memcpy(p, recording, wavBytes); NetworkClientSecure tls; tls.setCACert(ROOT_CAS); HTTPClient http; http.useHTTP10(true); http.setTimeout(30000); http.begin(tls, SERVER); http.addHeader("Content-Type", "application/octet-stream"); http.addHeader("X-Anybody-Body", deviceName); int code = http.POST(body, total); free(body); if (code != 200) { send("err server " + String(code) + " " + (code > 0 ? http.getString().substring(0, 120) : http.errorToString(code))); http.end(); face = F_SAD; mode = M_IDLE; return; } NetworkClient *s = http.getStreamPtr(); String line; uint32_t last = millis(); bool done = false; while (!done) { while (s->available()) { char c = s->read(); if (c == '\n') { if (line.startsWith("{")) { if (line.indexOf("\"t\":\"done\"") >= 0) done = true; else handleEvent(line); } line = ""; last = millis(); } else if (line.length() < 4000) { line += c; } } if (done || (!s->connected() && !s->available()) || millis() - last > 30000) break; bodyTick(); delay(2); } http.end(); mode = M_IDLE; lastCommandAt = millis(); } // ---------- touch ---------- bool touchDown = false; bool longSent = false; uint32_t touchSince = 0; uint32_t touchChangedAt = 0; // Hold to talk: records while the pad is held, then sends the turn. void recordAndTalk() { mode = M_LISTEN; face = F_NEUTRAL; size_t at = 44; static int16_t chunk[256]; uint32_t started = millis(), releasedAt = 0; while (at + sizeof(chunk) <= RECORD_MAX) { size_t n = mic.readBytes((char *)chunk, sizeof(chunk)); for (size_t i = 0; i < n / 2; i++) chunk[i] = constrain((int32_t)chunk[i] * 4, -32768, 32767); memcpy(recording + at, chunk, n); at += n; bodyTick(); if (!touched()) { if (!releasedAt) releasedAt = millis(); if (millis() - releasedAt > 150) break; // a short gap is a shaky finger, not a release } else { releasedAt = 0; } } touchDown = touched(); touchChangedAt = millis(); if (millis() - started < MIN_RECORD_MS) { mode = M_IDLE; return; } talkTurn(at - 44); } void touchTick(uint32_t now) { bool down = touched(); if (down != touchDown && now - touchChangedAt > 30) { touchDown = down; touchChangedAt = now; if (down) { touchSince = now; longSent = false; if (drivingWheels) { stopWheels(); return send("touch"); } send("touch"); if (!connected && online() && micOk && recording) return recordAndTalk(); if (!connected) surpriseUntil = now + 700; } } if (touchDown && !longSent && now - touchSince > 1200) { longSent = true; send("touch_long"); } } // ---------- hands-free ears ---------- const size_t PREROLL_SAMPLES = MIC_RATE * EAR_PREROLL_MS / 1000; int16_t preroll[PREROLL_SAMPLES]; size_t prerollAt = 0; bool prerollFull = false; int16_t earChunk[EAR_CHUNK]; int loudChunks = 0; bool earsWereReady = false; uint32_t earsRestUntil = 0; // Reads one chunk with the same gain as hold-to-talk and returns its loudness: // the mean distance from the chunk's average, so the microphone's DC offset does not count. float hearChunk(size_t &samples) { samples = mic.readBytes((char *)earChunk, sizeof(earChunk)) / 2; if (!samples) return 0; int32_t sum = 0; for (size_t i = 0; i < samples; i++) { earChunk[i] = constrain((int32_t)earChunk[i] * 4, -32768, 32767); sum += earChunk[i]; } int32_t mean = sum / (int32_t)samples; uint32_t level = 0; for (size_t i = 0; i < samples; i++) level += abs(earChunk[i] - mean); return (float)level / samples; } float startLevel() { return max(noiseFloor * 3.0f, (float)earMin); } float stopLevel() { return startLevel() * 0.6f; } void forgetPreroll() { prerollAt = 0; prerollFull = false; loudChunks = 0; } // Records from just before the voice started until the room is quiet again, then sends the turn. void listenAndTalk() { mode = M_LISTEN; face = F_NEUTRAL; size_t at = 44; size_t from = prerollFull ? prerollAt : 0, kept = prerollFull ? PREROLL_SAMPLES : prerollAt; for (size_t i = 0; i < kept; i++) { memcpy(recording + at, &preroll[(from + i) % PREROLL_SAMPLES], 2); at += 2; } forgetPreroll(); uint32_t voicedMs = 0, quietMs = 0; float levelSum = 0; int chunks = 0; bool ended = false; while (at + sizeof(earChunk) <= RECORD_MAX) { size_t samples; float level = hearChunk(samples); memcpy(recording + at, earChunk, samples * 2); at += samples * 2; uint32_t ms = samples * 1000 / MIC_RATE; if (level >= stopLevel()) { voicedMs += ms; quietMs = 0; } else quietMs += ms; levelSum += level; chunks++; bodyTick(); if (quietMs >= EAR_SILENCE_MS || touched()) { ended = true; break; } } touchDown = touched(); touchChangedAt = millis(); if (!ended) { // Ten seconds without a pause is a fan, a TV, or traffic: learn it as the room's noise. noiseFloor = max(noiseFloor, levelSum / max(chunks, 1) / 2.0f); mode = M_IDLE; earsRestUntil = millis() + 300; return; } if (voicedMs < EAR_MIN_VOICE_MS) { mode = M_IDLE; earsRestUntil = millis() + 200; return; } uint32_t trailMs = quietMs > 200 ? quietMs - 200 : 0; at -= min(at - 44, (size_t)(trailMs * MIC_RATE / 1000) * 2); autoTurn = true; talkTurn(at - 44); autoTurn = false; earsRestUntil = millis() + EAR_REST_MS; } void earsTick(uint32_t now) { bool ready = earsAuto && mode == M_IDLE && !connected && online() && micOk && recording && !drivingWheels && !running && !touchDown; if (!ready) { earsWereReady = false; return; } if (!earsWereReady) { earsWereReady = true; earsRestUntil = max(earsRestUntil, now + 300); // drop the audio that piled up while the ears were off forgetPreroll(); } size_t samples; float level = hearChunk(samples); if ((int32_t)(now - earsRestUntil) < 0) return; for (size_t i = 0; i < samples; i++) { preroll[prerollAt] = earChunk[i]; if (++prerollAt == PREROLL_SAMPLES) { prerollAt = 0; prerollFull = true; } } if (level >= startLevel()) { if (++loudChunks >= EAR_START_CHUNKS) listenAndTalk(); return; } loudChunks = 0; noiseFloor += (min(level, noiseFloor * 2.0f) - noiseFloor) * 0.02f; } // ---------- main ---------- void setup() { Serial.begin(115200); pinMode(PIN_TOUCH, INPUT_PULLDOWN); uint64_t mac = ESP.getEfuseMac(); snprintf(deviceName, sizeof(deviceName), "Anybody-%04X", (unsigned)((mac >> 32) & 0xFFFF)); prefs.begin("anybody", false); wifiName = prefs.getString("ssid", ""); wifiPass = prefs.getString("pass", ""); camAllowed = prefs.getBool("cam", true); camFlip = prefs.getBool("flip", false); volume = prefs.getInt("vol", 60); earsAuto = prefs.getBool("ears", true); earMin = prefs.getInt("earmin", 400); Wire.begin(PIN_SDA, PIN_SCL); for (uint8_t address : {0x3C, 0x3D}) { Wire.beginTransmission(address); if (Wire.endTransmission() == 0) { oled.setI2CAddress(address * 2); oledOk = true; break; } } if (oledOk) { oled.begin(); oled.setBusClock(400000); } pcaBegin(); wheelsBegin(); startCamera(); jointBegin(head); jointBegin(arm); jointBegin(armL); ledShow(0, 0, 0); startSound(); lines = xQueueCreate(8, sizeof(Line)); startBluetooth(); joinWifi(); Serial.printf("%s ready (%s). OLED %s, servo board %s, camera %s, microphone %s, speaker %s, PSRAM %s.\n", deviceName, FIRMWARE, oledOk ? "found" : "not found", pcaOk ? "found" : "not found", camOk ? "found" : "not found", micOk ? "on" : "off", speakerOk ? "on" : "off", psramFound() ? "found" : "missing: pick OPI PSRAM"); } void loop() { uint32_t now = millis(); static String serialLine; Line line; while (xQueueReceive(lines, &line, 0) == pdTRUE) handle(String(line.text)); while (Serial.available()) { char c = Serial.read(); if (c == '\n' || c == '\r') { if (serialLine.length()) handle(serialLine); serialLine = ""; } else if (serialLine.length() < 150) { serialLine += c; } } if (joined) { joined = false; mode = M_IDLE; face = F_HAPPY; ledCustom = false; ledR = 0; ledG = 50; ledB = 140; lastCommandAt = now; startAction("wave"); } if (dropped) { dropped = false; restPose(); mode = online() ? M_IDLE : M_WAIT; delay(200); BLEDevice::startAdvertising(); } if (mode != M_WAIT && mode != M_IDLE && now - lastCommandAt > 20000) mode = M_IDLE; netTick(now); bodyTick(); touchTick(now); earsTick(now); delay(1); }