Rover
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
/*
Connectivitizer example: a two-motor rover, driven from the phone
An ESP32, a dual H-bridge and two DC motors (tank steering). The rover serves its own control pad
(../../ui/rover.html, compiled in as page.h); the Connectivitizer app shows it and talks to the
rover through its session. Everything is on one port, the service "api":
WebSocket /drive in: {"l":-1..1,"r":-1..1}, about 20 a second while the stick is held
out: telemetry, 5 a second
POST /drive the same command for a browser without the app; answers with telemetry
GET /telemetry {"battery":7.9,"batteryPercent":78,"speed":0.4,"heading":212.5,
"distanceCm":64,"rssi":-58,"armed":true} (distanceCm may be null)
POST /arm {"armed":true|false} -> {"armed":...}
GET /.cz/ui.json, /.cz/ui.html the device UI (docs/device-ui/README.md); GET / is the page too
SAFETY
- Dead-man stop: 300 ms without a drive command and the motors stop (DEADMAN_MS). The check runs
on a timer of its own, every 10 ms, not in loop(): a slow client cannot delay it.
- The motors only move while armed. The rover starts disarmed and POST /arm changes it.
- Stopping is immediate, speeding up is ramped.
Put the rover on a box, wheels in the air, for the first test.
WIRING (ESP32 DevKit, TB6612FNG; an L298N or DRV8833 board works with the same six signals)
GPIO25 -> PWMA GPIO26 -> AIN1 GPIO27 -> AIN2 left motor on A01/A02
GPIO32 -> PWMB GPIO33 -> BIN1 GPIO18 -> BIN2 right motor on B01/B02
GPIO19 -> STBY (drivers without a standby pin: PIN_STANDBY = -1)
3V3 -> VCC, battery + -> VM, GND -> GND (battery, driver and ESP32 share ground)
Battery + --[100k]--+--[33k]-- GND, the middle to GPIO34 (8.4 V becomes 2.08 V; never more than 3.3 V)
HC-SR04 (optional): GPIO16 -> TRIG, ECHO --[1k]--+--[2k]-- GND, the middle to GPIO17 (ECHO is 5 V)
The ESP32 gets its 5 V from a step-down converter on the battery, not from the motor driver's logic pin.
The WebSocket is served by this sketch itself (RFC 6455: the handshake, text frames, ping, close) on a
plain WiFiServer, next to the HTTP requests, so no other library is needed besides Connectivitizer.
Written for the arduino-esp32 core 2.x and 3.x (the LEDC calls differ; see pwmBegin).
*/
// ---------- pins ----------
const int PIN_LEFT_PWM = 25;
const int PIN_LEFT_IN1 = 26;
const int PIN_LEFT_IN2 = 27;
const int PIN_RIGHT_PWM = 32;
const int PIN_RIGHT_IN1 = 33;
const int PIN_RIGHT_IN2 = 18;
const int PIN_STANDBY = 19; // high while armed; -1 when the driver has no standby pin
const int PIN_BATTERY = 34; // ADC1 only: ADC2 does not work while Wi-Fi is on
const int PIN_SONAR_TRIG = 16;
const int PIN_SONAR_ECHO = 17;
// ---------- what you may have to change ----------
const bool LEFT_INVERTED = false; // true when a track runs backwards on "forward"
const bool RIGHT_INVERTED = false;
const float BATTERY_DIVIDER = (100.0f + 33.0f) / 33.0f; // (R1 + R2) / R2
const float BATTERY_EMPTY_V = 6.4f; // 2S Li-ion: 3.2 V a cell
const float BATTERY_FULL_V = 8.4f; // 4.2 V a cell
const float MIN_POWER = 0.18f; // the share of full power at which the motors just start to turn
const float SPIN_DEG_PER_S = 150.0f; // how fast the rover turns on the spot at full power, for the heading estimate
// ---------- safety and timing ----------
const uint32_t DEADMAN_MS = 300; // no drive command for this long: stop
const uint32_t MOTOR_TICK_MS = 10; // how often the motor timer runs
const float RAMP_PER_S = 4.0f; // speeding up: at most this much power more per second (0 to full in 250 ms)
const uint32_t TELEMETRY_MS = 200; // 5 a second on the WebSocket
const uint32_t PWM_HZ = 20000; // above what people hear; an L298N is happier with 1000
const uint8_t PWM_BITS = 8;
const uint32_t PWM_MAX = (1u << PWM_BITS) - 1;
// ---------- the server: HTTP and WebSocket on one port ----------
const int MAX_CONNECTIONS = 6; // what one Connectivitizer session opens at most (CZ_MAX_STREAMS)
const int MAX_SOCKETS = 2; // of which WebSockets
const size_t RX_SIZE = 1536; // the headers of a request, or one WebSocket frame
const uint32_t REQUEST_TIMEOUT_MS = 5000;
struct Connection {
WiFiClient client;
bool used = false;
bool webSocket = false;
uint32_t lastMs = 0;
size_t length = 0;
char rx[RX_SIZE];
};
// ---------- motors ----------
// loop() and the network only write what is wanted; the timer below is the only code that moves a motor.
static portMUX_TYPE driveLock = portMUX_INITIALIZER_UNLOCKED;
static float wantLeft = 0, wantRight = 0; // the last command, -1..1
static uint32_t lastDriveMs = 0; // when it came
static bool haveDrive = false;
static bool armed = false;
static volatile float outLeft = 0, outRight = 0; // what the motors do now
static volatile float headingDeg = 0; // an estimate from the motor powers (there is no compass)
static Ticker motorTicker;
static void pwmBegin(int pin, int channel) {
(void)channel; // core 3 finds a channel itself
ledcAttach(pin, PWM_HZ, PWM_BITS);
}
static void pwmWrite(int pin, int channel, uint32_t duty) {
(void)channel;
ledcWrite(pin, duty);
}
static void pwmBegin(int pin, int channel) {
ledcSetup(channel, PWM_HZ, PWM_BITS);
ledcAttachPin(pin, channel);
}
static void pwmWrite(int pin, int channel, uint32_t duty) {
(void)pin;
ledcWrite(channel, duty);
}
static void setMotor(int pinPwm, int channel, int pinIn1, int pinIn2, bool inverted, float power) {
if (power == 0) {
pwmWrite(pinPwm, channel, 0);
digitalWrite(pinIn1, LOW);
digitalWrite(pinIn2, LOW);
return;
}
bool forward = (power > 0) != inverted;
digitalWrite(pinIn1, forward ? HIGH : LOW);
digitalWrite(pinIn2, forward ? LOW : HIGH);
float share = MIN_POWER + (1.0f - MIN_POWER) * fabsf(power);
pwmWrite(pinPwm, channel, (uint32_t)(share * PWM_MAX + 0.5f));
}
static float ramp(float now, float want) {
if (want == 0) return 0; // stopping is never ramped
if (now != 0 && (want > 0) != (now > 0)) now = 0; // nor is the stop before a reversal
if ((want > 0) == (now > 0) && fabsf(want) <= fabsf(now)) return want; // neither is slowing down
float step = RAMP_PER_S * MOTOR_TICK_MS / 1000.0f;
float change = want - now;
if (change > step) change = step;
if (change < -step) change = -step;
return now + change;
}
// Every MOTOR_TICK_MS, in the timer task. This is where the dead-man rule and the arm switch are enforced.
static void motorTick() {
uint32_t now = millis();
float left = 0, right = 0;
portENTER_CRITICAL(&driveLock);
bool alive = armed && haveDrive && (uint32_t)(now - lastDriveMs) <= DEADMAN_MS;
if (alive) {
left = wantLeft;
right = wantRight;
} else {
haveDrive = false; // an old command never comes back to life, not even when millis() wraps
}
portEXIT_CRITICAL(&driveLock);
float l = ramp(outLeft, left);
float r = ramp(outRight, right);
outLeft = l;
outRight = r;
setMotor(PIN_LEFT_PWM, 0, PIN_LEFT_IN1, PIN_LEFT_IN2, LEFT_INVERTED, l);
setMotor(PIN_RIGHT_PWM, 1, PIN_RIGHT_IN1, PIN_RIGHT_IN2, RIGHT_INVERTED, r);
float heading = headingDeg + (l - r) / 2.0f * SPIN_DEG_PER_S * MOTOR_TICK_MS / 1000.0f;
if (heading >= 360.0f) heading -= 360.0f;
if (heading < 0.0f) heading += 360.0f;
headingDeg = heading;
}
static float clampPower(float value) { return value < -1 ? -1 : value > 1 ? 1 : value; }
static void drive(float left, float right) {
portENTER_CRITICAL(&driveLock);
wantLeft = clampPower(left);
wantRight = clampPower(right);
lastDriveMs = millis();
haveDrive = true;
portEXIT_CRITICAL(&driveLock);
}
static void stopDriving() {
portENTER_CRITICAL(&driveLock);
wantLeft = 0;
wantRight = 0;
haveDrive = false;
portEXIT_CRITICAL(&driveLock);
}
static void setArmed(bool value) {
portENTER_CRITICAL(&driveLock);
armed = value;
wantLeft = 0; // arming never starts with an old command
wantRight = 0;
haveDrive = false;
portEXIT_CRITICAL(&driveLock);
if (PIN_STANDBY >= 0) digitalWrite(PIN_STANDBY, value ? HIGH : LOW);
}
static bool isArmed() {
portENTER_CRITICAL(&driveLock);
bool value = armed;
portEXIT_CRITICAL(&driveLock);
return value;
}
// ---------- battery ----------
static float batteryVolts = 0;
static void readBattery() {
float volts = analogReadMilliVolts(PIN_BATTERY) / 1000.0f * BATTERY_DIVIDER;
batteryVolts = batteryVolts == 0 ? volts : batteryVolts + (volts - batteryVolts) * 0.1f; // the motors make it jump
}
static int batteryPercent() {
float share = (batteryVolts - BATTERY_EMPTY_V) / (BATTERY_FULL_V - BATTERY_EMPTY_V);
return (int)(100.0f * (share < 0 ? 0 : share > 1 ? 1 : share) + 0.5f);
}
// ---------- distance (HC-SR04), without waiting for the echo ----------
static volatile uint32_t echoRiseUs = 0;
static volatile uint32_t echoWidthUs = 0;
static volatile uint32_t echoAtMs = 0;
static void IRAM_ATTR onEcho() {
if (digitalRead(PIN_SONAR_ECHO)) {
echoRiseUs = micros();
} else {
echoWidthUs = micros() - echoRiseUs;
echoAtMs = millis();
}
}
static void pingSonar() {
digitalWrite(PIN_SONAR_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_SONAR_TRIG, LOW);
}
/** Centimetres to whatever is ahead, or -1 when there is no fresh echo within the sensor's 4 m. */
static int distanceCm() {
uint32_t width = echoWidthUs;
if (echoAtMs == 0 || millis() - echoAtMs > 500 || width < 100 || width > 23500) return -1;
return (int)(width / 58);
}
static int distanceCm() { return -1; }
static size_t telemetryJson(char *out, size_t size) {
char distance[12] = "null";
int cm = distanceCm();
if (cm >= 0) snprintf(distance, sizeof distance, "%d", cm);
float speed = (fabsf(outLeft) + fabsf(outRight)) / 2.0f;
int written = snprintf(out, size,
"{\"battery\":%.2f,\"batteryPercent\":%d,\"speed\":%.2f,\"heading\":%.1f,\"distanceCm\":%s,\"rssi\":%d,\"armed\":%s}",
batteryVolts, batteryPercent(), speed, (float)headingDeg, distance, (int)WiFi.RSSI(), isArmed() ? "true" : "false");
return written < 0 ? 0 : (size_t)written < size ? (size_t)written : size - 1;
}
// ---------- the smallest JSON reading that does the job ----------
/** The text after `"key":`, or nullptr. Good for the flat objects this sketch is sent, not for JSON in general. */
static const char *jsonValue(const char *json, const char *key) {
char quoted[16];
snprintf(quoted, sizeof quoted, "\"%s\"", key);
const char *at = strstr(json, quoted);
if (!at) return nullptr;
at += strlen(quoted);
while (*at == ' ' || *at == '\t' || *at == '\r' || *at == '\n') at++;
if (*at != ':') return nullptr;
at++;
while (*at == ' ' || *at == '\t' || *at == '\r' || *at == '\n') at++;
return at;
}
static bool jsonNumber(const char *json, const char *key, float *out) {
const char *at = jsonValue(json, key);
if (!at) return false;
char *end = nullptr;
float value = strtof(at, &end);
if (end == at || !isfinite(value)) return false;
*out = value;
return true;
}
/** A drive command, from the WebSocket or from POST /drive. False when it is not one. */
static bool driveFromJson(const char *json) {
float left, right;
if (!jsonNumber(json, "l", &left) || !jsonNumber(json, "r", &right)) return false;
drive(left, right);
return true;
}
// ---------- HTTP and WebSocket on one port (the constants and Connection are at the top) ----------
static WiFiServer server(80);
static Connection connections[MAX_CONNECTIONS];
static void closeConnection(Connection &c) {
if (c.webSocket) stopDriving(); // whoever was steering is gone
c.client.stop();
c.used = false;
c.webSocket = false;
c.length = 0;
}
static bool sendAll(WiFiClient &client, const char *data, size_t length) {
while (length > 0) {
size_t part = length > 2048 ? 2048 : length;
size_t sent = client.write((const uint8_t *)data, part);
if (sent == 0) return false;
data += sent;
length -= sent;
}
return true;
}
static void respond(Connection &c, int status, const char *reason, const char *type, const char *body, size_t length) {
char head[200];
int n = snprintf(head, sizeof head,
"HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %u\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
status, reason, type, (unsigned)length);
if (sendAll(c.client, head, (size_t)n)) sendAll(c.client, body, length);
closeConnection(c);
}
static void respondText(Connection &c, int status, const char *reason, const char *text) {
respond(c, status, reason, "text/plain; charset=utf-8", text, strlen(text));
}
static void respondJson(Connection &c, const char *json, size_t length) {
respond(c, 200, "OK", "application/json", json, length);
}
/** The value of a header (name in lower case) within rx[0..headEnd), or false. */
static bool header(const char *rx, size_t headEnd, const char *name, char *out, size_t size) {
size_t nameLength = strlen(name);
const char *line = strstr(rx, "\r\n");
while (line && (size_t)(line - rx) < headEnd) {
line += 2;
size_t i = 0;
while (i < nameLength && tolower((unsigned char)line[i]) == name[i]) i++;
if (i == nameLength && line[i] == ':') {
const char *value = line + i + 1;
while (*value == ' ' || *value == '\t') value++;
size_t n = 0;
while (value[n] != '\r' && value[n] != '\0' && n + 1 < size) {
out[n] = value[n];
n++;
}
while (n > 0 && (out[n - 1] == ' ' || out[n - 1] == '\t')) n--;
out[n] = '\0';
return true;
}
line = strstr(line, "\r\n");
}
return false;
}
static bool containsNoCase(const char *text, const char *lowerWord) {
size_t n = strlen(lowerWord);
for (; *text; text++) {
size_t i = 0;
while (i < n && tolower((unsigned char)text[i]) == lowerWord[i]) i++;
if (i == n) return true;
}
return false;
}
/** Sec-WebSocket-Accept for a Sec-WebSocket-Key (RFC 6455, 4.2.2): base64(SHA-1(key + GUID)). */
static bool webSocketAccept(const char *key, char *out, size_t size) {
char joined[128];
int n = snprintf(joined, sizeof joined, "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key);
if (n <= 0 || (size_t)n >= sizeof joined) return false;
unsigned char hash[20];
if (mbedtls_sha1((const unsigned char *)joined, (size_t)n, hash) != 0) return false;
if (mbedtls_sha1_ret((const unsigned char *)joined, (size_t)n, hash) != 0) return false;
size_t written = 0;
if (mbedtls_base64_encode((unsigned char *)out, size - 1, &written, hash, sizeof hash) != 0) return false;
out[written] = '\0';
return true;
}
/** One unfragmented frame from the server (never masked). `length` up to 65535. */
static bool sendFrame(Connection &c, uint8_t opcode, const char *payload, size_t length) {
uint8_t frame[4 + 256];
if (length > 256) return false;
size_t head = 2;
frame[0] = 0x80 | opcode;
if (length < 126) {
frame[1] = (uint8_t)length;
} else {
frame[1] = 126;
frame[2] = (uint8_t)(length >> 8);
frame[3] = (uint8_t)(length & 0xff);
head = 4;
}
memcpy(frame + head, payload, length);
return sendAll(c.client, (const char *)frame, head + length);
}
static void closeWebSocket(Connection &c, uint16_t code) {
char payload[2] = {(char)(code >> 8), (char)(code & 0xff)};
sendFrame(c, 0x8, payload, 2);
closeConnection(c);
}
static void sendTelemetry(Connection &c) {
char json[200];
size_t n = telemetryJson(json, sizeof json);
if (!sendFrame(c, 0x1, json, n)) closeConnection(c);
}
/** Takes the complete frames out of rx. Frames from a client are masked; the messages here are one small text frame each. */
static void readFrames(Connection &c) {
while (c.used) {
if (c.length < 2) return;
uint8_t *rx = (uint8_t *)c.rx;
bool fin = rx[0] & 0x80;
uint8_t opcode = rx[0] & 0x0f;
bool masked = rx[1] & 0x80;
size_t length = rx[1] & 0x7f;
size_t head = 2;
if ((rx[0] & 0x70) || !masked) return closeWebSocket(c, 1002); // protocol error
if (length == 127) return closeWebSocket(c, 1009); // far too big
if (length == 126) {
if (c.length < 4) return;
length = ((size_t)rx[2] << 8) | rx[3];
head = 4;
}
if (opcode >= 0x8 && (length > 125 || !fin)) return closeWebSocket(c, 1002);
head += 4; // the mask
if (head + length > RX_SIZE - 1) return closeWebSocket(c, 1009);
if (c.length < head + length) return; // the rest is still on its way
uint8_t *mask = rx + head - 4;
uint8_t *payload = rx + head;
for (size_t i = 0; i < length; i++) payload[i] ^= mask[i & 3];
if (opcode == 0x1 && fin) {
char text[96];
if (length < sizeof text) {
memcpy(text, payload, length);
text[length] = '\0';
driveFromJson(text); // anything else is ignored
}
} else if (opcode == 0x8) {
sendFrame(c, 0x8, (const char *)payload, length >= 2 ? 2 : 0);
return closeConnection(c);
} else if (opcode == 0x9) {
if (!sendFrame(c, 0xA, (const char *)payload, length)) return closeConnection(c);
} else if (opcode == 0xA) {
// a pong nobody asked for: allowed, ignored
} else {
return closeWebSocket(c, 1003); // binary or fragmented messages: not understood
}
size_t used = head + length;
memmove(c.rx, c.rx + used, c.length - used);
c.length -= used;
}
}
static int openSockets() {
int count = 0;
for (Connection &c : connections) {
if (c.used && c.webSocket) count++;
}
return count;
}
/** A complete request is in rx: headers up to headEnd, then `bodyLength` bytes of body. */
static void handleRequest(Connection &c, size_t headEnd, size_t bodyLength) {
char method[8] = "";
char path[64] = "";
if (sscanf(c.rx, "%7s %63s", method, path) != 2) return respondText(c, 400, "Bad Request", "Not an HTTP request.");
char *query = strchr(path, '?');
if (query) *query = '\0';
bool get = strcmp(method, "GET") == 0;
bool post = strcmp(method, "POST") == 0;
const char *body = c.rx + headEnd;
(void)bodyLength; // rx is terminated behind the body
if (strcmp(path, "/drive") == 0 && get) {
char upgrade[32], key[64], accept[32];
if (!header(c.rx, headEnd, "upgrade", upgrade, sizeof upgrade) || !containsNoCase(upgrade, "websocket") ||
!header(c.rx, headEnd, "sec-websocket-key", key, sizeof key) || !webSocketAccept(key, accept, sizeof accept)) {
return respondText(c, 426, "Upgrade Required", "GET /drive is a WebSocket. Use POST /drive without one.");
}
if (openSockets() >= MAX_SOCKETS) return respondText(c, 503, "Service Unavailable", "Too many WebSockets.");
char head[160];
int n = snprintf(head, sizeof head,
"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\n\r\n", accept);
if (!sendAll(c.client, head, (size_t)n)) return closeConnection(c);
c.webSocket = true;
c.length = 0;
sendTelemetry(c);
return;
}
if (strcmp(path, "/drive") == 0 && post) {
if (!driveFromJson(body)) return respondText(c, 400, "Bad Request", "Expected {\"l\":-1..1,\"r\":-1..1}.");
char json[200];
return respondJson(c, json, telemetryJson(json, sizeof json));
}
if (strcmp(path, "/telemetry") == 0 && get) {
char json[200];
return respondJson(c, json, telemetryJson(json, sizeof json));
}
if (strcmp(path, "/arm") == 0 && post) {
const char *value = jsonValue(body, "armed");
bool on = value && strncmp(value, "true", 4) == 0;
bool off = value && strncmp(value, "false", 5) == 0;
if (!on && !off) return respondText(c, 400, "Bad Request", "Expected {\"armed\":true} or {\"armed\":false}.");
setArmed(on);
return respondJson(c, on ? "{\"armed\":true}" : "{\"armed\":false}", on ? 14 : 15);
}
if (strcmp(path, "/.cz/ui.json") == 0 && get) return respondJson(c, ROVER_MANIFEST, strlen(ROVER_MANIFEST));
if ((strcmp(path, "/.cz/ui.html") == 0 || strcmp(path, "/") == 0) && get) {
return respond(c, 200, "OK", "text/html; charset=utf-8", ROVER_PAGE, ROVER_PAGE_LENGTH);
}
respondText(c, 404, "Not Found", "Not found.");
}
/** Looks whether rx holds a whole request yet. */
static void readRequest(Connection &c) {
c.rx[c.length] = '\0';
const char *end = strstr(c.rx, "\r\n\r\n");
if (!end) {
if (c.length >= RX_SIZE - 1) respondText(c, 431, "Request Header Fields Too Large", "The request headers are too large.");
return;
}
size_t headEnd = (size_t)(end - c.rx) + 4;
char value[16];
size_t bodyLength = header(c.rx, headEnd, "content-length", value, sizeof value) ? (size_t)strtoul(value, nullptr, 10) : 0;
if (headEnd + bodyLength > RX_SIZE - 1) return respondText(c, 413, "Payload Too Large", "The request is too large.");
if (c.length < headEnd + bodyLength) return; // the body is still on its way
handleRequest(c, headEnd, bodyLength);
}
static void serveConnections() {
// New connections. The Connectivitizer library connects here like any client in the network would.
for (;;) {
WiFiClient client = server.accept();
if (!client) break;
Connection *slot = nullptr;
for (Connection &c : connections) {
if (!c.used) {
slot = &c;
break;
}
}
if (!slot) {
client.stop();
break;
}
client.setNoDelay(true); // small frames, sent at once
slot->client = client;
slot->used = true;
slot->webSocket = false;
slot->length = 0;
slot->lastMs = millis();
}
for (Connection &c : connections) {
if (!c.used) continue;
int waiting = c.client.available();
if (waiting > 0 && c.length < RX_SIZE - 1) {
int got = c.client.read((uint8_t *)c.rx + c.length, RX_SIZE - 1 - c.length);
if (got > 0) {
c.length += (size_t)got;
c.lastMs = millis();
if (c.webSocket) readFrames(c);
else readRequest(c);
}
} else if (!c.client.connected()) {
closeConnection(c);
} else if (!c.webSocket && millis() - c.lastMs > REQUEST_TIMEOUT_MS) {
closeConnection(c); // a request that never came
}
}
}
// ---------- setup and loop ----------
void setup() {
// The motors first: everything off before anything else has a chance to fail.
if (PIN_STANDBY >= 0) {
pinMode(PIN_STANDBY, OUTPUT);
digitalWrite(PIN_STANDBY, LOW);
}
pinMode(PIN_LEFT_IN1, OUTPUT);
pinMode(PIN_LEFT_IN2, OUTPUT);
pinMode(PIN_RIGHT_IN1, OUTPUT);
pinMode(PIN_RIGHT_IN2, OUTPUT);
pwmBegin(PIN_LEFT_PWM, 0);
pwmBegin(PIN_RIGHT_PWM, 1);
setMotor(PIN_LEFT_PWM, 0, PIN_LEFT_IN1, PIN_LEFT_IN2, LEFT_INVERTED, 0);
setMotor(PIN_RIGHT_PWM, 1, PIN_RIGHT_IN1, PIN_RIGHT_IN2, RIGHT_INVERTED, 0);
motorTicker.attach_ms(MOTOR_TICK_MS, motorTick);
Serial.begin(115200);
analogSetPinAttenuation(PIN_BATTERY, ADC_11db); // up to about 3.1 V at the pin
pinMode(PIN_SONAR_TRIG, OUTPUT);
digitalWrite(PIN_SONAR_TRIG, LOW);
pinMode(PIN_SONAR_ECHO, INPUT);
attachInterrupt(digitalPinToInterrupt(PIN_SONAR_ECHO), onEcho, CHANGE);
WiFi.mode(WIFI_STA);
WiFi.setSleep(false); // Wi-Fi power saving delays every packet; a rover wants its commands now
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
// An ordinary server on port 80. It knows nothing about Connectivitizer.
server.begin();
Connectivitizer.setLog(Serial);
Connectivitizer.setServer(SERVER_URL);
Connectivitizer.setSharedKey(SHARED_KEY);
Connectivitizer.expose("api", 80); // the server above, under the name "api"
if (!Connectivitizer.begin(DEVICE_KEY, DEVICE_NAME)) {
Serial.println("Connectivitizer: check DEVICE_KEY, DEVICE_NAME and SHARED_KEY");
}
}
void loop() {
serveConnections();
uint32_t now = millis();
static uint32_t telemetryAt = 0;
if (now - telemetryAt >= TELEMETRY_MS) {
telemetryAt = now;
for (Connection &c : connections) {
if (c.used && c.webSocket) sendTelemetry(c);
}
}
static uint32_t sensorsAt = 0;
if (now - sensorsAt >= 100) {
sensorsAt = now;
readBattery();
pingSonar();
}
static bool wasOnline = false;
bool online = WiFi.status() == WL_CONNECTED;
if (online != wasOnline) {
wasOnline = online;
if (online) {
Serial.print("Wi-Fi connected. In a browser: http://");
Serial.println(WiFi.localIP());
} else {
Serial.println("Wi-Fi lost.");
}
}
static bool wasReachable = false;
bool reachable = Connectivitizer.connected();
if (reachable != wasReachable) {
wasReachable = reachable;
Serial.println(reachable ? "Reachable through Connectivitizer." : "Not reachable through Connectivitizer right now.");
}
delay(1);
}