from math import pi, sin, cos

from pygame.font import Font

from esp_hadouken.pgfw.GameChild import GameChild
from esp_hadouken.pgfw.Vector import Vector

class Pedal(GameChild, Vector):

    def __init__(self, parent, index):
        GameChild.__init__(self, parent)
        self.effect = 0
        self.index = index
        self.display_active = self.check_command_line(self.parent.display_flag)
        self.reset()
        self.init_display()
        self.set_coefficients()

    def reset(self):
        Vector.__init__(self)

    def init_display(self):
        if self.display_active:
            self.display_surface = self.get_screen()
            self.coordinates = 0, (self.index + 1) * 20
            self.font = Font(self.parent.parent.font_path, 14)
            self.render()

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

    def set_coefficients(self):
        index = self.index
        cx = sin(pi * index / 4)
        cy = -cos(pi * index / 4)
        if cx < .000000001 and cx > -.0000000001:
            cx = 0
        if cy < .000000001 and cy > -.0000000001:
            cy = 0
        self.cx, self.cy = cx, cy

    def set_slopes(self):
        min_na_dist = self.parent.min_negative_acceleration_distance
        min_na = self.parent.min_negative_acceleration
        max_v = self.parent.parent.max_velocity
        initial_thrust = self.parent.initial_thrust
        peak_distance = self.parent.peak_distance
        peak_acceleration = self.parent.peak_acceleration
        self.tail_slope = (min_na - self.parent.max_negative_acceleration) / \
                          (-min_na_dist + max_v)
        self.rest_slope = (initial_thrust - min_na) / min_na_dist
        self.motion_slope = (peak_acceleration - initial_thrust) / peak_distance
        self.head_slope = -peak_acceleration / (max_v - peak_distance)

    def update(self, active):
        self.update_effect(active)
        self.set()
        self.display()

    def update_effect(self, active):
        if active:
            self.effect += self.parent.attack
        elif not active:
            self.effect -= self.parent.release
        self.constrain()

    def constrain(self):
        effect = self.effect
        if effect < 0 or effect > 1:
            if effect < 0:
                effect = 0
            else:
                effect = 1
            self.effect = effect

    def set(self):
        if self.effect:
            vx, vy = self.parent.parent
            cx, cy = self.cx, self.cy
            self.x = self.get_component(vx, cx)
            self.y = self.get_component(vy, cy)
        else:
            self.x = 0
            self.y = 0

    def get_component(self, velocity, coefficient):
        if coefficient < 0:
            velocity = -velocity
        max_v = self.parent.parent.max_velocity
        if not coefficient or velocity >= max_v:
            return 0
        if velocity <= -max_v:
            magnitude = -self.parent.max_negative_acceleration
        elif velocity <= -self.parent.min_negative_acceleration_distance:
            magnitude = self.tail_thrust(velocity)
        elif velocity <= 0:
            magnitude = self.rest_thrust(velocity)
        elif velocity <= self.parent.peak_distance:
            magnitude = self.motion_thrust(velocity)
        else:
            magnitude = self.head_thrust(velocity)
        return coefficient * self.effect * magnitude

    def are_same_sign(self, left, right):
        return left == 0 or right == 0 or abs(left) / left == abs(right) / right

    def tail_thrust(self, velocity):
        return (self.tail_slope * \
                (velocity + self.parent.min_negative_acceleration_distance)) + \
                self.parent.min_negative_acceleration

    def rest_thrust(self, velocity):
        return (self.rest_slope * velocity) + self.parent.initial_thrust

    def motion_thrust(self, velocity):
        return (self.motion_slope * (velocity - self.parent.peak_distance)) + \
               self.parent.peak_acceleration

    def head_thrust(self, velocity):
        return self.head_slope * (velocity - self.parent.parent.max_velocity)

    def display(self):
        if self.display_active:
            if self.string != str(self):
                self.render()
            self.display_surface.blit(self.text, self.coordinates)

    def __str__(self):
        return "[{0: .2f}, {1: .2f}] {2: .2f}".format(self.x, self.y,
                                                      self.effect)
from pygame import Color

from esp_hadouken.GameChild import *

