Sohaib Arif — AI Safety Research

Notes on AI safety for local & embedded models

Driving an AMD Kria KR260 Robot over WiFi in a cardboard chassis

Introduction

The AMD Kria KR260 Robotics Starter Kit pairs Arm processor cores with programmable FPGA logic, which makes it an interesting brain for a small robot. This post follows up on Getting Started with AMD Kria KR260 Hardware and Hidden Pitfalls in Learning Robotics: Choosing Your Motors and Power Supply. In those first tests, the robot was still tied to cables. This update covers cutting them: adding WiFi and battery power, mapping the PMOD connectors to Linux GPIO numbers, and driving the robot from a laptop keyboard over the network.

The build stays deliberately cheap and simple: a cardboard chassis, four TT motors, two L298N motor drivers, AA batteries and a USB power bank. If you have a KR260 and want a low-risk way to get it moving, this is a good place to start.

Hardware changes

To make the robot wireless after the initial tests, I added three components:

  • WiFi adapter: Netgear Nighthawk AX1800 USB WiFi adapter (A7500)
  • Power bank: Anker Zolo 74 Wh power bank
  • Power cable: USB-C to 5.5 mm × 2.5 mm DC cable (USB-C input, 12 V / 3 A DC output)

The WiFi adapter is bulky, but it supports WiFi 6 and works with the KR260. Finding a compatible adapter took some research. The Kria runs a modified version of Ubuntu, and most common USB WiFi dongles won't work with it out of the box, so I used Claude to search for one with driver support. After connecting the adapter and configuring the drivers, the board connected over 5 GHz WiFi.

For driving commands alone, it doesn't matter much whether you use 2.4 GHz or 5 GHz. Later, when I add point-cloud or video streaming, the extra bandwidth of 5 GHz will matter.

Cost and complexity are worth calling out here. This version of the robot has no high-voltage LiPo or NiMH battery packs. The four TT motors run through two L298N motor drivers, and four standard AA batteries are enough to power them. The KR260 itself runs from the power bank, as long as the power bank can output 12 V. The USB-C to 12 V DC cable connects the power bank to the board's barrel jack.

Once everything was connected, I tested the wheels on carpet and on hardwood floor with a fixed movement sequence (the test script below). I then gave that test script to Claude to generate a PyGame client that drives the robot from a keyboard.

Finding the pin numbers

Each direction input on the two L298N drivers connects to one GPIO pin on the KR260's PMOD connectors:

GPIO PMOD Motor L298N input
698 PMOD1 Left front, forward IN1
699 PMOD1 Left front, reverse IN2
700 PMOD1 Left rear, forward IN3
701 PMOD1 Left rear, reverse IN4
706 PMOD2 Right front, forward IN1
707 PMOD2 Right front, reverse IN2
708 PMOD2 Right rear, forward IN3
709 PMOD2 Right rear, reverse IN4

GPIO 698–705 are the eight I/O pins on PMOD1, and 706–713 are the eight I/O pins on PMOD2. Each PMOD connector has 12 pins; the remaining four are power and ground. Whitney Knitter's Hackster tutorial shows the pinout and the custom PL design, and its "Testing the GPIO" section shows how to find these numbers.

First, unload the default app and load the app you built in the Vivado tutorial:

sudo xmutil unloadapp
sudo xmutil loadapp <your-app-name>

Then list the GPIO controllers:

ls /sys/class/gpio/

This lists entries named gpiochip followed by a number. Check the label of each one, replacing 698 with each number you found:

cat /sys/class/gpio/gpiochip698/label

One of them returns 80010000.gpio, and the others run up to 80050000.gpio. Each label is one GPIO block in your design, and the number in its gpiochip name is the first GPIO number for that connector:

  • 80010000.gpio → first pin of PMOD1
  • 80020000.gpio → first pin of PMOD2
  • 80030000.gpio → first pin of PMOD3
  • 80040000.gpio → first pin of PMOD4
  • 80050000.gpio → first pin of the Raspberry Pi header

In my case, the mapping was:

Label GPIO chip Connector
80010000.gpio gpiochip698 PMOD1
80020000.gpio gpiochip706 PMOD2
80030000.gpio gpiochip714 PMOD3
80040000.gpio gpiochip722 PMOD4

Using this map, I exported GPIO 698 through 713, set them as outputs, and gave the ubuntu user permission to write to them. These settings reset on reboot, so run the script after each boot:

#!/usr/bin/env bash

