// sweep4: four servos sweep smoothly back and forth, each offset along the cycle.// Servos on GPIO18, 19, 21, 22 (ESP32Servo, 500-2500 us = 0-180 degrees).#include <ESP32Servo.h>#include "MDParams.h"enum { SWEEP_PERIOD_MS, SWEEP_MIN_DEG, SWEEP_MAX_DEG, PHASE_STEP_PCT };MD_PARAMS(4, {"SWEEP_PERIOD_MS", , 500, 20000}, // one full back-and-forth sweep {"SWEEP_MIN_DEG", , 0, 180}, {"SWEEP_MAX_DEG", , 0, 180}, {"PHASE_STEP_PCT", , 0, 100}); // how far along the cycle each next servo isconst int SERVO_PINS[4] = {18, 19, 21, 22};Servo servos[4];int angles[4];void setup() { Serial.begin(115200); for (int i = 0; i < 4; i++) { servos[i].setPeriodHertz(50); // standard 50 Hz servo signal servos[i].attach(SERVO_PINS[i], 500, 2500); } Serial.println("sweep4 ready");}void loop() { static unsigned long lastPrint = 0; unsigned long now = millis(); float lo = PARAM(SWEEP_MIN_DEG), hi = PARAM(SWEEP_MAX_DEG); for (int i = 0; i < 4; i++) { float phase = fmod((float)now / PARAM(SWEEP_PERIOD_MS) + i * PARAM(PHASE_STEP_PCT) / 100.0, 1.0); // cosine ease: slow at both ends, fastest in the middle angles[i] = (int)(lo + (hi - lo) * (1 - cos(2 * PI * phase)) / 2); servos[i].write(angles[i]); } if (now - lastPrint >= 1000) { // report once per second lastPrint = now; Serial.printf("angles: %d %d %d %d\n", angles[0], angles[1], angles[2], angles[3]); } delay(20); // one update per servo frame}
// button: hold the button on GPIO27 to move servo 1; release to move it back.// Servos 2-4 hold one angle. The button pulls GPIO27 to ground when pressed.#include <ESP32Servo.h>#include "MDParams.h"enum { PRESSED_ANGLE, RELEASED_ANGLE, HOLD_ANGLE, DEBOUNCE_MS };MD_PARAMS(4, {"PRESSED_ANGLE", , 0, 180}, // servo 1 while the button is held {"RELEASED_ANGLE", , 0, 180}, // servo 1 otherwise {"HOLD_ANGLE", , 0, 180}, // servos 2-4 {"DEBOUNCE_MS", , 1, 200});const int SERVO_PINS[4] = {18, 19, 21, 22};const int BUTTON_PIN = 27;Servo servos[4];int lastState = -1;void setup() { Serial.begin(115200); pinMode(BUTTON_PIN, INPUT_PULLUP); // idle high, pressed low for (int i = 0; i < 4; i++) { servos[i].setPeriodHertz(50); servos[i].attach(SERVO_PINS[i], 500, 2500); servos[i].write(i == 0 ? PARAM(RELEASED_ANGLE) : PARAM(HOLD_ANGLE)); } Serial.println("button ready");}void loop() { int state = digitalRead(BUTTON_PIN); if (state != lastState) { // act only on a change lastState = state; bool pressed = (state == LOW); int angle = pressed ? PARAM(PRESSED_ANGLE) : PARAM(RELEASED_ANGLE); servos[0].write(angle); Serial.printf("%s: servo 1 -> %d\n", pressed ? "pressed" : "released", angle); } delay(PARAM(DEBOUNCE_MS)); // simple debounce}
// pot: a potentiometer on GPIO34 (ADC1 channel 6) steers all four servos.// analogRead returns 0-4095; each servo maps it to its own range.#include <ESP32Servo.h>#include "MDParams.h"enum { HALF_MIN_DEG, HALF_MAX_DEG, OFFSET_DEG, PRINT_MS };MD_PARAMS(4, {"HALF_MIN_DEG", , 0, 180}, // servo 3 range {"HALF_MAX_DEG", , 0, 180}, {"OFFSET_DEG", , -180, 180}, // servo 4 = servo 1 + offset {"PRINT_MS", , 50, 5000});const int SERVO_PINS[4] = {18, 19, 21, 22};const int POT_PIN = 34;Servo servos[4];void setup() { Serial.begin(115200); analogReadResolution(12); // 0-4095 for (int i = 0; i < 4; i++) { servos[i].setPeriodHertz(50); servos[i].attach(SERVO_PINS[i], 500, 2500); } Serial.println("pot ready");}void loop() { static unsigned long lastPrint = 0; int raw = analogRead(POT_PIN); int a[4]; a[0] = map(raw, 0, 4095, 0, 180); // full range a[1] = map(raw, 0, 4095, 180, 0); // mirrored a[2] = map(raw, 0, 4095, PARAM(HALF_MIN_DEG), PARAM(HALF_MAX_DEG)); a[3] = constrain(a[0] + PARAM(OFFSET_DEG), 0, 180); for (int i = 0; i < 4; i++) servos[i].write(a[i]); if (millis() - lastPrint >= (unsigned long)PARAM(PRINT_MS)) { lastPrint = millis(); Serial.printf("raw=%d angles: %d %d %d %d\n", raw, a[0], a[1], a[2], a[3]); } delay(20);}
// blink: the on-board LED (GPIO2) and an external LED (GPIO4) blink, taking turns or together.#include "MDParams.h"enum { BLINK_MS, TOGETHER };MD_PARAMS(2, {"BLINK_MS", , 50, 5000}, // time each phase lasts {"TOGETHER", , 0, 1}); // 0 = take turns, 1 = blink togetherconst int BOARD_LED = 2; // DevKitC blue LEDconst int EXT_LED = 4; // external LED with a resistorvoid setup() { Serial.begin(115200); pinMode(BOARD_LED, OUTPUT); pinMode(EXT_LED, OUTPUT); Serial.println("blink ready");}void loop() { bool together = PARAM(TOGETHER); digitalWrite(BOARD_LED, HIGH); digitalWrite(EXT_LED, together ? HIGH : LOW); Serial.println("LED on"); delay(PARAM(BLINK_MS)); digitalWrite(BOARD_LED, LOW); digitalWrite(EXT_LED, together ? LOW : HIGH); Serial.println("LED off"); delay(PARAM(BLINK_MS));}
// walk: four servos are the duck's two legs. Press the GPIO27 button to start or stop walking.// GPIO18 left hip, GPIO19 left knee, GPIO21 right hip, GPIO22 right knee.// A short beep on the GPIO25 buzzer marks each toggle; the GPIO2 LED is on while walking.#include <ESP32Servo.h>#include "MDParams.h"enum { STEP_MS, HIP_SWING_DEG, KNEE_LIFT_DEG, BEEP_HZ };MD_PARAMS(4, {"STEP_MS", , 300, 5000}, // one full gait cycle {"HIP_SWING_DEG", , 0, 60}, {"KNEE_LIFT_DEG", , 0, 60}, {"BEEP_HZ", , 100, 8000});const int PINS[4] = {18, 19, 21, 22}; // L hip, L knee, R hip, R kneeconst int BUTTON = 27, BUZZER = 25, LED = 2;Servo legs[4];bool walking = false;int lastButton = HIGH;void stand() { for (int i = 0; i < 4; i++) legs[i].write(90); }void setup() { Serial.begin(115200); pinMode(BUTTON, INPUT_PULLUP); // pressed = LOW pinMode(LED, OUTPUT); for (int i = 0; i < 4; i++) { legs[i].setPeriodHertz(50); legs[i].attach(PINS[i], 500, 2500); } stand(); Serial.println("walk ready: press the button");}void loop() { int b = digitalRead(BUTTON); if (b == LOW && lastButton == HIGH) { // react on the press, not the release walking = !walking; digitalWrite(LED, walking); tone(BUZZER, PARAM(BEEP_HZ), 60); // short beep Serial.println(walking ? "walking" : "stopped"); if (!walking) stand(); } lastButton = b; if (walking) { // gait: hips swing opposite each other, each knee lifts while its hip swings forward float p = (float)(millis() % PARAM(STEP_MS)) / PARAM(STEP_MS) * 2 * PI; float hip = PARAM(HIP_SWING_DEG), knee = PARAM(KNEE_LIFT_DEG); legs[0].write(90 + hip * sinf(p)); // left hip legs[1].write(90 + knee * max(0.0f, cosf(p))); // left knee legs[2].write(90 - hip * sinf(p)); // right hip legs[3].write(90 + knee * max(0.0f, -cosf(p))); // right knee } delay(20);}
// melody: press the GPIO27 button to play the start of "Twinkle Twinkle" on the GPIO25 buzzer.// The GPIO4 LED flashes with every note; the GPIO34 potentiometer sets the speed.#include "MDParams.h"enum { TEMPO_MIN_MS, TEMPO_MAX_MS, NOTE_PCT, TRANSPOSE };MD_PARAMS(4, {"TEMPO_MIN_MS", , 50, 1000}, // beat with the pot at 0 {"TEMPO_MAX_MS", , 50, 2000}, // beat with the pot at 4095 {"NOTE_PCT", , 10, 100}, // how much of each beat the note sounds {"TRANSPOSE", , -12, 12}); // semitones up or downconst int BUTTON = 27, BUZZER = 25, LED = 4, POT = 34;const char *NAMES[] = {"C4", "D4", "E4", "F4", "G4", "A4"};const int FREQS[] = {262, 294, 330, 349, 392, 440};// "Twinkle twinkle little star, how I wonder what you are": note index, beatsconst int SONG[][2] = {{0,1},{0,1},{4,1},{4,1},{5,1},{5,1},{4,2}, {3,1},{3,1},{2,1},{2,1},{1,1},{1,1},{0,2}};const int SONG_LEN = sizeof(SONG) / sizeof(SONG[0]);void setup() { Serial.begin(115200); pinMode(BUTTON, INPUT_PULLUP); // pressed = LOW pinMode(LED, OUTPUT); Serial.println("melody ready: press the button");}void play() { int beatMs = map(analogRead(POT), 0, 4095, PARAM(TEMPO_MIN_MS), PARAM(TEMPO_MAX_MS)); float shift = pow(2.0, PARAM(TRANSPOSE) / 12.0); Serial.printf("playing, beat %d ms\n", beatMs); for (int i = 0; i < SONG_LEN; i++) { int n = SONG[i][0], ms = SONG[i][1] * beatMs; int hz = (int)(FREQS[n] * shift + 0.5); int on = ms * PARAM(NOTE_PCT) / 100, off = ms * (100 - PARAM(NOTE_PCT)) / 100; Serial.printf("%s %d Hz\n", NAMES[n], hz); digitalWrite(LED, HIGH); tone(BUZZER, hz); delay(on); // note noTone(BUZZER); digitalWrite(LED, LOW); delay(off); // gap until the next beat } Serial.println("done");}void loop() { if (digitalRead(BUTTON) == LOW) play(); delay(20);}
// distance: an HC-SR04 measures the distance; the closer the object, the further servo 1 turns.// Closer than ALERT_CM, the buzzer sounds. TRIG GPIO5, ECHO GPIO16, servo GPIO18, buzzer GPIO25.#include <ESP32Servo.h>#include "MDParams.h"enum { ALERT_CM, MEASURE_MS, FAR_CM };MD_PARAMS(3, {"ALERT_CM", , 2, 400}, // buzzer on below this distance {"MEASURE_MS", , 20, 2000}, // time between measurements {"FAR_CM", , 10, 400}); // at this distance or further servo 1 is at 0 degreesconst int TRIG = 5, ECHO = 16, SERVO_PIN = 18, BUZZER = 25;Servo servo;void setup() { Serial.begin(115200); pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); servo.setPeriodHertz(50); servo.attach(SERVO_PIN, 500, 2500); Serial.println("distance ready");}void loop() { digitalWrite(TRIG, LOW); delayMicroseconds(2); digitalWrite(TRIG, HIGH); delayMicroseconds(10); // a 10 us pulse starts a measurement digitalWrite(TRIG, LOW); unsigned long us = pulseIn(ECHO, HIGH, 40000); // echo time; the sensor gives 38 ms for "no echo" float cm = us / 58.0; // sound: 58 us per cm, there and back if (us == 0 || cm > 400) { Serial.printf("echo %lu us: out of range\n", us); servo.write(0); noTone(BUZZER); } else { int far = PARAM(FAR_CM); int angle = map(constrain((int)cm, 2, far), 2, far, 180, 0); // closer = bigger angle servo.write(angle); if (cm < PARAM(ALERT_CM)) tone(BUZZER, 1000); else noTone(BUZZER); Serial.printf("echo %lu us: %.1f cm, servo %d\n", us, cm, angle); } delay(PARAM(MEASURE_MS));}
// oled: a 128x64 SSD1306 OLED (I2C 0x3C, SDA GPIO32, SCL GPIO33) shows a title, the knob reading (GPIO34)// and the four servo angles as bars. The knob also steers the servos on GPIO18, 19, 21, 22.#include <Wire.h>#include <Adafruit_GFX.h>#include <Adafruit_SSD1306.h>#include <ESP32Servo.h>#include "MDParams.h"enum { REFRESH_MS, TITLE_SIZE };MD_PARAMS(2, {"REFRESH_MS", , 20, 1000}, // screen and servo update interval {"TITLE_SIZE", , 1, 2}); // text size of the titleAdafruit_SSD1306 display(128, 64, &Wire, -1);const int SERVO_PINS[4] = {18, 19, 21, 22};const int KNOB = 34;Servo servos[4];void setup() { Serial.begin(115200); Wire.begin(32, 33); // SDA, SCL (GPIO21/22 drive servos here) if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) Serial.println("OLED not found"); for (int i = 0; i < 4; i++) { servos[i].setPeriodHertz(50); servos[i].attach(SERVO_PINS[i], 500, 2500); } Serial.println("oled ready");}void loop() { int raw = analogRead(KNOB); // 0-4095 int a[4] = {map(raw, 0, 4095, 0, 180), map(raw, 0, 4095, 180, 0), 90, map(raw, 0, 4095, 45, 135)}; for (int i = 0; i < 4; i++) servos[i].write(a[i]); display.clearDisplay(); display.setTextColor(SSD1306_WHITE); display.setTextSize(PARAM(TITLE_SIZE)); display.setCursor(0, 0); display.print("Microduck"); display.setTextSize(1); display.setCursor(0, 18); static unsigned long frame = 0; display.printf("knob %4d frame %lu", raw, ++frame); for (int i = 0; i < 4; i++) { // one bar per servo: 0-180 degrees = 0-100 px int y = 30 + i * 9; display.setCursor(0, y); display.printf("S%d", i + 1); display.drawRect(16, y, 102, 7, SSD1306_WHITE); display.fillRect(17, y + 1, a[i] * 100 / 180, 5, SSD1306_WHITE); } display.display(); delay(PARAM(REFRESH_MS));}
// serial: control the servos and the buzzer by typing commands in the serial monitor.// s1 90 servo 1 to 90 degrees (s1..s4)// all 45 every servo to 45 degrees// beep 440 buzzer at 440 Hz for 200 ms// help list the commands// Servos on GPIO18, 19, 21, 22; buzzer on GPIO25.#include <ESP32Servo.h>#include "MDParams.h"enum { ECHO, BEEP_MS };MD_PARAMS(2, {"ECHO", , 0, 1}, // 1 = repeat each command before the answer {"BEEP_MS", , 10, 2000}); // length of a beepconst int SERVO_PINS[4] = {18, 19, 21, 22};const int BUZZER = 25;Servo servos[4];String line;void help() { Serial.println("commands: s1..s4 <0-180>, all <0-180>, beep <hz>, help");}void run(String cmd) { cmd.trim(); if (PARAM(ECHO)) Serial.println("> " + cmd); int space = cmd.indexOf(' '); String word = space < 0 ? cmd : cmd.substring(0, space); int value = space < 0 ? -1 : cmd.substring(space + 1).toInt(); if (word.length() == 2 && word[0] == 's' && word[1] >= '1' && word[1] <= '4' && value >= 0 && value <= 180) { servos[word[1] - '1'].write(value); Serial.printf("ok servo %c = %d\n", word[1], value); } else if (word == "all" && value >= 0 && value <= 180) { for (int i = 0; i < 4; i++) servos[i].write(value); Serial.printf("ok all servos = %d\n", value); } else if (word == "beep" && value >= 20 && value <= 20000) { tone(BUZZER, value, PARAM(BEEP_MS)); Serial.printf("ok beep %d Hz\n", value); } else { if (word != "help") Serial.println("unknown command: " + cmd); help(); }}void setup() { Serial.begin(115200); for (int i = 0; i < 4; i++) { servos[i].setPeriodHertz(50); servos[i].attach(SERVO_PINS[i], 500, 2500); servos[i].write(90); } Serial.println("serial ready"); help();}void loop() { while (Serial.available()) { // collect characters until Enter char c = Serial.read(); if (c == '\n' || c == '\r') { if (line.length()) run(line); line = ""; } else if (line.length() < 64) line += c; } delay(5);}