from pygame.key import get_pressed, get_mods
from pygame.font import Font
from pygame.locals import *

from esp_hadouken.pgfw.GameChild import GameChild

class Calibrator(GameChild):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.display_surface = self.get_screen()
        self.font = Font(self.parent.font_path, 10)
        self.delegate = self.get_delegate()
        self.load_configuration()
        self.render()
        self.place()
        self.subscribe(self.respond, KEYDOWN)

    def load_configuration(self):
        config = self.get_configuration("engine")
        self.step = config["calibrator-step"]

    def render(self):
        string = str(self)
        self.text = self.font.render(string, False, (0, 0, 0), (255, 255, 255))
        self.string = string

    def __str__(self):
        engine = self.parent
        accelerator = engine.accelerator
        pattern = "v {0:.2f} a {1:.2f} r {2:.2f} t {3:.2f} pa {4:.2f} " + \
                  "pd {5:.2f} lna {6:.2f} lnd {7:.2f} hna {8:.2f} d {9:.2f}"
        return pattern.format(engine.max_velocity, accelerator.attack,
                              accelerator.release, accelerator.initial_thrust,
                              accelerator.peak_acceleration,
                              accelerator.peak_distance,
                              accelerator.min_negative_acceleration,
                              accelerator.min_negative_acceleration_distance,
                              accelerator.max_negative_acceleration,
                              engine.deceleration)

    def place(self):
        rect = self.text.get_rect()
        rect.bottomleft = self.display_surface.get_rect().bottomleft
        self.rect = rect

    def respond(self, event):
        if self.parent.parent.is_active():
            if get_mods() & KMOD_CTRL and event.key == K_COMMA:
                profile = self.parent.profile
                profile.add(increment_index=True)
                profile.write()

    def update(self):
        self.calibrate()
        self.draw()

    def calibrate(self):
        state = get_pressed()
        step = self.step
        engine = self.parent
        accelerator = engine.accelerator
        if state[K_1]:
            engine.max_velocity += step
        if state[K_q]:
            engine.max_velocity -= step
        if state[K_2]:
            accelerator.attack += step
        if state[K_w]:
            accelerator.attack -= step
        if state[K_3]:
            accelerator.release += step
        if state[K_e]:
            accelerator.release -= step
        if state[K_4]:
            accelerator.initial_thrust += step
        if state[K_r]:
            accelerator.initial_thrust -= step
        if state[K_5]:
            accelerator.peak_acceleration += step
        if state[K_t]:
            accelerator.peak_acceleration -= step
        if state[K_6]:
            accelerator.peak_distance += step
        if state[K_y]:
            accelerator.peak_distance -= step
        if state[K_7]:
            accelerator.min_negative_acceleration += step
        if state[K_u]:
            accelerator.min_negative_acceleration -= step
        if state[K_8]:
            accelerator.min_negative_acceleration_distance += step
        if state[K_i]:
            accelerator.min_negative_acceleration_distance -= step
        if state[K_9]:
            accelerator.max_negative_acceleration += step
        if state[K_o]:
            accelerator.max_negative_acceleration -= step
        if state[K_0]:
            engine.deceleration += step
        if state[K_p]:
            engine.deceleration -= step

    def draw(self):
        if self.string != str(self):
            self.render()
        self.display_surface.blit(self.text, self.rect)
from esp_hadouken.pgfw.GameChild import GameChild

class Profile(GameChild, list):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.delegate = self.get_delegate()
        self.load_configuration()
        self.load()
        self.apply()
        self.subscribe(self.respond)

    def load_configuration(self):
        self.path = self.get_resource("engine", "profile-path")

    def load(self):
        list.__init__(self)
        for line in file(self.path):
            self.add(line.split())
        self.index = 0

    def add(self, values=None, increment_index=False):
        if not values:
            engine = self.parent
            accelerator = engine.accelerator
            values = "NAME-ME", engine.max_velocity, accelerator.attack, \
                     accelerator.release, accelerator.initial_thrust, \
                     accelerator.peak_acceleration, accelerator.peak_distance, \
                     accelerator.min_negative_acceleration, \
                     accelerator.min_negative_acceleration_distance, \
                     accelerator.max_negative_acceleration, \
                     engine.deceleration, 1
        self.append([values[0]] + map(float, values[1:-1]) + \
                    [bool(int(values[-1]))])
        if increment_index:
            self.increment_index()


    def apply(self):
        engine = self.parent
        profile = self[self.index]
        engine.set(profile[1], profile[-2])
        engine.accelerator.set(profile[2:-2])

    def respond(self, event):
        if self.parent.parent.is_active():
            if self.delegate.compare(event, "select"):
                self.rotate()

    def rotate(self):
        self.set_next_active()
        self.apply()

    def set_next_active(self):
        while True:
            self.increment_index()
            if self[self.index][-1]:
                break

    def increment_index(self):
        index = self.index + 1
        if index >= len(self):
            index = 0
        self.index = index

    def write(self):
        stream = file(self.path, "w")
        for profile in self:
            stream.write(" ".join(map(str, profile[:-1]) + \
                                  [str(int(profile[-1]))]) + "\n")
