Mantenha a ponte desligada.
STBY inicia em nível baixo. Sem credenciais, o robô fica no modo seguro.
O firmware completo exibido diretamente dos arquivos do projeto. Acompanhe o controle, inspecione o analisador de comandos e compile localmente.
STBY inicia em nível baixo. Sem credenciais, o robô fica no modo seguro.
ID do robô, sequência, velocidade, TTL e HMAC precisam ser válidos antes de ativar os motores.
O driver é desabilitado quando o comando expira ou a rede Wi-Fi cai.
python3 -m venv .tools-venv
.tools-venv/bin/pip install platformio==6.2.0
PLATFORMIO_CORE_DIR="$PWD/.pio-core" .tools-venv/bin/pio run -d firmware
npm run test:firmwareO alvo fixado é ESP32-C3-DevKitM-1 com Espressif32 6.12.0 / Arduino 2.0.17. A compilação verifica a família do microcontrolador, não a placa personalizada. Leia a referência eletrônica antes de conectar os fios.
Copiar firmware/include/secrets.example.hpara o arquivo ignorado secrets.h. Defina o Wi-Fi e uma chave de rádio independente de 32 bytes, codificada em 64 caracteres hexadecimais por robô. Escolha ROBOT_ID 0, 1 ou 2 na compilação. Nunca envie o arquivo real ao repositório.
Chaves de sala e de rádio físico são credenciais distintas. O cliente da sala controla a simulação. O rádio físico usa uma ponte supervisionada separadamente, chaves HMAC por robô e prazos em tempo real. A ponte padrão não aciona hardware.
A função do motor converte velocidade solicitada em PWM. Não há encoder, medição de velocidade, PID ou compensação da bateria. A confirmação relata o comando aplicado, não o movimento medido. Use o interruptor externo e desligue os motores para programar; não use GPIO4–7 para JTAG com motores armados.
Inicie com o driver desligado, autentique os pacotes de rádio, aplique comandos às rodas e pare ao expirar ou perder Wi-Fi.
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiUdp.h>
#include <mbedtls/md.h>
#include "protocol.h"
#if __has_include("secrets.h")
#include "secrets.h"
#else
#include "secrets.example.h"
#endif
// GPIO numbers, not module pad numbers. STBY needs an external 10 kΩ pulldown.
constexpr int PIN_A1 = 0, PIN_A2 = 1, PIN_APWM = 3;
constexpr int PIN_B1 = 4, PIN_B2 = 5, PIN_BPWM = 6, PIN_STBY = 7;
WiFiUDP radio;
uint8_t key[32];
bool configured = false, seen = false, armed = false;
uint32_t lastSequence = 0, lastCommandAt = 0;
uint16_t ttl = 0;
int16_t appliedLeft = 0, appliedRight = 0;
int hexDigit(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
bool loadKey() {
if (strlen(RADIO_KEY_HEX) != 64) return false;
for (int i = 0; i < 32; i++) {
const int a = hexDigit(RADIO_KEY_HEX[2 * i]);
const int b = hexDigit(RADIO_KEY_HEX[2 * i + 1]);
if (a < 0 || b < 0) return false;
key[i] = (a << 4) | b;
}
return true;
}
void stopMotors() {
digitalWrite(PIN_STBY, LOW);
ledcWrite(0, 0);
ledcWrite(1, 0);
appliedLeft = 0;
appliedRight = 0;
armed = false;
}
void motor(int a, int b, int channel, int speed) {
digitalWrite(a, speed > 0 ? HIGH : LOW);
digitalWrite(b, speed < 0 ? HIGH : LOW);
// Open-loop illustration: commanded mm/s is mapped to an 8-bit PWM duty.
// This is not measured velocity control; calibrate a real motor separately.
ledcWrite(channel, abs(speed) * 255 / 600);
}
bool authenticated(const uint8_t* packet) {
uint8_t digest[32];
const auto* info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
if (mbedtls_md_hmac(info, key, 32, packet, 14, digest) != 0) return false;
uint8_t diff = 0;
for (int i = 0; i < 16; i++) diff |= digest[i] ^ packet[14 + i];
return diff == 0;
}
void setup() {
// Disable the bridge before configuring direction, PWM or networking.
pinMode(PIN_STBY, OUTPUT);
digitalWrite(PIN_STBY, LOW);
for (int pin : {PIN_A1, PIN_A2, PIN_B1, PIN_B2}) {
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
}
ledcSetup(0, 20000, 8);
ledcSetup(1, 20000, 8);
ledcAttachPin(PIN_APWM, 0);
ledcAttachPin(PIN_BPWM, 1);
stopMotors();
Serial.begin(115200);
configured = loadKey();
if (!configured) {
Serial.println("Safe mode: configure radio key before operation");
return;
}
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
radio.begin(20011);
}
void loop() {
if (!configured) {
delay(5);
return;
}
if (WiFi.status() != WL_CONNECTED) {
stopMotors();
delay(5);
return;
}
if (armed && uint32_t(millis() - lastCommandAt) >= ttl) stopMotors();
const int size = radio.parsePacket();
if (size) {
uint8_t bytes[31];
const int n = radio.read(bytes, sizeof(bytes));
WheelCommand cmd;
// Only a valid, authenticated and newer packet refreshes the deadline.
if (size == 30 && decodeCommand(bytes, n, ROBOT_ID, cmd) &&
authenticated(bytes) && (!seen || cmd.sequence > lastSequence)) {
seen = true;
lastSequence = cmd.sequence;
ttl = cmd.ttl;
lastCommandAt = millis();
motor(PIN_A1, PIN_A2, 0, cmd.left);
motor(PIN_B1, PIN_B2, 1, cmd.right);
digitalWrite(PIN_STBY, HIGH);
armed = true;
appliedLeft = cmd.left;
appliedRight = cmd.right;
// This acknowledgement is not authenticated speed/odometry telemetry.
char telemetry[128];
snprintf(telemetry, sizeof(telemetry),
"{\"version\":1,\"id\":%u,\"sequence\":%lu,\"left\":%d,\"right\":%d}",
ROBOT_ID, (unsigned long)lastSequence, appliedLeft, appliedRight);
radio.beginPacket(radio.remoteIP(), radio.remotePort());
radio.write((const uint8_t*)telemetry, strlen(telemetry));
radio.endPacket();
}
}
delay(1);
}
Confira tamanho, assinatura/versão, identidade do robô, faixa de velocidade e prazo do comando.
#pragma once
#include <cstdint>
#include <cstddef>
struct WheelCommand { uint32_t sequence; int16_t left; int16_t right; uint16_t ttl; };
inline uint16_t read16(const uint8_t* p) { return uint16_t(p[0]) | uint16_t(p[1]) << 8; }
inline bool decodeCommand(const uint8_t* p,size_t n,uint8_t robot,WheelCommand& out) {
if(n!=30 || p[0]!='R' || p[1]!='S' || p[2]!=1 || p[3]!=robot) return false;
const int16_t left=int16_t(read16(p+8)),right=int16_t(read16(p+10));
const uint16_t ttl=read16(p+12);
if(left < -600 || left > 600 || right < -600 || right > 600 || ttl==0 || ttl>250) return false;
out={uint32_t(p[4]) | uint32_t(p[5])<<8 | uint32_t(p[6])<<16 | uint32_t(p[7])<<24,left,right,ttl};
return true;
}
Plataforma ESP32 fixada e alvo ESP32-C3. Defina ROBOT_ID de forma independente para cada robô.
[env:esp32-c3-devkitm-1]
platform = espressif32@6.12.0
board = esp32-c3-devkitm-1
framework = arduino
monitor_speed = 115200
build_flags = -DROBOT_ID=0
A chave de rádio vazia mantém a compilação padrão no modo seguro. O secrets.h real é ignorado e nunca publicado.
#pragma once
#define WIFI_SSID "isolated-team-network"
#define WIFI_PASSWORD "replace-locally"
// Exactly 64 hex characters. Generate independently for each robot.
#define RADIO_KEY_HEX ""