class GlyphPalette(GameChild, list):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        list.__init__(self, [])
        self.set_interval_properties()
        self.populate()

    def set_interval_properties(self):
        length = self.get_configuration()["scoreboard-palette-length"]
        interval_count = 6
        self.interval_length = length / interval_count
        self.overflow = length % interval_count

    def populate(self):
        brightness = self.get_configuration()["scoreboard-palette-brightness"]
        self.add_interval([255, brightness, brightness], [0, 1, 0])
        self.add_interval([255, 255, brightness], [-1, 0, 0])
        self.add_interval([brightness, 255, brightness], [0, 0, 1])
        self.add_interval([brightness, 255, 255], [0, -1, 0])
        self.add_interval([brightness, brightness, 255], [1, 0, 0])
        self.add_interval([255, brightness, 255], [0, 0, -1])

    def add_interval(self, components, actions):
        for ii, action in enumerate(actions):
            if action == 1:
                components[ii] = 0
            elif action == -1:
                components[ii] = 255
        length = self.interval_length + (self.overflow > 0)
        self.overflow -= 1
        step = 255 / length
        for ii in range(length):
            self.append(Color(*components))
            for ii, action in enumerate(actions):
                if action == 1:
                    components[ii] += step
                elif action == -1:
                    components[ii] -= step
from pygame import Surface, Color, Rect

from esp_hadouken.GameChild import *
from esp_hadouken.Font import *

class Heading(GameChild, Surface):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.init_surface()
        self.set_rect()
        self.add_labels()
        self.render_title()

    def init_surface(self):
        parent = self.parent
        width = parent.get_width() - parent.get_padding()
        Surface.__init__(self, (width, parent.get_heading_height()))
        self.fill(Color(self.get_configuration()["scoreboard-heading-bg"]))

    def set_rect(self):
        rect = self.get_rect()
        offset = self.parent.get_padding() / 2
        rect.topleft = offset, offset
        self.rect = rect

    def add_labels(self):
        labels = []
        margin = self.get_margin()
        for ii in range(5):
            labels.append(Label(self, ii))
        self.labels = labels

    def render_title(self):
        config = self.get_configuration()
        size = config["scoreboard-heading-title-size"]
        text = config["scoreboard-heading-title"]
        color = Color(config["scoreboard-heading-title-color"])
        rend = Font(self, size).render(text, True, color)
        rect = rend.get_rect()
        offset = config["scoreboard-heading-title-offset"]
        rect.centery = self.get_rect().centery + offset
        rect.left = config["scoreboard-heading-title-indent"]
        self.blit(rend, rect)

    def get_margin(self):
        return self.get_configuration()["scoreboard-heading-margin"]

    def update(self):
        for label in self.labels:
            label.update()
        self.draw()

    def draw(self):
        self.parent.blit(self, self.rect)


class Label(GameChild, Surface):

    def __init__(self, parent, index):
        GameChild.__init__(self, parent)
        self.index = index
        self.init_surface()
        self.set_rect()

    def init_surface(self):
        parent = self.parent
        size = parent.get_height() - parent.get_margin()
        Surface.__init__(self, (size, size))
        self.paint()

    def paint(self):
        palette = self.get_palette()
        count = self.get_configuration()["scoreboard-heading-checker-count"]
        size = tuple([self.get_width() / count] * 2)
        for ii in range(count):
            for jj in range(count):
                rect = Rect((ii * size[0], jj * size[0]), size)
                self.fill(Color(palette[(ii + jj) % len(palette)]), rect)

    def get_palette(self):
        index = self.index
        if index == 0:
            level = "octo"
        elif index == 1:
            level = "horse"
        elif index == 2:
            level = "diortem"
        elif index == 3:
            level = "circulor"
        else:
            level = "tooth"
        return self.get_configuration()[level + "-level-palette"]

    def set_rect(self):
        rect = self.get_rect()
        rect.left = self.calculate_indent()
        rect.centery = self.parent.get_rect().centery
        self.rect = rect

    def calculate_indent(self):
        parent = self.parent
        width = parent.get_width()
        columns = parent.parent.get_column_widths()
        offset = (columns[3] * width - self.get_width()) / 2
        return sum(columns[:self.index + 3]) * width + offset

    def update(self):
        self.draw()

    def draw(self):
        self.parent.blit(self, self.rect)
18.97.14.80
18.97.14.80
18.97.14.80
 
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 😇