Sohaib Arif — AI Safety Research

Notes on AI safety for local & embedded models

Adding FPGA PWM speed control to an AMD Kria KR260 robot with IBT-2 motor drivers

Introduction

This is a follow-up to Driving an AMD Kria KR260 Robot over WiFi in a cardboard chassis, which built on my earlier post Getting started with AMD Kria KR260 hardware.

In the last build the L298N enable pins were jumpered high, so the motors only had two speeds: stopped and flat out. Speed control needs PWM, and toggling a sysfs GPIO from Python is far too slow and jittery to generate it. The KR260 has an FPGA, so the better answer is to generate PWM in hardware.

In this post I:

  • replaced the AXI GPIO on PMOD3 with a small custom 8-channel PWM core written in Verilog
  • loaded it on the board and drove it from Python with no kernel driver
  • tested it on a Parallax servo from an old Boe-Bot kit
  • moved the robot to a metal 4WD chassis driven by two IBT-2 (BTS7960) motor drivers
  • rewrote the client and server with speed control, safety features and Xbox controller support

As before, I used an AI assistant (Claude) for research, code generation and debugging along the way. All the code below is the final working version.

Hardware changes

Top view of the new robot
Top view of the new robot
IBT2 wiring in first layer
IBT2 wiring in first layer
  • Chassis: metal 4WD chassis, 27 × 27 cm, with large off-road wheels and four geared DC motors
  • Motor drivers: two IBT-2 (BTS7960) boards, one per side, replacing the L298Ns
  • Motor power: 12 V (3S) LiPo with a Deans connector, split to both drivers (details below)
  • Test servo: Parallax Continuous Rotation Servo (#900-00008) from a Boe-Bot kit

The PMODs are now split by job:

Connector Job Linux access
PMOD1 Right IBT-2 enable pins sysfs GPIO 698–705
PMOD2 Left IBT-2 enable pins sysfs GPIO 706–713
PMOD3 8 PWM outputs (new) PWM core at 0x8003_0000
PMOD4 Spare GPIO sysfs GPIO 714–721 (moved, see below)

Aside: how PWM works. Pulse width modulation controls power from a pin that can only be on or off. The pin switches between high and low at a fixed frequency, and the fraction of each period it spends high is the duty cycle. A motor driver passes that switching on to the motor, which responds to the average voltage, so 30% duty gives roughly 30% speed. Switching at 20 kHz keeps the motors quiet because the frequency is above human hearing. Servos read the signal differently: they measure the length of each pulse rather than the average. A 50 Hz signal with a 1.5 ms pulse means "center" or "stop", and shorter or longer pulses move or turn the servo one way or the other. That's why each channel of the PWM core below has its own frequency and pulse width.

For a longer introduction with diagrams, see SparkFun's Pulse Width Modulation tutorial.

Adding a PWM block to the FPGA

My block design had one AXI GPIO per PMOD. I deleted the one for PMOD3 and put a custom PWM core in its place. The core sits on the same AXI interconnect, so Linux sees it as a small block of registers at a fixed address.

Each of the 8 channels has its own period and duty registers, so motors can run at 20 kHz while a servo on another pin runs at 50 Hz. New values only take effect at the end of the current period, so changing speed never produces a glitch.

Offset Register Meaning
0x00 ENABLE Bit n enables channel n
0x04 ID Reads 0x50574D38 ("PWM8"), a sanity check from Python
0x40 + 8n PERIOD_n Period in clock cycles
0x44 + 8n DUTY_n High time in clock cycles

I simulated it in Icarus Verilog before going near Vivado. The test checked exact duty cycles, byte writes, register readback and duty changes while running. Here's the core:

`timescale 1ns / 1ps
// -----------------------------------------------------------------------------
// pwm8_axi.v  -  8-channel PWM generator with an AXI4-Lite slave interface
//
// Drop this into the KR260 block design with "Add Module" (module reference).
// Vivado infers the s_axi_* ports as an AXI4-Lite slave, so Connection
// Automation can wire it up exactly like an AXI GPIO.
//
// Register map (32-bit registers, byte offsets from the base address):
//   0x00  ENABLE     [7:0]  one bit per channel, 1 = running, 0 = output low
//   0x04  ID         read-only, 0x50574D38 ("PWM8") - handy sanity check
//   0x40 + 8*n  PERIOD_n  period of channel n in PL clock cycles
//   0x44 + 8*n  DUTY_n    high time of channel n in PL clock cycles
//                         (0 = always low, >= PERIOD = always high)
//
// New PERIOD/DUTY values are taken at the end of the current period, so
// changing speed never produces a runt pulse.  With a 100 MHz PL clock:
//   20 kHz motor PWM -> PERIOD = 5000
//   50 Hz servo      -> PERIOD = 2_000_000, DUTY = 100_000..200_000 (1-2 ms)
// -----------------------------------------------------------------------------
module pwm8_axi (
    (* X_INTERFACE_INFO = "xilinx.com:signal:clock:1.0 s_axi_aclk CLK" *)
    (* X_INTERFACE_PARAMETER = "ASSOCIATED_BUSIF s_axi, ASSOCIATED_RESET s_axi_aresetn" *)
    input  wire        s_axi_aclk,
    (* X_INTERFACE_INFO = "xilinx.com:signal:reset:1.0 s_axi_aresetn RST" *)
    (* X_INTERFACE_PARAMETER = "POLARITY ACTIVE_LOW" *)
    input  wire        s_axi_aresetn,

    // AXI4-Lite write address / data / response
    input  wire [6:0]  s_axi_awaddr,
    input  wire [2:0]  s_axi_awprot,
    input  wire        s_axi_awvalid,
    output reg         s_axi_awready,
    input  wire [31:0] s_axi_wdata,
    input  wire [3:0]  s_axi_wstrb,
    input  wire        s_axi_wvalid,
    output reg         s_axi_wready,
    output wire [1:0]  s_axi_bresp,
    output reg         s_axi_bvalid,
    input  wire        s_axi_bready,

    // AXI4-Lite read address / data
    input  wire [6:0]  s_axi_araddr,
    input  wire [2:0]  s_axi_arprot,
    input  wire        s_axi_arvalid,
    output reg         s_axi_arready,
    output reg  [31:0] s_axi_rdata,
    output wire [1:0]  s_axi_rresp,
    output reg         s_axi_rvalid,
    input  wire        s_axi_rready,

    // PWM outputs -> PMOD3
    output wire [7:0]  pwm_out
);

    localparam [31:0] ID_VALUE = 32'h50574D38; // "PWM8"

    wire clk  = s_axi_aclk;
    wire rstn = s_axi_aresetn;

    assign s_axi_bresp = 2'b00; // OKAY
    assign s_axi_rresp = 2'b00; // OKAY

    // ---------------------------------------------------------------- registers
    reg  [7:0]  enable;
    reg  [31:0] period [0:7];
    reg  [31:0] duty   [0:7];

    // ------------------------------------------------------------- write path
    // Accept address and data together, then return a write response.
    wire wr_start = s_axi_awvalid && s_axi_wvalid && !s_axi_awready && !s_axi_bvalid;
    wire wr_en    = s_axi_awvalid && s_axi_awready && s_axi_wvalid && s_axi_wready;
    wire [4:0] wr_idx = s_axi_awaddr[6:2];

    always @(posedge clk) begin
        if (!rstn) begin
            s_axi_awready <= 1'b0;
            s_axi_wready  <= 1'b0;
            s_axi_bvalid  <= 1'b0;
        end else begin
            s_axi_awready <= wr_start;
            s_axi_wready  <= wr_start;
            if (wr_en)
                s_axi_bvalid <= 1'b1;
            else if (s_axi_bready)
                s_axi_bvalid <= 1'b0;
        end
    end

    integer k, b;
    always @(posedge clk) begin
        if (!rstn) begin
            enable <= 8'd0;
            for (k = 0; k < 8; k = k + 1) begin
                period[k] <= 32'd0;
                duty[k]   <= 32'd0;
            end
        end else if (wr_en) begin
            if (wr_idx == 5'd0) begin
                if (s_axi_wstrb[0]) enable <= s_axi_wdata[7:0];
            end else if (wr_idx[4]) begin
                for (b = 0; b < 4; b = b + 1) begin
                    if (s_axi_wstrb[b]) begin
                        if (wr_idx[0])
                            duty[wr_idx[3:1]][b*8 +: 8]   <= s_axi_wdata[b*8 +: 8];
                        else
                            period[wr_idx[3:1]][b*8 +: 8] <= s_axi_wdata[b*8 +: 8];
                    end
                end
            end
        end
    end

    // -------------------------------------------------------------- read path
    wire [4:0] rd_idx = s_axi_araddr[6:2];

    always @(posedge clk) begin
        if (!rstn) begin
            s_axi_arready <= 1'b0;
            s_axi_rvalid  <= 1'b0;
            s_axi_rdata   <= 32'd0;
        end else begin
            s_axi_arready <= s_axi_arvalid && !s_axi_arready && !s_axi_rvalid;
            if (s_axi_arvalid && s_axi_arready) begin
                s_axi_rvalid <= 1'b1;
                if (rd_idx == 5'd0)
                    s_axi_rdata <= {24'd0, enable};
                else if (rd_idx == 5'd1)
                    s_axi_rdata <= ID_VALUE;
                else if (rd_idx[4])
                    s_axi_rdata <= rd_idx[0] ? duty[rd_idx[3:1]] : period[rd_idx[3:1]];
                else
                    s_axi_rdata <= 32'd0;
            end else if (s_axi_rready) begin
                s_axi_rvalid <= 1'b0;
            end
        end
    end

    // ---------------------------------------------------------- PWM channels
    genvar i;
    generate
        for (i = 0; i < 8; i = i + 1) begin : ch
            reg [31:0] cnt;
            reg [31:0] per_act;   // active (latched) period
            reg [31:0] duty_act;  // active (latched) duty
            reg        out_q;

            always @(posedge clk) begin
                if (!rstn || !enable[i]) begin
                    cnt      <= 32'd0;
                    per_act  <= period[i];
                    duty_act <= duty[i];
                    out_q    <= 1'b0;
                end else begin
                    if (per_act == 32'd0 || cnt >= per_act - 32'd1) begin
                        cnt      <= 32'd0;
                        per_act  <= period[i];   // pick up new settings
                        duty_act <= duty[i];     // only at period boundary
                    end else begin
                        cnt <= cnt + 32'd1;
                    end
                    out_q <= (cnt < duty_act);
                end
            end

            assign pwm_out[i] = out_q;
        end
    endgenerate

endmodule

Updating the Vivado project

  1. Add pwm8_axi.v with Add Sources. Right-click the block design canvas and choose Add Module → pwm8_axi. Vivado recognises the s_axi_* ports as an AXI4-Lite slave.
  2. Connect s_axi to the SmartConnect port the old pmod_3 GPIO used (M03_AXI in my design). Connect the clock and reset to the same sources as the other GPIOs. In my design that's clk_wiz_0/clk_out2 and proc_sys_reset_1/peripheral_aresetn. Note the clock frequency. Mine is 200 MHz, and it matters later.
  3. Right-click pwm_out, choose Make External, and rename the port to pmod3_pwm.
  4. In the Address Editor, give the block the old PMOD3 address (0x8003_0000) so PMOD4 and the RPi GPIO keep theirs.

My address map after the change:

Block Base address
axi_intc_0 0x8000_0000
pmod_1 0x8001_0000
pmod_2 0x8002_0000
pwm8_axi_0 0x8003_0000 (4K)
pmod_4 0x8004_0000
rpi_gpio 0x8005_0000

The HDL wrapper. My wrapper is user-managed (krio_gpio_redo.srcs/sources_1/imports/hdl/kria_bd_wrapper.v), so I edited it by hand. The PMOD3 inout port became an output, the 8 PMOD3 IOBUFs and their wires were deleted, and the three tri-state connections became one line:

module kria_bd_wrapper
   (
    output [0:0]fan_en_b,
    inout [7:0]pmod1_io,
    inout [7:0]pmod2_io,
    output [7:0]pmod3_pwm,      // was: inout [7:0]pmod3_io
    inout [7:0]pmod4_io,
    inout [27:0]rpi_gpio
    );
  ...
  kria_bd kria_bd_i
       (.fan_en_b(fan_en_b),
        ...
        .pmod3_pwm(pmod3_pwm),  // replaces .pmod3_io_tri_i/_o/_t
        ...

get_files *_wrapper.v in the Tcl console finds the wrapper. Don't edit kria_bd.v: that's the generated netlist, and Vivado overwrites it.

The constraints. My first bitstream build failed at the very end:

ERROR: [DRC NSTD-1] Unspecified I/O Standard: 8 out of 61 logical ports use I/O standard (IOSTANDARD) value 'DEFAULT' ... Problem ports: pmod3_pwm[7:0].
ERROR: [DRC UCIO-1] Unconstrained Logical Port: 8 out of 61 logical ports have no user assigned specific location constraint (LOC) ... Problem ports: pmod3_pwm[7:0].

The XDC still used the old port name, so the new pins had no location or I/O standard. Don't use the suggested set_property SEVERITY {Warning} workaround. It builds a bitstream with your outputs on random pins. Rename the ports instead and keep the same package pins:

sed -i.bak 's/pmod3_io\[/pmod3_pwm[/g' pmod_pinout.xdc
grep -n "pmod3" pmod_pinout.xdc

Every PMOD3 PACKAGE_PIN and IOSTANDARD line should now name pmod3_pwm[0] to [7]. Channel n of the PWM core comes out on the same pin as bit n of the old PMOD3 GPIO.

Side quest: Vivado on Ubuntu 26.04

Midway through this I upgraded my desktop from Ubuntu 24.04 to 26.04. Afterwards Vivado 2025.2.1 showed its splash screen and quit, while the Vitis IDE still worked. Running vivado from a terminal showed the real error:

application-specific initialization failed: couldn't load file "libxv_commontasks.so": libncurses.so.5: cannot open shared object file: No such file or directory

Ubuntu no longer ships the old ncurses 5 libraries, and the upgrade removed the copies I had installed. The cleanest fix is installing the Ubuntu 22.04 packages, which only depend on libc:

cd /tmp
wget http://security.ubuntu.com/ubuntu/pool/universe/n/ncurses/libtinfo5_6.3-2ubuntu0.1_amd64.deb
wget http://security.ubuntu.com/ubuntu/pool/universe/n/ncurses/libncurses5_6.3-2ubuntu0.1_amd64.deb
sudo apt install ./libtinfo5_6.3-2ubuntu0.1_amd64.deb ./libncurses5_6.3-2ubuntu0.1_amd64.deb

The quicker workaround is to point the old names at the current libraries:

sudo ln -sf /lib/x86_64-linux-gnu/libncurses.so.6 /lib/x86_64-linux-gnu/libncurses.so.5
sudo ln -sf /lib/x86_64-linux-gnu/libtinfo.so.6   /lib/x86_64-linux-gnu/libtinfo.so.5

Lesson learned: always launch Vivado from a terminal when it misbehaves. The desktop icon hides the error.

Building and loading the new overlay

XSA. Generating the bitstream doesn't produce an XSA. Export it with File → Export → Export Hardware → Include bitstream, or from Tcl:

write_hw_platform -fixed -include_bit -force -file /home/sohaib/repos/krio_gpio_redo/kria_bd_wrapper_pwm.xsa

Device tree overlay. Same flow as Whitney Knitter's tutorial, with one catch. The tutorial runs hsi::open_hw_design first, but createdts -hw opens the XSA itself. Running both gives ERROR: [Hsi 55-1571] The design file ... is already opened. Skip the first line:

xsct
createdts -hw /home/sohaib/repos/krio_gpio_redo/kria_bd_wrapper_pwm.xsa -zocl -platform-name kria_kr260 -git-branch xlnx_rel_v2022.1 -overlay -compile -out ./dtg_kr260_pwm
exit

I kept the tutorial's xlnx_rel_v2022.1 branch because it already worked with the Kria Ubuntu image. -compile didn't produce a pl.dtbo for me, so I compiled it by hand:

cd $(dirname $(find ./dtg_kr260_pwm -name pl.dtsi))
dtc -@ -O dtb -o pl.dtbo pl.dtsi

The overlay has no node for the PWM core, and it doesn't need one. Python accesses the core directly through /dev/mem.

Load it on the KR260. Copy pl.dtbo, the bitstream .bin and shell.json into a folder under /lib/firmware/xilinx/. Mine is kr260_kria_pwm_gpio. Then:

sudo xmutil unloadapp
sudo xmutil loadapp kr260_kria_pwm_gpio

The GPIO chips after loading:

ubuntu@kria:~$ ls /sys/class/gpio/
export  gpiochip512  gpiochip516  gpiochip690  gpiochip698  gpiochip706  gpiochip714  gpiochip722  unexport
gpiochip Label Connector
698 80010000.gpio PMOD1
706 80020000.gpio PMOD2
714 80040000.gpio PMOD4 (was 722)
722 80050000.gpio RPi header (moved down too)

There's no 80030000 entry, which is correct: the PWM core isn't a GPIO controller. PMOD1 and PMOD2 kept their numbers, so the motor-enable code didn't change. But anything that hardcoded PMOD4 or RPi GPIO numbers needs updating.

Debugging: the old bitstream was still loaded

The first run of my Python driver failed its ID check:

RuntimeError: No PWM8 core at 0x80030000 - check PWM_BASE and that the new bitstream is loaded

xmutil listapps showed the new app loaded, and the address was right. So I read the registers directly:

sudo python3 - <<'EOF'
import mmap, os
fd = os.open("/dev/mem", os.O_RDWR | os.O_SYNC)
for base in (0x80010000, 0x80030000):          # PMOD1 GPIO for comparison, then PWM
    m = mmap.mmap(fd, 0x1000, offset=base)
    v = memoryview(m).cast("I")
    print(hex(base), [hex(v[i]) for i in range(4)])
    v.release(); m.close()
os.close(fd)
EOF
0x80010000 ['0xea', '0xff', '0x0', '0xffffffff']
0x80030000 ['0xd8', '0xff', '0x0', '0xffffffff']

0x80030000 looked exactly like an AXI GPIO: pin levels, then 0xff in the direction register. The new overlay had loaded, but the app folder still held the old .bin, so the FPGA still had the PMOD3 GPIO. After copying the new bitstream across (check with md5sum against the one in impl_1) and reloading, the second word read 0x50574d38, which is "PWM8".

This trick is worth remembering. Reading the registers directly tells you within seconds what hardware is really in the FPGA, whatever the device tree says.

Testing PWM with a servo

Before connecting motors, I tested with a Parallax Continuous Rotation Servo (#900-00008) from an old Boe-Bot kit. It takes a 50 Hz signal with 1.3 ms pulses for full speed one way, 1.5 ms for stop and 1.7 ms for full speed the other way. It worked fine with PMOD3's 3.3 V signal.

Servo wire Connection
White (signal) PMOD3 pin 7 (channel 4)
Black (ground) PMOD3 GND and the servo battery's negative
Red (power) A separate ~6 V supply such as the Boe-Bot's 4×AA pack, never the PMOD's 3.3 V

The driver uses only the Python standard library and talks to the core through /dev/mem, so it needs sudo:

#!/usr/bin/env python3
"""
pwm8.py - drive the pwm8_axi core on PMOD3 of the KR260 (standard library only).

Needs root (it maps /dev/mem). Set PWM_BASE to the address Vivado's Address
Editor assigned to the pwm8_axi block, and PL_CLK_HZ to your pl_clk0 rate.

PMOD3 channel numbering follows the pwm_out bit order in your XDC:
    ch0..ch3 -> PMOD3 pins 1..4 (top row), ch4..ch7 -> pins 7..10 (bottom row)
"""
import mmap
import os

PWM_BASE  = 0x80030000      # <-- check Address Editor (old pmod_3 GPIO slot)
PL_CLK_HZ = 200_000_000     # clk_wiz_0 clk_out2 frequency (the clock the
                            # pwm8_axi block runs on), NOT pl_clk0

_ENABLE = 0x00
_ID     = 0x04
_ID_VAL = 0x50574D38        # "PWM8"


class PWM8:
    def __init__(self, base=PWM_BASE, clk_hz=PL_CLK_HZ):
        self.clk_hz = clk_hz
        fd = os.open("/dev/mem", os.O_RDWR | os.O_SYNC)
        try:
            self._mm = mmap.mmap(fd, 0x1000, mmap.MAP_SHARED,
                                 mmap.PROT_READ | mmap.PROT_WRITE, offset=base)
        finally:
            os.close(fd)
        # 32-bit view so every access is a single aligned word transaction
        self._regs = memoryview(self._mm).cast("I")
        if self._rd(_ID) != _ID_VAL:
            raise RuntimeError(f"No PWM8 core at 0x{base:08X} - check PWM_BASE "
                               "and that the new bitstream is loaded")
        self._enabled = self._rd(_ENABLE) & 0xFF

    # -- raw register access ------------------------------------------------
    def _rd(self, off):
        return self._regs[off // 4]

    def _wr(self, off, val):
        self._regs[off // 4] = int(val) & 0xFFFFFFFF

    # -- per-channel setup ----------------------------------------------------
    def set_frequency(self, ch, hz):
        """Set PWM frequency of channel ch (keeps the same duty fraction)."""
        old_period = self._rd(0x40 + 8 * ch)
        old_frac = (self._rd(0x44 + 8 * ch) / old_period) if old_period else 0.0
        period = max(1, round(self.clk_hz / hz))
        self._wr(0x40 + 8 * ch, period)
        self._wr(0x44 + 8 * ch, round(period * old_frac))

    def set_duty(self, ch, fraction):
        """Duty cycle 0.0 .. 1.0 (motor speed)."""
        fraction = min(max(fraction, 0.0), 1.0)
        period = self._rd(0x40 + 8 * ch)
        self._wr(0x44 + 8 * ch, round(period * fraction))

    def set_pulse_us(self, ch, microseconds):
        """High time in microseconds (servos: ~1000-2000 us at 50 Hz)."""
        self._wr(0x44 + 8 * ch, round(microseconds * self.clk_hz / 1_000_000))

    def enable(self, ch, on=True):
        if on:
            self._enabled |= (1 << ch)
        else:
            self._enabled &= ~(1 << ch)
        self._wr(_ENABLE, self._enabled)

    def stop_all(self):
        for ch in range(8):
            self._wr(0x44 + 8 * ch, 0)
        self._enabled = 0
        self._wr(_ENABLE, 0)

    def close(self):
        self._regs.release()
        self._mm.close()


if __name__ == "__main__":
    import time

    # Suggested wiring: ch0 = left L298N ENA, ch1 = left ENB,
    #                   ch2 = right L298N ENA, ch3 = right ENB
    pwm = PWM8()
    MOTORS = (0, 1, 2, 3)
    for ch in MOTORS:
        pwm.set_frequency(ch, 1_000)     # 1 kHz; try up to ~20 kHz
        pwm.set_duty(ch, 0.0)
        pwm.enable(ch)

    # Set the IN1-IN4 direction pins on PMOD1/PMOD2 as usual, then ramp speed:
    try:
        for pct in range(0, 101, 10):
            for ch in MOTORS:
                pwm.set_duty(ch, pct / 100)
            print(f"duty {pct}%")
            time.sleep(0.5)
    finally:
        pwm.stop_all()
        pwm.close()

The bug. My first test turned the servo in only one direction, whatever pulse width I asked for. The driver assumed a 100 MHz clock, but my AXI blocks run on clk_out2 at 200 MHz. Every pulse came out half as long as requested: "stop" (1500 µs) was really 750 µs, far outside the servo's range. Setting PL_CLK_HZ = 200_000_000 fixed it. The test script now prints the period and pulse width it programmed, along with the clock frequency it assumes, so this mistake is visible straight away.

The Boe-Bot servo also needs centering: hold a 1.5 ms pulse and gently turn the trimmer screw until it stops moving. The test script has a --center mode for that:

#!/usr/bin/env python3
"""
servo_test.py - exercise a Parallax Continuous Rotation Servo (#900-00008,
the Boe-Bot drive servo) from PMOD3 on the KR260 using the pwm8_axi core.

Servo control spec (datasheet): pulse every 20 ms (50 Hz), 1.3-1.7 ms pulses
  1300 us = full speed clockwise
  1500 us = stop  (only after the servo has been centered - see --center)
  1700 us = full speed counter-clockwise
  Speed is roughly linear in between (0-50 RPM).

Usage (needs pwm8.py in the same folder, run as root):
  sudo python3 servo_test.py --center     # hold 1500 us while you trim the pot
  sudo python3 servo_test.py              # scripted test sequence
  sudo python3 servo_test.py --pulse 1600 # hold one pulse width, Ctrl+C to stop
  sudo python3 servo_test.py --blink      # 1 Hz LED blink on the pin, no servo
  add --ch N to use another PMOD3 channel (default 4 = PMOD3 pin 7)
"""
import argparse
import time

from pwm8 import PWM8

SERVO_HZ = 50
STOP_US = 1500
MIN_US, MAX_US = 1300, 1700


def hold(pwm, ch, us, seconds, label):
    us = min(max(us, MIN_US), MAX_US)
    pwm.set_pulse_us(ch, us)
    print(f"{label:<28} {us} us")
    time.sleep(seconds)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ch", type=int, default=4,
                    help="PWM channel 0-7 (0-3 = PMOD3 pins 1-4, 4-7 = pins 7-10)")
    ap.add_argument("--pulse", type=int, help="hold this pulse width in us")
    ap.add_argument("--center", action="store_true",
                    help="hold 1500 us so you can adjust the centering pot")
    ap.add_argument("--blink", action="store_true",
                    help="1 Hz 50%% square wave for an LED check")
    args = ap.parse_args()

    pwm = PWM8()
    ch = args.ch
    try:
        if args.blink:
            pwm.set_frequency(ch, 1)
            pwm.set_duty(ch, 0.5)
            pwm.enable(ch)
            print(f"Blinking PMOD3 channel {ch} at 1 Hz - Ctrl+C to stop")
            while True:
                time.sleep(1)

        # Configure 50 Hz with a 'stop' pulse BEFORE enabling, so the very
        # first pulse the servo sees is a stop command.
        pwm.set_frequency(ch, SERVO_HZ)
        pwm.set_pulse_us(ch, STOP_US)
        pwm.enable(ch)

        period = pwm._rd(0x40 + 8 * ch)
        high = pwm._rd(0x44 + 8 * ch)
        print(f"PWM check: period {period} counts = {period / pwm.clk_hz * 1000:.2f} ms, "
              f"high {high} counts = {high / pwm.clk_hz * 1e6:.0f} us "
              f"(assuming {pwm.clk_hz / 1e6:.0f} MHz clock)")

        if args.center or args.pulse is not None:
            us = STOP_US if args.center else args.pulse
            hold(pwm, ch, us, 0, "Holding")
            if args.center:
                print("Gently turn the pot screw until the servo stops "
                      "(no turning or buzzing).")
            print("Ctrl+C to stop")
            while True:
                time.sleep(1)

        hold(pwm, ch, STOP_US, 2, "Stop")
        hold(pwm, ch, 1450, 3, "Slow clockwise")
        hold(pwm, ch, MIN_US, 3, "Full speed clockwise")
        hold(pwm, ch, STOP_US, 2, "Stop")
        hold(pwm, ch, 1550, 3, "Slow counter-clockwise")
        hold(pwm, ch, MAX_US, 3, "Full speed counter-clockwise")
        hold(pwm, ch, STOP_US, 1, "Stop")

        print("Ramp clockwise -> counter-clockwise")
        for us in range(MIN_US, MAX_US + 1, 20):
            hold(pwm, ch, us, 0.4, "  ramp")
        hold(pwm, ch, STOP_US, 1, "Stop")
    except KeyboardInterrupt:
        pass
    finally:
        pwm.set_pulse_us(ch, STOP_US)   # command a stop first...
        time.sleep(0.1)
        pwm.enable(ch, False)           # ...then drop the signal
        pwm.close()
        print("Done - channel disabled")


if __name__ == "__main__":
    main()
sudo python3 servo_test.py --center   # hold 1500 us, adjust the pot
sudo python3 servo_test.py            # full test sequence

Driving the IBT-2 motor drivers

Each IBT-2 has a full H-bridge with four control inputs: RPWM, LPWM, R_EN and L_EN. I gave each signal its own wire color to make debugging easier, and used the same colors on both drivers:

Wire IBT-2 pin Right driver Left driver
Yellow R_EN PMOD1 bit 0 (gpio698) PMOD2 bit 0 (gpio706)
Orange L_EN PMOD1 bit 1 (gpio699) PMOD2 bit 1 (gpio707)
Blue LPWM PMOD3 bit 0 (PWM ch0) PMOD3 bit 2 (PWM ch2)
Green RPWM PMOD3 bit 1 (PWM ch1) PMOD3 bit 3 (PWM ch3)
VCC / GND PMOD1 3.3 V / GND PMOD2 3.3 V / GND

A few notes:

  • Power the IBT-2's logic VCC from the PMOD's 3.3 V. The board's input buffer then reads 3.3 V signals reliably. At 5 V it might not.
  • Leave R_IS and L_IS (current sense) unconnected. They can go above 3.3 V.
  • Watch the old GPIO numbers. After this change, gpio714–717 belong to PMOD4, not PMOD3.

How the driver controls each board:

R_EN, L_EN RPWM LPWM Result
1, 1 PWM 0 One direction, speed = duty
1, 1 0 PWM Other direction
1, 1 0 0 Brake
0, 0 x x Coast (outputs off)

The driver never drives both PWM pins at once, runs at 20 kHz (inaudible), and on exit sets both duty cycles to 0 and the enable pins low:

#!/usr/bin/env python3
"""
ibt2.py - drive two IBT-2 (BTS7960) motor drivers from the KR260.

Enable pins (R_EN / L_EN) are plain GPIOs on PMOD1/PMOD2 (sysfs).
PWM pins (RPWM / LPWM) come from the pwm8_axi core on PMOD3.
Needs pwm8.py in the same folder. Run as root.

IBT-2 truth table (per driver):
  R_EN=L_EN=1, RPWM=pwm, LPWM=0  -> motor one way, speed = duty
  R_EN=L_EN=1, RPWM=0,   LPWM=pwm -> motor the other way
  R_EN=L_EN=1, RPWM=0,   LPWM=0   -> brake (both low sides on)
  R_EN=L_EN=0                     -> coast (outputs off)

Usage:
  sudo python3 ibt2.py                 # test sequence (wheels off the ground!)
  sudo python3 ibt2.py --max 0.4       # limit test speed to 40 %
  sudo python3 ibt2.py --freq 5000     # different PWM frequency
"""
import argparse
import os
import time

from pwm8 import PWM8

PWM_FREQ_HZ = 20_000        # BTS7960 handles up to ~25 kHz; 20 kHz is inaudible

# --- wiring (matches the colour code) ------------------------------------
#                   RPWM(green) LPWM(blue) R_EN(yellow) L_EN(orange) invert
RIGHT = dict(name="right", rpwm=1, lpwm=0, r_en=698, l_en=699, invert=True)
LEFT  = dict(name="left",  rpwm=3, lpwm=2, r_en=706, l_en=707, invert=True)
# 'invert' flips direction so +speed drives the robot forward on both sides.
# Set from the 2026-11-01 video test: with right=False the right side ran
# backwards on +speed. If a side goes backwards on +speed, flip its flag.

GPIO_ROOT = "/sys/class/gpio"


class SysfsGPIO:
    """Minimal sysfs GPIO output (same mechanism as your setup script)."""

    def __init__(self, num):
        path = f"{GPIO_ROOT}/gpio{num}"
        if not os.path.exists(path):
            with open(f"{GPIO_ROOT}/export", "w") as f:
                f.write(str(num))
            for _ in range(100):                 # wait for the node to appear
                if os.path.exists(f"{path}/direction"):
                    break
                time.sleep(0.01)
        with open(f"{path}/direction", "w") as f:
            f.write("low")                       # output, starting LOW
        self._fd = os.open(f"{path}/value", os.O_WRONLY)

    def set(self, on):
        os.pwrite(self._fd, b"1" if on else b"0", 0)

    def close(self):
        os.close(self._fd)


class IBT2:
    """One IBT-2 board = one side of the robot."""

    def __init__(self, pwm, name, rpwm, lpwm, r_en, l_en, invert=False):
        self.pwm, self.name = pwm, name
        self.ch_r, self.ch_l = rpwm, lpwm
        self.invert = invert
        self.en = [SysfsGPIO(r_en), SysfsGPIO(l_en)]
        self.speed = 0.0
        for ch in (rpwm, lpwm):
            pwm.set_frequency(ch, PWM_FREQ_HZ)
            pwm.set_duty(ch, 0.0)
            pwm.enable(ch)

    def enable(self, on=True):
        for g in self.en:
            g.set(on)

    def set_speed(self, speed):
        """speed -1.0 .. +1.0  (0 = brake while enabled)."""
        speed = max(-1.0, min(1.0, speed))
        s = -speed if self.invert else speed
        if s > 0:
            self.pwm.set_duty(self.ch_l, 0.0)    # turn the other side off first
            if self.speed_dir() < 0:
                time.sleep(0.001)                # one-way switch: let LPWM settle
            self.pwm.set_duty(self.ch_r, s)
        elif s < 0:
            self.pwm.set_duty(self.ch_r, 0.0)
            if self.speed_dir() > 0:
                time.sleep(0.001)
            self.pwm.set_duty(self.ch_l, -s)
        else:
            self.pwm.set_duty(self.ch_r, 0.0)
            self.pwm.set_duty(self.ch_l, 0.0)
        self.speed = s

    def speed_dir(self):
        return (self.speed > 0) - (self.speed < 0)

    def coast(self):
        self.set_speed(0.0)
        self.enable(False)

    def close(self):
        self.coast()
        for ch in (self.ch_r, self.ch_l):
            self.pwm.enable(ch, False)
        for g in self.en:
            g.close()


class Robot:
    def __init__(self, pwm=None):
        self.pwm = pwm or PWM8()
        self.right = IBT2(self.pwm, **RIGHT)
        self.left = IBT2(self.pwm, **LEFT)

    def enable(self, on=True):
        self.right.enable(on)
        self.left.enable(on)

    def drive(self, left, right):
        """Tank drive: each side -1.0 .. +1.0."""
        self.left.set_speed(left)
        self.right.set_speed(right)

    def stop(self):
        self.drive(0.0, 0.0)

    def close(self):
        self.right.close()
        self.left.close()
        self.pwm.close()


def step(robot, left, right, seconds, label):
    print(f"{label:<26} left {left:+.2f}  right {right:+.2f}")
    robot.drive(left, right)
    time.sleep(seconds)


def main():
    global PWM_FREQ_HZ
    ap = argparse.ArgumentParser()
    ap.add_argument("--max", type=float, default=0.5, help="max test speed 0-1")
    ap.add_argument("--freq", type=int, default=PWM_FREQ_HZ, help="PWM Hz")
    args = ap.parse_args()
    PWM_FREQ_HZ = args.freq
    v = max(0.0, min(1.0, args.max))

    robot = Robot()
    try:
        robot.enable(True)
        step(robot, 0, 0, 1, "Enabled, stopped")
        step(robot, 0, v * 0.6, 2, "Right side forward")
        step(robot, 0, 0, 1, "Stop")
        step(robot, 0, -v * 0.6, 2, "Right side reverse")
        step(robot, 0, 0, 1, "Stop")
        step(robot, v * 0.6, 0, 2, "Left side forward")
        step(robot, 0, 0, 1, "Stop")
        step(robot, -v * 0.6, 0, 2, "Left side reverse")
        step(robot, 0, 0, 1, "Stop")
        print("Ramp both forward")
        for i in range(11):
            s = v * i / 10
            step(robot, s, s, 0.3, "  ramp")
        step(robot, 0, 0, 1, "Stop")
        step(robot, -v * 0.6, v * 0.6, 2, "Spin left")
        step(robot, v * 0.6, -v * 0.6, 2, "Spin right")
        step(robot, 0, 0, 1, "Stop")
    except KeyboardInterrupt:
        pass
    finally:
        robot.close()          # PWM to 0, enables low, channels off
        print("Done - drivers disabled")


if __name__ == "__main__":
    main()

Getting the directions right. I ran the test sequence with the wheels off the ground and filmed it. Each side switched on and off at the right moments, but "both forward" spun the robot in place and the "spin" steps drove it straight. One side was mirrored. Flipping the right side's invert flag to True fixed it, which is the value in the code above. The video made this obvious far faster than watching the wheels live.

failed motor test
failed motor test
working motor test
working motor test

Powering the robot

The motors run from a 12 V (3S) LiPo. A 3S pack sits around 9–12.6 V depending on charge, comfortably inside the IBT-2's 6–27 V supply range. The battery has a single Deans (T-plug) output, and it needs to feed two drivers.

The usual approach is a terminal block or a small power distribution board. This chassis has very little room, so I used plug-in parts instead:

LiPo (Deans) --> Deans Y-splitter --+--> Deans-to-bare-wire lead --> right IBT-2  B+ / B-
                                    +--> Deans-to-bare-wire lead --> left IBT-2   B+ / B-

The Y-splitter puts both drivers in parallel on the battery. Each splitter output plugs into a Deans-to-bare-wire lead, and the bare ends screw into that driver's B+ and B− power terminals. The motors connect to each driver's M+ and M− terminals.

Things worth checking before plugging in the battery for the first time:

  • Polarity at the screw terminals. Deans plugs only fit one way, but the bare-wire ends don't care. Check red goes to B+ and black to B− on both drivers, ideally with a multimeter on the leads before the battery is connected. Reversed polarity is a quick way to destroy an IBT-2.
  • Common ground. The PMOD GND wire also connects the KR260's ground to the battery negative through the IBT-2, which the control signals need.
  • Unplug the Deans connector whenever the robot isn't in use.

No fuse or switch yet. There's nowhere to put them until the new deck plate frees up space. For now, the software does the safety work:

  • The PWM outputs stay low whenever a channel is disabled, so the motors can't run until the server enables them.
  • The server's watchdog stops the motors if commands stop arriving for 0.5 s.
  • Speed ramping avoids sudden current spikes from instant full reverses.
  • --max caps the top speed.
  • Ctrl+C, SIGTERM and every script exit set the duty to 0 and turn the drivers off.

Software can't protect against a short circuit or a wiring fault, though. Once there's room, the plan is an inline fuse on the battery lead and a power switch within easy reach.

Client and server

The client/server split is the same as last time: UDP on port 5005, with the desktop sending commands 20 times a second. The new version sends a left and right speed instead of key names:

client -> server : "D <left> <right> <seq>"   left/right in -1.0 .. 1.0
                   "X"                         stop immediately
server -> client : "S <left> <right> <seq>"   speeds actually applied + echo

With variable speed on a heavier robot, the server needs more safety than before:

  • Watchdog: if no command arrives for 0.5 s, the robot stops. This covers a WiFi drop or a closed laptop.
  • Ramping: speeding up from 0 to full takes 0.5 s, and slowing down is faster. This protects the drivers and gearboxes from instant full reverses.
  • Speed cap: --max limits the top speed on the robot itself, whatever the client sends.
  • One controller at a time: other clients are ignored until the active one goes quiet.
  • Clean shutdown: Ctrl+C or SIGTERM sets the speed to 0 and turns the drivers off.
  • Dry-run mode: --dry-run prints the commands without touching the motors, for testing the network side.

The server runs on the KR260, next to ibt2.py and pwm8.py:

#!/usr/bin/env python3
"""
robot_server.py - UDP drive server for the KR260 robot (Python standard library only).

Runs on the KR260 next to ibt2.py and pwm8.py:
    sudo python3 robot_server.py              # drive the motors
    python3 robot_server.py --dry-run         # no motors, just print commands

Protocol (UDP, ASCII, one line per packet):
    client -> server : "D <left> <right> <seq>"   left/right in -1.0 .. 1.0
                       "X"                         stop immediately
    server -> client : "S <left> <right> <seq>"   speeds actually applied + echo

Safety:
  * Watchdog: no valid packet for WATCHDOG_S seconds -> motors stop.
  * Slew limiting: speed changes are ramped (faster when slowing down) so the
    IBT-2s never see an instant full reverse.
  * Only one client at a time drives the robot; others are ignored until the
    active client goes quiet.
  * Ctrl+C / SIGTERM stop the motors and disable the drivers.
"""
import argparse
import signal
import socket
import time

PORT = 5005
WATCHDOG_S = 0.5      # stop if the client goes quiet this long
LOOP_HZ = 50          # control loop rate
ACCEL_PER_S = 2.0     # max speed increase per second (0 -> full in 0.5 s)
DECEL_PER_S = 5.0     # max speed decrease per second (braking is quicker)
MAX_SPEED = 1.0       # hard cap applied on the robot, whatever the client asks


class DryRunRobot:
    """Stand-in for ibt2.Robot so the network side can be tested without motors."""

    def __init__(self):
        self.last = None

    def enable(self, on=True):
        print(f"[dry-run] drivers {'enabled' if on else 'disabled'}")

    def drive(self, left, right):
        cur = (round(left, 2), round(right, 2))
        if cur != self.last:
            print(f"[dry-run] left {left:+.2f}  right {right:+.2f}")
            self.last = cur

    def close(self):
        print("[dry-run] closed")


def slew(current, target, dt):
    """Move current toward target, accelerating slowly and braking faster."""
    if target == current:
        return current
    slowing = abs(target) < abs(current) or (target * current < 0)
    step = (DECEL_PER_S if slowing else ACCEL_PER_S) * dt
    if abs(target - current) <= step:
        return target
    return current + step if target > current else current - step


def parse(data):
    """Return ('D', left, right, seq), ('X',) or None for anything malformed."""
    try:
        parts = data.decode("ascii", "strict").split()
    except UnicodeDecodeError:
        return None
    if parts == ["X"]:
        return ("X",)
    if len(parts) == 4 and parts[0] == "D":
        try:
            left, right, seq = float(parts[1]), float(parts[2]), int(parts[3])
        except ValueError:
            return None
        if left != left or right != right:          # NaN check
            return None
        clamp = lambda v: max(-MAX_SPEED, min(MAX_SPEED, v))
        return ("D", clamp(left), clamp(right), seq)
    return None


def main():
    global MAX_SPEED
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=PORT)
    ap.add_argument("--dry-run", action="store_true", help="no motors, print commands")
    ap.add_argument("--max", type=float, default=MAX_SPEED,
                    help="hard speed cap 0-1 (default 1.0)")
    args = ap.parse_args()
    MAX_SPEED = max(0.0, min(1.0, args.max))

    if args.dry_run:
        robot = DryRunRobot()
    else:
        from ibt2 import Robot          # needs pwm8.py + root
        robot = Robot()

    stop_flag = {"stop": False}
    signal.signal(signal.SIGTERM, lambda *_: stop_flag.update(stop=True))

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(("0.0.0.0", args.port))
    sock.settimeout(1.0 / LOOP_HZ)

    target = [0.0, 0.0]
    current = [0.0, 0.0]
    client = None
    last_rx = 0.0
    timed_out = True
    last_t = time.monotonic()

    print(f"Robot server listening on UDP {args.port} "
          f"(max speed {MAX_SPEED:.2f}{', DRY RUN' if args.dry_run else ''})")
    robot.enable(True)
    robot.drive(0.0, 0.0)
    try:
        while not stop_flag["stop"]:
            # ---- receive (at most one loop period of waiting) -------------
            try:
                data, addr = sock.recvfrom(128)
            except socket.timeout:
                data = None
            now = time.monotonic()

            if data is not None:
                cmd = parse(data)
                active = client is None or addr == client or now - last_rx > WATCHDOG_S
                if cmd is not None and active:
                    if addr != client:
                        print(f"Client connected: {addr[0]}:{addr[1]}")
                        client = addr
                    last_rx = now
                    if timed_out:
                        timed_out = False
                    if cmd[0] == "X":
                        target = [0.0, 0.0]
                        current = [0.0, 0.0]        # immediate stop
                        seq = -1
                    else:
                        target = [cmd[1], cmd[2]]
                        seq = cmd[3]
                    reply = f"S {current[0]:.3f} {current[1]:.3f} {seq}"
                    sock.sendto(reply.encode("ascii"), addr)

            # ---- watchdog ---------------------------------------------------
            if not timed_out and now - last_rx > WATCHDOG_S:
                timed_out = True
                target = [0.0, 0.0]
                print("Watchdog: no commands - stopping")

            # ---- slew + apply ----------------------------------------------
            dt = min(now - last_t, 0.1)
            last_t = now
            current = [slew(current[0], target[0], dt), slew(current[1], target[1], dt)]
            robot.drive(current[0], current[1])
    except KeyboardInterrupt:
        pass
    finally:
        robot.drive(0.0, 0.0)
        robot.close()
        sock.close()
        print("Server stopped - motors off")


if __name__ == "__main__":
    main()

The PyGame client runs on the desktop. It shows the link status, latency, and both the commanded and applied speed for each side.

Gamepad support. My first version read the controller through pygame's basic joystick API. My Xbox controller worked elsewhere but couldn't drive the robot. The likely causes: that API numbers sticks and buttons differently depending on the OS and on whether the controller uses USB, the Xbox wireless adapter or Bluetooth, and it ignores the controller whenever the window isn't focused. Switching fixed it. The final version uses SDL's GameController API (pygame._sdl2.controller), which gives Xbox controllers a fixed layout everywhere, and sets SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS. The window also shows live stick and trigger values, which makes problems easy to spot.

Input Keyboard Xbox controller
Drive W/S or Up/Down Left stick, or RT/LT as analog throttle
Steer / spin A/D or Left/Right Left stick left/right
Speed limit 1–9, 0 (10–100%) RB / LB (±10%)
Emergency stop Space (hold) B (hold)
Quit Esc (sends stop)
#!/usr/bin/env python3
"""
robot_client.py - PyGame remote control for the KR260 robot.

Run on the desktop (pip install pygame):
    python3 robot_client.py <kria-ip> [--port 5005]

Keyboard
    W / Up        forward            S / Down     reverse
    A / Left      turn left          D / Right    turn right
    W+A, W+D ...  arc turns          A or D alone spin in place
    1 - 9, 0      speed limit 10 % ... 90 %, 100 %
    Space         emergency stop (held = stays stopped)
    Esc / close   quit (sends stop)

Xbox controller (any SDL-recognised gamepad)
    Left stick    up/down = forward/reverse, left/right = steer
    RT / LT       forward / reverse throttle (analog)
    B             emergency stop (held)
    RB / LB       speed limit +10 % / -10 %
    Works over USB, the Xbox wireless adapter or Bluetooth; it can be
    plugged in before or after the client starts.

Sends "D <left> <right> <seq>" 20 times a second over UDP; the server stops
the motors if packets stop arriving for 0.5 s.
"""
import argparse
import os
import select
import socket
import time

# Let the pad keep working even when the window is not focused.
os.environ.setdefault("SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS", "1")
import pygame  # noqa: E402

try:
    from pygame._sdl2 import controller as sdl_controller
except ImportError:                      # very old pygame: fall back to raw joystick
    sdl_controller = None

SEND_HZ = 20
TURN_GAIN = 0.6        # how hard W+A / W+D arcs
SPIN_GAIN = 0.8        # spin-in-place speed relative to the limit
DEADZONE = 0.15        # stick / trigger deadzone (Xbox sticks rest near 0.05)
LINK_TIMEOUT = 0.5


def mix(forward, turn, limit):
    """forward/turn in -1..1 -> (left, right) in -limit..limit (tank mix)."""
    if abs(forward) < 1e-3:
        left, right = turn * SPIN_GAIN, -turn * SPIN_GAIN
    else:
        left, right = forward + turn * TURN_GAIN, forward - turn * TURN_GAIN
    biggest = max(1.0, abs(left), abs(right))     # keep the turn ratio when clamping
    return left / biggest * limit, right / biggest * limit


def dz(v):
    """Apply deadzone and rescale so output still reaches +-1."""
    if abs(v) < DEADZONE:
        return 0.0
    return (abs(v) - DEADZONE) / (1 - DEADZONE) * (1 if v > 0 else -1)


class Gamepad:
    """Wraps an SDL GameController (standard Xbox layout) or a raw joystick."""

    def __init__(self):
        self.dev = None
        self.kind = None
        self.name = ""
        if sdl_controller is not None:
            sdl_controller.init()
        self.scan()

    def scan(self):
        self.dev, self.kind, self.name = None, None, ""
        for i in range(pygame.joystick.get_count()):
            if sdl_controller is not None and sdl_controller.is_controller(i):
                self.dev = sdl_controller.Controller(i)
                self.kind, self.name = "controller", self.dev.name
                break
        else:
            if pygame.joystick.get_count():
                self.dev = pygame.joystick.Joystick(0)
                self.dev.init()
                self.kind, self.name = "joystick", self.dev.get_name()
        if self.dev is not None:
            print(f"Gamepad: {self.name} ({self.kind} API)")

    def handle_event(self, event):
        """Hot-plug + button presses. Returns +1/-1 to change the speed limit."""
        if event.type in (pygame.JOYDEVICEADDED, pygame.CONTROLLERDEVICEADDED,
                          pygame.JOYDEVICEREMOVED, pygame.CONTROLLERDEVICEREMOVED):
            self.scan()
        elif self.kind == "controller" and event.type == pygame.CONTROLLERBUTTONDOWN:
            if event.button == pygame.CONTROLLER_BUTTON_RIGHTSHOULDER:
                return +1
            if event.button == pygame.CONTROLLER_BUTTON_LEFTSHOULDER:
                return -1
        elif self.kind == "joystick" and event.type == pygame.JOYBUTTONDOWN:
            if event.button == 5:      # RB on most Xbox raw mappings
                return +1
            if event.button == 4:      # LB
                return -1
        return 0

    def read(self):
        """Returns (forward, turn, stop, raw_text) with forward/turn in -1..1."""
        if self.dev is None:
            return 0.0, 0.0, False, "no gamepad"
        try:
            if self.kind == "controller":
                ax = lambda a: self.dev.get_axis(a) / 32767.0
                lx = ax(pygame.CONTROLLER_AXIS_LEFTX)
                ly = ax(pygame.CONTROLLER_AXIS_LEFTY)
                lt = ax(pygame.CONTROLLER_AXIS_TRIGGERLEFT)     # 0..1
                rt = ax(pygame.CONTROLLER_AXIS_TRIGGERRIGHT)    # 0..1
                stop = bool(self.dev.get_button(pygame.CONTROLLER_BUTTON_B))
            else:
                lx, ly = self.dev.get_axis(0), self.dev.get_axis(1)
                lt = rt = 0.0
                stop = self.dev.get_numbuttons() > 1 and bool(self.dev.get_button(1))
        except pygame.error:              # unplugged mid-read
            self.scan()
            return 0.0, 0.0, False, "gamepad lost"
        trig = dz(max(rt, 0.0)) - dz(max(lt, 0.0))
        stick = -dz(ly)                   # stick up is negative in SDL
        forward = trig if abs(trig) > abs(stick) else stick
        turn = dz(lx)
        raw = f"LX {lx:+.2f}  LY {ly:+.2f}  LT {lt:.2f}  RT {rt:.2f}" + ("  B" if stop else "")
        return forward, turn, stop, raw


def draw_bar(screen, font, x, label, cmd, applied):
    top, height, width = 90, 250, 70
    mid = top + height // 2
    pygame.draw.rect(screen, (60, 60, 70), (x, top, width, height), border_radius=6)
    pygame.draw.line(screen, (120, 120, 130), (x, mid), (x + width, mid), 1)
    # commanded (outline) and applied by the robot (filled)
    for value, filled in ((cmd, False), (applied, True)):
        h = int(abs(value) * height / 2)
        rect = (x + 8, mid - h, width - 16, h) if value >= 0 else (x + 8, mid, width - 16, h)
        colour = (80, 200, 120) if value >= 0 else (230, 120, 80)
        pygame.draw.rect(screen, colour, rect, 0 if filled else 2, border_radius=4)
    screen.blit(font.render(label, True, (220, 220, 220)), (x + 8, top + height + 8))
    screen.blit(font.render(f"{applied:+.2f}", True, (220, 220, 220)), (x + 8, top + height + 30))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("host", help="KR260 IP address")
    ap.add_argument("--port", type=int, default=5005)
    args = ap.parse_args()
    server = (args.host, args.port)

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setblocking(False)

    pygame.init()
    screen = pygame.display.set_mode((440, 470))
    pygame.display.set_caption(f"KR260 robot - {args.host}:{args.port}")
    font = pygame.font.SysFont(None, 24)
    small = pygame.font.SysFont(None, 20)
    big = pygame.font.SysFont(None, 32)
    clock = pygame.time.Clock()
    pad = Gamepad()

    limit = 0.5
    seq = 0
    sent_at = {}
    rtt_ms = None
    last_ack = 0.0
    applied = (0.0, 0.0)
    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                elif pygame.K_1 <= event.key <= pygame.K_9:
                    limit = (event.key - pygame.K_0) / 10
                elif event.key == pygame.K_0:
                    limit = 1.0
            step = pad.handle_event(event)
            if step:
                limit = round(min(1.0, max(0.1, limit + 0.1 * step)), 1)

        keys = pygame.key.get_pressed()
        forward = float((keys[pygame.K_w] or keys[pygame.K_UP]) - (keys[pygame.K_s] or keys[pygame.K_DOWN]))
        turn = float((keys[pygame.K_d] or keys[pygame.K_RIGHT]) - (keys[pygame.K_a] or keys[pygame.K_LEFT]))
        estop = bool(keys[pygame.K_SPACE])

        p_fwd, p_turn, p_stop, pad_raw = pad.read()
        if forward == 0:
            forward = p_fwd
        if turn == 0:
            turn = p_turn
        estop = estop or p_stop

        if estop:
            left = right = 0.0
            msg = "X"
        else:
            left, right = mix(forward, turn, limit)
            seq += 1
            msg = f"D {left:.3f} {right:.3f} {seq}"
            sent_at[seq] = time.monotonic()
        try:
            sock.sendto(msg.encode("ascii"), server)
        except OSError:
            pass                                   # network down: keep the UI alive

        # wait briefly for the reply (keeps the latency figure honest), then drain
        select.select([sock], [], [], 0.015)
        while True:
            try:
                data, _ = sock.recvfrom(128)
            except (BlockingIOError, OSError):
                break
            parts = data.decode("ascii", "replace").split()
            if len(parts) == 4 and parts[0] == "S":
                try:
                    applied = (float(parts[1]), float(parts[2]))
                    ack = int(parts[3])
                except ValueError:
                    continue
                last_ack = time.monotonic()
                if ack in sent_at:
                    rtt_ms = (last_ack - sent_at[ack]) * 1000
        for old in [s for s in sent_at if s < seq - 50]:
            del sent_at[old]

        # ---- draw ---------------------------------------------------------
        linked = time.monotonic() - last_ack < LINK_TIMEOUT
        screen.fill((25, 25, 32))
        status = "LINKED" if linked else "NO LINK"
        colour = (80, 220, 120) if linked else (230, 80, 80)
        screen.blit(big.render(status, True, colour), (20, 15))
        rtt = f"{rtt_ms:.0f} ms" if (linked and rtt_ms is not None) else "--"
        screen.blit(font.render(f"latency {rtt}", True, (200, 200, 200)), (20, 50))
        screen.blit(big.render(f"limit {int(round(limit * 100))}%", True, (230, 230, 120)), (270, 15))
        if estop:
            screen.blit(big.render("STOP", True, (240, 60, 60)), (185, 200))
        draw_bar(screen, font, 60, "LEFT", left, applied[0])
        draw_bar(screen, font, 310, "RIGHT", right, applied[1])
        pad_name = pad.name[:40] if pad.dev is not None else "no gamepad detected"
        screen.blit(small.render(f"pad: {pad_name}", True, (150, 150, 220)), (20, 405))
        screen.blit(small.render(pad_raw, True, (150, 150, 220)), (20, 423))
        screen.blit(small.render("WASD/stick/triggers drive  1-0, LB/RB limit  Space/B stop",
                                 True, (150, 150, 150)), (20, 447))
        pygame.display.flip()
        clock.tick(SEND_HZ)

    for _ in range(3):                             # make sure the robot stops
        try:
            sock.sendto(b"X", server)
        except OSError:
            pass
    pygame.quit()


if __name__ == "__main__":
    main()

Running it:

# on the KR260
sudo python3 robot_server.py --max 0.6

# on the desktop
pip install pygame
python3 robot_client.py <kria-ip>

Conclusion and next steps

The robot now has real speed control. The FPGA generates the PWM, Python just writes speed values into registers, and the robot drives on the floor with a keyboard or an Xbox controller. Moving PWM into the FPGA was worth the Vivado detour: the timing is exact whatever the CPU is doing, and the same core still has four spare channels for servos.

Two lessons from this round:

  • Know the clock your AXI blocks actually run on. Mine is clk_wiz_0/clk_out2 at 200 MHz, not pl_clk0.
  • When the hardware doesn't behave, read the registers before blaming the code.

Next up:

  • A deck plate. Everything is held down loosely right now. The chassis has a usable area of 15.5 × 13.5 cm on its top plate, and the KR260's mounting holes are 11.5 × 13.5 cm apart. The plan is a 3 mm aluminum plate on standoffs, laser-cut with holes for the chassis, the KR260 and a camera bracket. The PMOD jumper wires also need strain relief before they start shaking loose.
  • A fuse and a power switch on the LiPo lead, once the plate makes room for them.
  • An Intel RealSense D435i depth camera at the front for navigation. It has a standard 1/4-20 tripod thread and two M3 holes, so it can sit on a small bracket on the deck.
  • Reading the servo or encoder feedback in the FPGA, using the same approach as the PWM core.

Here is a sample of the robot driving robot driving with variable speed using IBT2 motor drivers

Robot driving using xbox controller robot driving using controller

fpgakria kr 260robotics

← All posts