Documento de requisitos: - Versao simplificada (foco no problema, escopo, "o sistema deve") em documentacao/requisitos - Copia detalhada/tecnica em documentacao/documento_de_requisitos_detalhado - Placeholders preenchidos (entregas, publico-alvo, equipe, indicadores, orcamento, continuidade) - Problematica reescrita (Marcos/Alexandre, LER/DORT, prototipo adaptavel) - Escopo IN/OUT revisado; elevador/teclador opcional com (*) e componente separado - IA: Godot + MuJoCo, Fritzing, Expo + PyTorch + WASM, path planning + depth + VLM; gaussian splats; ES para ESP32 - Referencias numeradas (ODS, NR-17, NBR 9050, LGPD, Resolucao CNE/CES, MuJoCo, Godot, PyTorch, WASM, Expo, gaussian splats, pi0.5, ES) - Lista de materiais sem "(sem modelo 3D)" Outros: - firmware/base_movel, modelos/fritzing, modelos/planta e ferramentas/scripts/planta - design/robomovel_control.papel.html: redesign da tela 03 (cabecalho, metricas, timeline)
274 lines
9.5 KiB
Arduino
274 lines
9.5 KiB
Arduino
// RoboMovel — firmware da base móvel (Arduino UNO + CNC Shield V3 + 4x A4988 + 4x NEMA17, rodas mecanum)
|
|
//
|
|
// Recebe comandos de velocidade da ESP32-CAM frontal (que fala com o app RoboMovelControl por WiFi)
|
|
// e gera os passos dos quatro motores com cinemática de rodas mecanum.
|
|
//
|
|
// Ligações (ESPECIFICACOES.md, seção 4):
|
|
// CNC Shield: X = traseiro-dir (STEP D2, DIR D5) · Y = dianteiro-dir (D3, D6)
|
|
// Z = traseiro-esq (D4, D7) · A = dianteiro-esq (D12, D13, jumpers da shield em D12/D13)
|
|
// EN comum em D8 (LOW = drivers ligados) · micropasso 1/16 por jumpers
|
|
// ESP32-CAM: U0T (IO1) -> A1 (RX do SoftwareSerial) · A0 (TX) -> divisor 1k/2k -> U0R (IO3)
|
|
//
|
|
// Protocolo serial (texto, uma linha por comando terminada em '\n', 19200 baud):
|
|
// V <vx> <vy> <w> velocidade: vx frente (mm/s), vy esquerda (mm/s), w giro anti-horário (graus/s)
|
|
// L <mm/s> limite de velocidade (RN04: 500 em corredor, 200 perto de pessoas/portas/elevador)
|
|
// S para com rampa
|
|
// E parada de emergência: corta os passos e desliga os drivers (RN10/RN11)
|
|
// R religa os drivers após uma parada de emergência
|
|
// ? responde "OK <vx> <vy> <w> <limite> <ligado>"
|
|
// Sem comando V por WATCHDOG_MS o robô para sozinho (WiFi/app caiu). Respostas: "OK ..." ou "ERR ...";
|
|
// o V só responde em caso de erro: o SoftwareSerial desliga as interrupções enquanto transmite, o que
|
|
// atrasaria os passos se cada comando de velocidade tivesse resposta.
|
|
|
|
#include <SoftwareSerial.h>
|
|
#include <math.h>
|
|
|
|
// ---- Geometria (ESPECIFICACOES.md, seção 1 e 3) ------------------------------------------------
|
|
const float WHEEL_RADIUS_MM = 30.0; // roda mecanum Ø60 mm
|
|
const float HALF_WHEELBASE_MM = 370.0 / 2; // entre-eixos 370 mm
|
|
const float HALF_TRACK_MM = 463.0 / 2; // bitola 463 mm
|
|
const float STEPS_PER_REV = 200.0 * 16; // 1,8°/passo, micropasso 1/16
|
|
|
|
// ---- Limites ------------------------------------------------------------------------------------
|
|
const float MAX_SPEED_MM_S = 500.0; // RN04
|
|
const float ACCEL_STEPS_S2 = 6000.0; // rampa por roda (~0,35 m/s²)
|
|
const unsigned long WATCHDOG_MS = 500;
|
|
const unsigned long RAMP_PERIOD_MS = 10;
|
|
const long SERIAL_BAUD = 19200;
|
|
|
|
// ---- Pinos --------------------------------------------------------------------------------------
|
|
const uint8_t PIN_ENABLE = 8;
|
|
const uint8_t PIN_ESP_RX = A1; // ligado no U0T da ESP32-CAM
|
|
const uint8_t PIN_ESP_TX = A0; // vai pelo divisor até o U0R
|
|
|
|
enum Wheel { FL, FR, RL, RR, WHEELS };
|
|
// Ordem FL, FR, RL, RR -> eixos A, Y, Z, X da shield.
|
|
const uint8_t STEP_PIN[WHEELS] = {12, 3, 4, 2};
|
|
const uint8_t DIR_PIN[WHEELS] = {13, 6, 7, 5};
|
|
// Os motores da direita ficam espelhados; troque o sinal aqui se uma roda girar ao contrário.
|
|
const bool INVERT[WHEELS] = {false, true, false, true};
|
|
|
|
SoftwareSerial esp(PIN_ESP_RX, PIN_ESP_TX);
|
|
|
|
// ---- Geração de passos (Timer1, acumulador de fase por roda) -------------------------------------
|
|
// O ISR roda a TICK_HZ. Cada roda soma |velocidade| ao seu acumulador; ao estourar, sobe o STEP
|
|
// (o pulso desce no tick seguinte, 40 us > 1 us exigido pelo A4988). Máximo = TICK_HZ / 2 passos/s.
|
|
const uint32_t TICK_HZ = 25000;
|
|
const uint32_t PHASE_ONE = 0x10000UL; // acumulador de 16 bits de fração
|
|
volatile uint32_t phaseStep[WHEELS]; // incremento por tick (passos/s * PHASE_ONE / TICK_HZ)
|
|
volatile uint32_t phaseAcc[WHEELS];
|
|
volatile uint8_t stepMaskD, stepMaskB; // pinos de STEP a baixar no próximo tick
|
|
|
|
ISR(TIMER1_COMPA_vect) {
|
|
PORTD &= ~stepMaskD;
|
|
PORTB &= ~stepMaskB;
|
|
uint8_t maskD = 0, maskB = 0;
|
|
for (uint8_t i = 0; i < WHEELS; i++) {
|
|
uint32_t acc = phaseAcc[i] + phaseStep[i];
|
|
if (acc >= PHASE_ONE) {
|
|
acc -= PHASE_ONE;
|
|
uint8_t pin = STEP_PIN[i];
|
|
if (pin < 8) maskD |= _BV(pin);
|
|
else maskB |= _BV(pin - 8);
|
|
}
|
|
phaseAcc[i] = acc;
|
|
}
|
|
PORTD |= maskD;
|
|
PORTB |= maskB;
|
|
stepMaskD = maskD;
|
|
stepMaskB = maskB;
|
|
}
|
|
|
|
void setupStepTimer() {
|
|
noInterrupts();
|
|
TCCR1A = 0;
|
|
TCCR1B = _BV(WGM12) | _BV(CS11); // CTC, prescaler 8 -> 2 MHz
|
|
OCR1A = (F_CPU / 8 / TICK_HZ) - 1; // 80 contagens = 25 kHz
|
|
TIMSK1 = _BV(OCIE1A);
|
|
interrupts();
|
|
}
|
|
|
|
// ---- Estado de movimento ----------------------------------------------------------------------
|
|
float cmdVx = 0, cmdVy = 0, cmdW = 0; // comando atual (mm/s, mm/s, graus/s)
|
|
float speedLimit = MAX_SPEED_MM_S;
|
|
float targetSteps[WHEELS]; // passos/s com sinal
|
|
float currentSteps[WHEELS];
|
|
bool driversOn = true;
|
|
unsigned long lastCommandMs = 0;
|
|
unsigned long lastRampMs = 0;
|
|
|
|
void setDrivers(bool on) {
|
|
driversOn = on;
|
|
digitalWrite(PIN_ENABLE, on ? LOW : HIGH);
|
|
}
|
|
|
|
// Cinemática inversa de rodas mecanum (roletes em "X" visto de cima).
|
|
void updateTargets() {
|
|
float vx = cmdVx, vy = cmdVy;
|
|
float linear = sqrt(vx * vx + vy * vy);
|
|
if (linear > speedLimit) {
|
|
vx *= speedLimit / linear;
|
|
vy *= speedLimit / linear;
|
|
}
|
|
float k = HALF_WHEELBASE_MM + HALF_TRACK_MM;
|
|
float wz = cmdW * (float)M_PI / 180.0; // rad/s
|
|
float wheelMmS[WHEELS] = {
|
|
vx - vy - k * wz, // FL
|
|
vx + vy + k * wz, // FR
|
|
vx + vy - k * wz, // RL
|
|
vx - vy + k * wz, // RR
|
|
};
|
|
// Mantém a borda de cada roda dentro do limite, preservando a direção do movimento.
|
|
float peak = 0;
|
|
for (uint8_t i = 0; i < WHEELS; i++) peak = max(peak, fabs(wheelMmS[i]));
|
|
float scale = peak > speedLimit ? speedLimit / peak : 1.0;
|
|
const float stepsPerMm = STEPS_PER_REV / (2 * (float)M_PI * WHEEL_RADIUS_MM);
|
|
for (uint8_t i = 0; i < WHEELS; i++) targetSteps[i] = wheelMmS[i] * scale * stepsPerMm;
|
|
}
|
|
|
|
void stopTargets() {
|
|
cmdVx = cmdVy = cmdW = 0;
|
|
updateTargets();
|
|
}
|
|
|
|
void applySpeeds() {
|
|
for (uint8_t i = 0; i < WHEELS; i++) {
|
|
float s = INVERT[i] ? -currentSteps[i] : currentSteps[i];
|
|
digitalWrite(DIR_PIN[i], s >= 0 ? HIGH : LOW);
|
|
uint32_t inc = (uint32_t)(fabs(s) * PHASE_ONE / TICK_HZ);
|
|
noInterrupts();
|
|
phaseStep[i] = inc;
|
|
interrupts();
|
|
}
|
|
}
|
|
|
|
void ramp(float dt) {
|
|
float maxDelta = ACCEL_STEPS_S2 * dt;
|
|
for (uint8_t i = 0; i < WHEELS; i++) {
|
|
float delta = targetSteps[i] - currentSteps[i];
|
|
if (delta > maxDelta) delta = maxDelta;
|
|
if (delta < -maxDelta) delta = -maxDelta;
|
|
// Nunca inverte o sentido sem passar por zero (o DIR só troca com a roda parada).
|
|
if (currentSteps[i] != 0 && (currentSteps[i] + delta) * currentSteps[i] < 0) {
|
|
currentSteps[i] = 0;
|
|
} else {
|
|
currentSteps[i] += delta;
|
|
}
|
|
}
|
|
applySpeeds();
|
|
}
|
|
|
|
void emergencyStop() {
|
|
cmdVx = cmdVy = cmdW = 0;
|
|
for (uint8_t i = 0; i < WHEELS; i++) {
|
|
targetSteps[i] = currentSteps[i] = 0;
|
|
}
|
|
applySpeeds();
|
|
setDrivers(false);
|
|
}
|
|
|
|
// ---- Protocolo ----------------------------------------------------------------------------------
|
|
struct LineReader {
|
|
char text[48];
|
|
uint8_t length = 0;
|
|
};
|
|
LineReader espLine, usbLine;
|
|
|
|
void reply(const char *text) {
|
|
esp.println(text);
|
|
Serial.println(text);
|
|
}
|
|
|
|
void handleLine(char *text) {
|
|
char *cmd = strtok(text, " \t\r");
|
|
if (cmd == nullptr) return;
|
|
char *a = strtok(nullptr, " \t\r");
|
|
char *b = strtok(nullptr, " \t\r");
|
|
char *c = strtok(nullptr, " \t\r");
|
|
|
|
switch (cmd[0]) {
|
|
case 'V':
|
|
if (!a || !b || !c) { reply("ERR uso: V <vx mm/s> <vy mm/s> <w graus/s>"); return; }
|
|
if (!driversOn) { reply("ERR parada de emergencia ativa; envie R"); return; }
|
|
cmdVx = atof(a); cmdVy = atof(b); cmdW = atof(c);
|
|
updateTargets();
|
|
lastCommandMs = millis();
|
|
break;
|
|
case 'L':
|
|
if (!a) { reply("ERR uso: L <mm/s>"); return; }
|
|
speedLimit = constrain(atof(a), 0, MAX_SPEED_MM_S);
|
|
updateTargets();
|
|
reply("OK");
|
|
break;
|
|
case 'S':
|
|
stopTargets();
|
|
reply("OK");
|
|
break;
|
|
case 'E':
|
|
emergencyStop();
|
|
reply("OK");
|
|
break;
|
|
case 'R':
|
|
setDrivers(true);
|
|
stopTargets();
|
|
reply("OK");
|
|
break;
|
|
case '?': {
|
|
char status[64], fx[8], fy[8], fw[8], fl[8];
|
|
dtostrf(cmdVx, 1, 0, fx); dtostrf(cmdVy, 1, 0, fy); dtostrf(cmdW, 1, 0, fw); dtostrf(speedLimit, 1, 0, fl);
|
|
snprintf(status, sizeof(status), "OK %s %s %s %s %d", fx, fy, fw, fl, driversOn ? 1 : 0);
|
|
reply(status);
|
|
break;
|
|
}
|
|
default:
|
|
reply("ERR comando desconhecido (V, L, S, E, R, ?)");
|
|
}
|
|
}
|
|
|
|
void readSerial(Stream &port, LineReader &reader) {
|
|
while (port.available()) {
|
|
char ch = port.read();
|
|
if (ch == '\n') {
|
|
reader.text[reader.length] = '\0';
|
|
handleLine(reader.text);
|
|
reader.length = 0;
|
|
} else if (reader.length < sizeof(reader.text) - 1) {
|
|
reader.text[reader.length++] = ch;
|
|
} else {
|
|
reader.length = 0; // linha longa demais: descarta
|
|
reply("ERR linha longa demais");
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---- Arduino ------------------------------------------------------------------------------------
|
|
void setup() {
|
|
for (uint8_t i = 0; i < WHEELS; i++) {
|
|
pinMode(STEP_PIN[i], OUTPUT);
|
|
pinMode(DIR_PIN[i], OUTPUT);
|
|
}
|
|
pinMode(PIN_ENABLE, OUTPUT);
|
|
setDrivers(true);
|
|
stopTargets();
|
|
|
|
Serial.begin(115200); // USB, para testes de bancada (mesmo protocolo)
|
|
esp.begin(SERIAL_BAUD);
|
|
setupStepTimer();
|
|
lastRampMs = millis();
|
|
reply("OK RoboMovel base pronta");
|
|
}
|
|
|
|
void loop() {
|
|
readSerial(esp, espLine);
|
|
readSerial(Serial, usbLine);
|
|
|
|
unsigned long now = millis();
|
|
if (now - lastCommandMs > WATCHDOG_MS && (cmdVx != 0 || cmdVy != 0 || cmdW != 0)) {
|
|
stopTargets(); // sem comandos recentes: para com rampa
|
|
}
|
|
if (now - lastRampMs >= RAMP_PERIOD_MS) {
|
|
ramp((now - lastRampMs) / 1000.0);
|
|
lastRampMs = now;
|
|
}
|
|
}
|