Files
JackBotEsp32/JackBotEsp/JackBotEsp.ino
T
2026-10-23 21:46:37 +02:00

251 lines
7.4 KiB
Arduino

#include <Adafruit_PWMServoDriver.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7789.h>
#include <SPI.h>
#include <WiFi.h>
#include <WiFiUdp.h> // CHANGED: Added UDP Support
#include <Wire.h>
#include <Emotes.h>
// ============================================================
// Protocol Definitions (MUST MATCH Python config.py)
// ============================================================
#define PACKET_VERSION 1
#define PKT_COMMAND 1
#define PKT_CONFIG 2
#define FT_ARRAY_F32 1
#define FT_STRING 2
#define FT_UINT8 3
#define FT_CONFIG_VAL 4
struct PacketHeader {
uint8_t packet_id;
uint8_t version;
uint16_t payload_len;
uint32_t timestamp;
};
// ============================================================
// Wi-Fi & UDP Setup
// ============================================================
const char *ssid = "PfLANze";
const char *password = "isteinbisschenengandiehals";
const char *ap_ssid = "JackBot-AP";
const char *ap_password = "robot-control";
WiFiUDP udp; // CHANGED: Switched from WiFiServer to WiFiUDP
unsigned int localPort = 3323;
IPAddress local_IP(192, 168, 188, 32);
IPAddress gateway(192, 168, 188, 1);
IPAddress subnet(255, 255, 255, 0);
// ============================================================
// Servo & Motion State
// ============================================================
int servoMin = 125;
int servoMax = 625;
int pythonInterval = 50; // Expected ms between Python frames (20Hz)
// Interpolation variables
float targetLeg[6][3];
float currentLegF[6][3];
float stepSize[6][3];
unsigned long lastInterpolationUpdate = 0;
const int INTERPOLATION_STEP_MS = 5; // 200Hz internal update rate
Adafruit_PWMServoDriver board0 = Adafruit_PWMServoDriver(0x40);
Adafruit_PWMServoDriver board1 = Adafruit_PWMServoDriver(0x41);
// ============================================================
// Display & Buffers
// ============================================================
#define DISPLAY_TEXT_MAX 64
char displayText[DISPLAY_TEXT_MAX] = "";
bool hasDisplayText = false;
#define TFT_CS 5
#define TFT_DC 16
#define TFT_RST 17
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);
JackBot::Emotes face(&tft);
#define MOTION_BUFFER_SIZE 10
struct MotionFrame { int leg[6][3]; };
MotionFrame motionBuffer[MOTION_BUFFER_SIZE];
volatile int motionHead = 0;
volatile int motionTail = 0;
bool pushMotion(int leg[6][3]) {
int next = (motionHead + 1) % MOTION_BUFFER_SIZE;
if (next == motionTail) return false;
memcpy(motionBuffer[motionHead].leg, leg, sizeof(motionBuffer[motionHead].leg));
motionHead = next;
return true;
}
bool popMotion(int leg[6][3]) {
if (motionHead == motionTail) return false;
memcpy(leg, motionBuffer[motionTail].leg, sizeof(motionBuffer[motionTail].leg));
motionTail = (motionTail + 1) % MOTION_BUFFER_SIZE;
return true;
}
// ============================================================
// Servo Control Logic
// ============================================================
int degToPulse(int deg) {
return map(deg, 0, 180, servoMin, servoMax);
}
void writeServos(float leg[6][3]) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 3; j++) {
int pulse = degToPulse((int)leg[i][j]);
if (i < 3) board0.setPWM(i * 3 + j, 0, pulse);
else board1.setPWM((i - 3) * 3 + j, 0, pulse);
}
}
}
void updateMotion() {
// Run this loop every 5ms (INTERPOLATION_STEP_MS)
if (millis() - lastInterpolationUpdate < INTERPOLATION_STEP_MS) return;
lastInterpolationUpdate = millis();
// 1. Check if we reached the target. If yes, try to grab a new frame from buffer.
bool atTarget = true;
for(int i=0; i<6; i++) {
for(int j=0; j<3; j++) {
if (abs(currentLegF[i][j] - targetLeg[i][j]) > 0.5) atTarget = false;
}
}
if (atTarget) {
int nextFrame[6][3];
if (popMotion(nextFrame)) {
for(int i=0; i<6; i++) {
for(int j=0; j<3; j++) {
targetLeg[i][j] = (float)nextFrame[i][j];
// Smooth the transition: Step size = Total Distance / Number of Interpolation Steps
int numSteps = pythonInterval / INTERPOLATION_STEP_MS;
stepSize[i][j] = (targetLeg[i][j] - currentLegF[i][j]) / (float)numSteps;
}
}
}
}
// 2. Incrementally move current position toward target
for(int i=0; i<6; i++) {
for(int j=0; j<3; j++) {
if (abs(currentLegF[i][j] - targetLeg[i][j]) > abs(stepSize[i][j])) {
currentLegF[i][j] += stepSize[i][j];
} else {
currentLegF[i][j] = targetLeg[i][j];
}
}
}
// 3. Update the actual hardware
writeServos(currentLegF);
}
// ============================================================
// TLV Parser (UDP Version)
// ============================================================
void parsePacket(uint8_t *buffer, size_t size) {
if (size < sizeof(PacketHeader)) return;
PacketHeader *header = (PacketHeader *)buffer;
if (header->version != PACKET_VERSION) return;
uint8_t *payload = buffer + sizeof(PacketHeader);
size_t pos = 0;
int tempLeg[6][3];
while (pos < header->payload_len) {
uint8_t f_type = payload[pos++];
uint16_t f_len = payload[pos] | (payload[pos+1] << 8);
pos += 2;
uint8_t *data = payload + pos;
if (header->packet_id == PKT_COMMAND) {
if (f_type == FT_ARRAY_F32 && f_len == 18) {
for (int i=0; i<6; i++) for (int j=0; j<3; j++) tempLeg[i][j] = data[i*3+j];
pushMotion(tempLeg);
} else if (f_type == FT_STRING) {
size_t len = min((size_t)f_len, (size_t)(DISPLAY_TEXT_MAX - 1));
memcpy(displayText, data, len); displayText[len] = '\0';
hasDisplayText = true;
}
} else if (header->packet_id == PKT_CONFIG) {
if (f_type == FT_CONFIG_VAL) {
uint8_t id = data[0]; int16_t val = data[1] | (data[2] << 8);
if (id == 1) servoMin = val;
if (id == 2) servoMax = val;
if (id == 3) pythonInterval = val;
Serial.printf("Config Sync: ID %d -> %d\n", id, val);
}
}
pos += f_len;
}
}
// ============================================================
// Setup & Loop
// ============================================================
void setup() {
Serial.begin(115200);
Wire.begin();
Wire.setClock(400000); // FIX: Overclock I2C to 400kHz for speed
tft.init(240, 320);
// WiFi Connection with Fallback AP
WiFi.mode(WIFI_STA);
WiFi.config(local_IP, gateway, subnet);
WiFi.begin(ssid, password);
unsigned long start = millis();
while (WiFi.status() != WL_CONNECTED && millis() - start < 8000) { delay(200); }
if (WiFi.status() != WL_CONNECTED) {
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(local_IP, local_IP, subnet);
WiFi.softAP(ap_ssid, ap_password);
face.drawCenteredText("AP: JackBot", ST77XX_MAGENTA);
} else {
face.drawCenteredText("WiFi: Connected", ST77XX_CYAN);
}
udp.begin(localPort); // Start UDP Listener
board0.begin(); board0.setPWMFreq(50);
board1.begin(); board1.setPWMFreq(50);
// Set initial pose
for(int i=0; i<6; i++) {
for(int j=0; j<3; j++) {
currentLegF[i][j] = 90.0; targetLeg[i][j] = 90.0;
}
}
}
void loop() {
// 1. Check for incoming UDP packets
int packetSize = udp.parsePacket();
if (packetSize) {
uint8_t packetBuffer[512];
int len = udp.read(packetBuffer, 512);
if (len > 0) parsePacket(packetBuffer, len);
}
// 2. Smoothly update servos
updateMotion();
// 3. Handle Display
if (hasDisplayText) {
face.drawCenteredText(displayText, ST77XX_GREEN);
hasDisplayText = false;
}
}