import pygame

class Animation:

    def __init__(self, frame_duration):
        self.reset_ticks()
        self.updates_this_cycle = 1
        self.overflow = 0
        self.update_count = 1
        self.actual_frame_duration = 0
        self.target_frame_duration = frame_duration
        self.stopping = False

    def reset_ticks(self):
        self.last_ticks = self.get_ticks()

    def play(self):
        while not self.stopping:
            self.advance_frame()
            self.update_frame_duration()
            self.update_overflow()
        self.stopping = False

    def advance_frame(self):
        while self.update_count > 0:
            self.sequence()
            self.update_count -= 1

    def update_frame_duration(self):
        last_ticks = self.last_ticks
        actual_frame_duration = self.get_ticks() - last_ticks
        last_ticks = self.get_ticks()
        wait_duration = self.get_configuration()["display-wait-duration"]
        while actual_frame_duration < self.target_frame_duration:
            pygame.time.wait(wait_duration)
            actual_frame_duration += self.get_ticks() - last_ticks
            last_ticks = self.get_ticks()
        self.actual_frame_duration = actual_frame_duration
        self.last_ticks = last_ticks

    def get_ticks(self):
        return pygame.time.get_ticks()

    def update_overflow(self):
        self.update_count = 1
        target_frame_duration = self.target_frame_duration
        overflow = self.overflow
        overflow += self.actual_frame_duration - target_frame_duration
        while overflow > target_frame_duration:
            self.update_count += 1
            overflow -= target_frame_duration
        overflow = self.overflow

    def stop(self):
        self.stopping = True

    def clear_queue(self):
        self.update_count = 1
from pygame import event
from pygame.locals import *

from GameChild import *

class EventDelegate(GameChild):

    command_event = USEREVENT
    state_change_event = USEREVENT + 1

    def __init__(self, game):
        GameChild.__init__(self, game)
        self.subscribers = dict()
        self.disable()

    def enable(self):
        self.enabled = True

    def disable(self):
        self.enabled = False

    def dispatch_events(self):
        if self.enabled:
            subscribers = self.subscribers
            for evt in event.get():
                kind = evt.type
                if kind in subscribers:
                    for subscriber in subscribers[kind]:
                        subscriber(evt)
        else:
            event.pump()

    def add_subscriber(self, kind, callback):
        subscribers = self.subscribers
        if kind not in subscribers:
            subscribers[kind] = list()
        subscribers[kind].append(callback)

    @classmethod
    def post_event(self, id, **kw):
        event.post(event.Event(id, **kw))
import sys

import pygame
from pygame.locals import *

from GameChild import *
from Animation import *
from Audio import *
from Display import *
from configuration.Configuration import *
from EventDelegate import *
from Input import *
from ScreenGrabber import *
from introduction.Introduction import *
from world.World import *

class Game(GameChild, Animation):
    
    def __init__(self):
        GameChild.__init__(self)
        self.configuration = Configuration()
        Animation.__init__(self, self.configuration["display-frame-duration"])
        pygame.init()
        self.add_children()
        self.subscribe_to_events()
        self.clear_queue()
        self.delegate.enable()
        self.introduction.activate()

    def add_children(self):
        self.audio = Audio(self)
        self.display = Display(self)
        self.delegate = EventDelegate(self)
        self.input = Input(self)
        self.screen_grabber = ScreenGrabber(self)
        self.introduction = Introduction(self)
        self.world = World(self)

    def subscribe_to_events(self):
        self.subscribe_to(QUIT, self.end)
        self.subscribe_to(Input.command_event, self.end)

    def get_configuration(self):
        return self.configuration

    def get_input(self):
        return self.input

    def sequence(self):
        self.delegate.dispatch_events()
        self.world.update()
        pygame.display.update()

    def end(self, evt):
        if evt.type == QUIT or evt.command == "quit":
            sys.exit()
from pygame.mixer import Channel, Sound, music

from GameChild import *

class Audio(GameChild):

    def __init__(self, game):
        GameChild.__init__(self, game)
        self.set_channels()

    def set_channels(self):
        config = self.get_configuration()
        self.bg_channel = Channel(config["audio-bg-channel"])

    def play_bgm(self, path, stream=False):
        if stream:
            self.bg_channel.stop()
            music.load(path)
            music.play(-1)
        else:
            music.stop()
            self.bg_channel.play(Sound(path), -1)
from transistors.GameChild import *
from slides.Slides import *

from transistors.EventDelegate import *

class Introduction(GameChild):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.slides = Slides(self)
        self.subscribe_to_events()

    def subscribe_to_events(self):
        self.subscribe_to(EventDelegate.command_event, self.advance)

    def reset(self):
        self.slides.reset()

    def activate(self):
        self.active = True
        self.set_music()
        self.draw()

    def deactivate(self):
        self.active = False

    def set_music(self):
        self.get_audio().play_bgm(self.get_resource("introduction-music-path"))

    def advance(self, evt):
        if self.active and evt.command == "release":
            if self.slides.advance():
                self.draw()
            else:
                self.deactivate()
                EventDelegate.post_event(EventDelegate.state_change_event,
                                         state="introduction-finished")

    def draw(self):
        self.slides.draw()
216.73.216.2
216.73.216.2
216.73.216.2
 
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 😇