Close

WiFi Servo Slave

A project log for µKatka

Tiny quadruped based on ESP8266

Radomir Dopieralski 12/24/2015 at 13:070 Comments

Mechanically µKatka is more or less complete -- there might be some further improvements in order, but the basic functionality is there. Electrically it's finished too. The last thing that is left is software. Using the Arduino ESP8266 core, I wrote a simple server that listens for commands and sets the servo positions accordingly.

#include <Servo.h>
#include <ESP8266WiFi.h>

WiFiServer server(1337);
WiFiClient client;

const int MAX_SERVO = 8;
const int PINS[MAX_SERVO] = {1, 3, 5, 4, 16, 14, 12, 13};

Servo servos[MAX_SERVO];


void setup() {
    delay(1000);
    WiFi.mode(WIFI_STA);
    WiFi.begin("ssid", "password");
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
    }
    server.begin();
    server.setNoDelay(true);
    for (int i = 0; i < MAX_SERVO; ++i) {
        servos[i].attach(PINS[i]);
        servos[i].writeMicroseconds(1500);
    }
}

void loop() {
    union {
        byte bytes[2];
        uint16_t integer;
    } int2bytes;
    byte servo;

    if (server.hasClient()) {
        if (client) {
            client.stop();
        }
        client = server.available();
    }
    if (client && client.connected()) {
        while (client.available() >= 3) {
            servo = client.read();
            int2bytes.bytes[0] = client.read();
            int2bytes.bytes[1] = client.read();
            if (servo < MAX_SERVO) {
                servos[servo].writeMicroseconds(int2bytes.integer);
            }
            yield();
        }
    }
    delay(20);
}
This lets me run a simple Python program on my computer to move the servos:
import socket
import struct

class Servos(object):
    def __init__(self, addr):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((addr, 1337))
        self.sock.setblocking(False)

    def move(self, servo, position):
        self.sock.sendall(struct.pack("<BH", servo, position))

    def __del__(self):
        self.sock.close()
And the end result of that is:

Of course this is still not a complete, working robot -- the remaining part is a Python script for the PC that would send the correct positions for walking. As I'm traveling until the end of the year, this will have to wait a little bit.

Discussions