from esp_hadouken.pgfw.GameChild import GameChild
from esp_hadouken.pgfw.Vector import Vector
from esp_hadouken.dot.engine.accelerator.Pedal import Pedal

class Accelerator(GameChild, list):

    N, NE, E, SE, S, SW, W, NW = range(8)

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.input = self.get_input()
        self.load_configuration()
        self.init_list()

    def load_configuration(self):
        config = self.get_configuration("engine")
        self.display_flag = config["accelerator-display-flag"]

    def init_list(self):
        list.__init__(self, [Pedal(self, ii) for ii in range(8)])

    def set(self, values):
        self.attack = values[0]
        self.release = values[1]
        self.initial_thrust = values[2]
        self.peak_acceleration = values[3]
        self.peak_distance = values[4]
        self.min_negative_acceleration = values[5]
        self.min_negative_acceleration_distance = values[6]
        self.max_negative_acceleration = values[7]

    def set_slopes(self):
        self.apply_to_pedals("set_slopes")

    def apply_to_pedals(self, method):
        for pedal in self:
            getattr(pedal, method)()

    def reset(self):
        self.apply_to_pedals("reset")

    def update(self):
        S, E, N, W = self.input.get_axes().values()
        self[self.N].update(N and not W and not E)
        self[self.NE].update(N and E)
        self[self.E].update(E and not N and not S)
        self[self.SE].update(E and S)
        self[self.S].update(S and not E and not W)
        self[self.SW].update(S and W)
        self[self.W].update(W and not S and not N)
        self[self.NW].update(W and N)

    def get_sum(self):
        total = Vector()
        for pedal in self:
            total += pedal
        return total
3.145.161.199
3.145.161.199
3.145.161.199
 
January 23, 2021

I wanted to document this chat-controlled robot I made for Babycastles' LOLCAM📸 that accepts a predefined set of commands like a character in an RPG party 〰 commands like walk, spin, bash, drill. It can also understand donut, worm, ring, wheels, and more. The signal for each command is transmitted as a 24-bit value over infrared using two Arduinos, one with an infrared LED, and the other with an infrared receiver. I built the transmitter circuit, and the receiver was built into the board that came with the mBot robot kit. The infrared library IRLib2 was used to transmit and receive the data as a 24-bit value.


fig. 1.1: the LEDs don't have much to do with this post!

I wanted to control the robot the way the infrared remote that came with the mBot controlled it, but the difference would be that since we would be getting input from the computer, it would be like having a remote with an unlimited amount of buttons. The way the remote works is each button press sends a 24-bit value to the robot over infrared. Inspired by Game Boy Advance registers and tracker commands, I started thinking that if we packed multiple parameters into the 24 bits, it would allow a custom move to be sent each time, so I wrote transmitter and receiver code to process commands that looked like this:

bit
name
description
00
time
multiply by 64 to get duration of command in ms
01
02
03
04
left
multiply by 16 to get left motor power
05
06
07
08
right
multiply by 16 to get right motor power
09
10
11
12
left sign
0 = left wheel backward, 1 = left wheel forward
13
right sign
0 = right wheel forward, 1 = right wheel backward
14
robot id
0 = send to player one, 1 = send to player two
15
flip
negate motor signs when repeating command
16
repeats
number of times to repeat command
17
18
19
delay
multiply by 128 to get time between repeats in ms
20
21
22
23
swap
swap the motor power values on repeat
fig 1.2: tightly stuffed bits

The first command I was able to send with this method that seemed interesting was one that made the mBot do a wheelie.

$ ./send_command.py 15 12 15 1 0 0 0 7 0 1
sending 0xff871fcf...


fig 1.3: sick wheels

A side effect of sending the signal this way is any button on any infrared remote will cause the robot to do something. The star command was actually reverse engineered from looking at the code a random remote button sent. For the robot's debut, it ended up with 15 preset commands (that number is in stonks 📈). I posted a highlights video on social media of how the chat controls turned out.

This idea was inspired by a remote frog tank LED project I made for Ribbit's Frog World which had a similar concept: press a button, and in a remote location where 🐸 and 🐠 live, an LED would turn on.


fig 2.1: saying hi to froggo remotely using an LED

😇 The transmitter and receiver Arduino programs are available to be copied and modified 😇