# Let the ubuntu user write to the GPIO control files
sudo chown -R ubuntu:ubuntu /sys/class/gpio/*

# PMOD1 (698-705) and PMOD2 (706-713)
for n in {698..713}; do
    # Export the GPIO
    echo "$n" | sudo tee /sys/class/gpio/export >/dev/null

    # Change ownership of the exported GPIO's files
    sudo chown -R ubuntu:ubuntu "/sys/class/gpio/gpio${n}"/*

    # Set the direction to "out"
    echo out | sudo tee "/sys/class/gpio/gpio${n}/direction" >/dev/null
done

Next, I used this Python script to drive the robot through a fixed sequence. It also became the input for the server code Claude generated.

import os
import time

MOTOR_PINS = [698, 699, 700, 701, 706, 707, 708, 709]


def stop(seconds: int = 0):
    for i in MOTOR_PINS:
        os.system(f"echo 0 > /sys/class/gpio/gpio{i}/value")
    time.sleep(seconds)


def forward(seconds: int):
    stop()
    os.system("echo 1 > /sys/class/gpio/gpio698/value")
    os.system("echo 1 > /sys/class/gpio/gpio700/value")
    os.system("echo 1 > /sys/class/gpio/gpio706/value")
    os.system("echo 1 > /sys/class/gpio/gpio708/value")
    time.sleep(seconds)


def backward(seconds: int):
    stop()
    os.system("echo 1 > /sys/class/gpio/gpio699/value")
    os.system("echo 1 > /sys/class/gpio/gpio701/value")
    os.system("echo 1 > /sys/class/gpio/gpio707/value")
    os.system("echo 1 > /sys/class/gpio/gpio709/value")
    time.sleep(seconds)


def turn_left(seconds: int):
    # Left wheels reverse, right wheels forward
    stop()
    os.system("echo 1 > /sys/class/gpio/gpio699/value")
    os.system("echo 1 > /sys/class/gpio/gpio701/value")
    os.system("echo 1 > /sys/class/gpio/gpio706/value")
    os.system("echo 1 > /sys/class/gpio/gpio708/value")
    time.sleep(seconds)


def turn_right(seconds: int):
    # Left wheels forward, right wheels reverse
    stop()
    os.system("echo 1 > /sys/class/gpio/gpio698/value")
    os.system("echo 1 > /sys/class/gpio/gpio700/value")
    os.system("echo 1 > /sys/class/gpio/gpio707/value")
    os.system("echo 1 > /sys/class/gpio/gpio709/value")
    time.sleep(seconds)


stop(2)
forward(4)
stop(2)
backward(4)
stop(1)
turn_left(2)
stop(1)
turn_right(2)
stop()

Client and server

The test script became the basis for a client and server pair. The server runs on the KR260 and listens for UDP packets. The client runs on your desktop and sends the keys you're pressing 20 times per second. If the server receives nothing for 0.5 seconds, it stops the motors, so a dropped connection doesn't leave the robot driving off on its own.

The server should have as few dependencies as possible, because adding Python libraries on the Kria can cause problems. The client, on the other hand, can live in a conda, uv or other Python environment and use libraries like PyGame, which also opens the door to gamepad support. The gamepad only needs to connect to your computer; the Kria runs whatever commands arrive, regardless of where they come from.

Here is the server. It uses only the standard library modules os, socket and time. Change the pin numbers to the ones you found in the previous section.

import os
import socket
import time

PORT = 5005
TIMEOUT = 0.5  # seconds without a packet before motors stop

# (forward, reverse) pin pairs for each motor, from the GPIO table above.
# Change these to the numbers you found on your board.
LEFT = [(698, 699), (700, 701)]
RIGHT = [(706, 707), (708, 709)]
ALL_PINS = [pin for pair in LEFT + RIGHT for pin in pair]


class Gpio:
    """Keeps the sysfs value files open; only writes when a pin changes."""

    def __init__(self, pins):
        self.files = {}
        self.state = {}
        for p in pins:
            base = f"/sys/class/gpio/gpio{p}"
            if not os.path.exists(base):
                with open("/sys/class/gpio/export", "w") as f:
                    f.write(str(p))
                time.sleep(0.1)
            with open(f"{base}/direction", "w") as f:
                f.write("out")
            self.files[p] = open(f"{base}/value", "wb", buffering=0)
            self.set(p, 0, force=True)

    def set(self, pin, value, force=False):
        value = 1 if value else 0
        if not force and self.state.get(pin) == value:
            return
        f = self.files[pin]
        f.seek(0)
        f.write(b"1" if value else b"0")
        self.state[pin] = value

    def close(self):
        for f in self.files.values():
            f.close()


def drive_side(gpio, motors, direction):
    """direction: 1 forward, -1 reverse, 0 stop.
    The pin going low is always written first so an H-bridge
    never sees both inputs high."""
    for fwd, rev in motors:
        if direction > 0:
            gpio.set(rev, 0)
            gpio.set(fwd, 1)
        elif direction < 0:
            gpio.set(fwd, 0)
            gpio.set(rev, 1)
        else:
            gpio.set(fwd, 0)
            gpio.set(rev, 0)


def keys_to_sides(keys):
    """Map pressed keys to (left, right) directions."""
    w, a, s, d = ("w" in keys), ("a" in keys), ("s" in keys), ("d" in keys)
    turn_left = a and not d
    turn_right = d and not a

    if w and not s:                   # forward, optionally curving
        if turn_left:
            return 0, 1
        if turn_right:
            return 1, 0
        return 1, 1
    if s and not w:                   # reverse, optionally curving
        if turn_left:
            return 0, -1
        if turn_right:
            return -1, 0
        return -1, -1
    if turn_left:                     # spin in place
        return -1, 1
    if turn_right:
        return 1, -1
    return 0, 0


def main():
    gpio = Gpio(ALL_PINS)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(("0.0.0.0", PORT))
    sock.settimeout(0.1)

    last_packet = 0.0
    current = (0, 0)
    print(f"Listening on UDP {PORT}. Ctrl+C to quit.")

    try:
        while True:
            try:
                data, addr = sock.recvfrom(64)
                keys = data.decode(errors="ignore").lower()
                last_packet = time.monotonic()
                target = keys_to_sides(keys)
            except socket.timeout:
                target = current

            if time.monotonic() - last_packet > TIMEOUT:
                target = (0, 0)

            if target != current:
                drive_side(gpio, LEFT, target[0])
                drive_side(gpio, RIGHT, target[1])
                current = target
                print(f"\rleft={target[0]:+d} right={target[1]:+d}   ",
                      end="", flush=True)
    except KeyboardInterrupt:
        pass
    finally:
        for p in ALL_PINS:
            gpio.set(p, 0, force=True)
        gpio.close()
        print("\nMotors off.")


if __name__ == "__main__":
    main()

And here is the PyGame client. Once you've found and verified your pins, you can ask an LLM of your choice to generate a different client, such as a web page or one built on another framework.

"""
Runs ON YOUR DESKTOP/LAPTOP. Opens a small pygame window; while it has focus,
W/A/S/D drive the robot.

  W  forward        S  reverse
  A  spin left      D  spin right
  W+A / W+D  curve forward     S+A / S+D  curve backward
  Space  stop       Esc  quit

Run:     python3 drive_client.py <kria-ip>
"""
import socket
import sys

import pygame

PORT = 5005
SEND_HZ = 20

if len(sys.argv) < 2:
    sys.exit("usage: python3 drive_client.py <kria-ip>")
HOST = sys.argv[1]

KEYS = (("w", pygame.K_w), ("a", pygame.K_a),
        ("s", pygame.K_s), ("d", pygame.K_d))


def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    pygame.init()
    screen = pygame.display.set_mode((460, 220))
    pygame.display.set_caption("Robot drive - WASD")
    font = pygame.font.SysFont(None, 34)
    small = pygame.font.SysFont(None, 24)
    clock = pygame.time.Clock()

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False

        pressed = pygame.key.get_pressed()
        keys = "".join(c for c, code in KEYS if pressed[code])
        # Stop if Space is held or the window loses focus
        if pressed[pygame.K_SPACE] or not pygame.key.get_focused():
            keys = ""

        sock.sendto((keys or "-").encode(), (HOST, PORT))

        screen.fill((25, 25, 30))
        label = keys.upper() if keys else "STOPPED"
        screen.blit(font.render(f"Keys: {label}", True, (240, 240, 240)),
                    (20, 40))
        screen.blit(small.render(f"Sending to {HOST}:{PORT}", True,
                                 (150, 150, 160)), (20, 100))
        screen.blit(small.render("Space = stop   Esc = quit", True,
                                 (150, 150, 160)), (20, 140))
        pygame.display.flip()
        clock.tick(SEND_HZ)

    for _ in range(3):
        sock.sendto(b"-", (HOST, PORT))
    pygame.quit()


if __name__ == "__main__":
    main()

Conclusion

The robot now drives wirelessly on a cardboard chassis. It runs well on floors and tables, but turning is still a problem.

You may have noticed that the GPIO table has no speed-control pins (ENA and ENB on the L298N). The TT motors are slow enough that I left the jumpers on ENA and ENB of both drivers, which keeps every motor at full speed. That means the software only needs to control direction.

Here's the robot in action (click to watch on YouTube):

Cardboard KR260 robot driving over WiFi
Cardboard KR260 robot driving over WiFi

For getting started and testing, a cardboard box with four TT motors and AA batteries is still a great platform. For the next step, I'm planning to replace the cardboard with an aluminum chassis, four higher-torque motors and a LiPo battery.

Here's a preview of the next build. From the top, the KR260 and the WiFi adapter sit on the new aluminum chassis with larger off-road wheels:

Top view of the new robot
Top view of the new robot

Underneath are the power bank and a Gens ace 3800 mAh 3S (11.1 V) LiPo battery:

Underside of the new robot showing the power bank and a Gens ace 3800 mAh 3S LiPo battery
Underside of the new robot showing the power bank and a Gens ace 3800 mAh 3S LiPo battery

fpgakria kr 260

← All posts