1. Introduction: Why "PIO" is Needed for Quantum Operations
Controlling qubits, particularly Exchange-only qubits using spin, requires extremely sharp and accurate pulses that involve "setting a pin to HIGH for only a few nanoseconds and immediately returning it to LOW."
If you try to do this with a standard microcontroller (CPU), background OS operations and timer interrupts interfere, causing "jitter" in the pulse width.
This is where the PIO (Programmable I/O) feature of the Raspberry Pi RP2040 comes into play.

Gemini is now so good that I can't even understand what it's saying, but since it worked when I ran it, I'm posting the result.
2. Implementation This Time: A Trinity Control System
The code this time achieves jitter-free pulse control through the coordination of three roles.
① PIO Assembly (pulse_logic.h)
A tiny program that runs on its own state machine without relying on the CPU.
pull block: Waits motionlessly until data arrives from the Mac.out pins, 2: Instantly turns ON the specified pins (J12/J23).jmp x--: Loops in place for the specified number of clocks (e.g., 14clk) to burn time.push block: Reports completion to the CPU.
#ifndef PULSE_LOGIC_H
#define PULSE_LOGIC_H
#include "hardware/pio.h"
static const uint16_t pulse_generator_instructions[] = {
0x80a0, // 0: pull block (Wait for commands from Mac)
0x6002, // 1: out pins, 2 (Pin ON: J12=1, J23=2)
0x603e, // 2: out x, 30 (Load clock count)
0xa0c1, // 3: mov isr, x (Copy current value for reply)
0x0044, // 4: jmp x-- 4 (Count loop)
0xa042, // 5: mov pins, null (Pin OFF)
0x8020, // 6: push block (Send counted value back to Mac)
};
static const struct pio_program pulse_generator_program = {
.instructions = pulse_generator_instructions,
.length = 7,
.origin = -1,
};
static inline void pulse_generator_program_init(PIO pio, uint sm, uint offset, uint pin) {
pio_sm_config c = pio_get_default_sm_config();
sm_config_set_out_pins(&c, pin, 2);
// Reduce clock by 1/4 to ensure capture even at 3clk (31.25MHz)
// This results in a minimum pulse width of approximately 32ns.
sm_config_set_clkdiv(&c, 4.0f);
pio_gpio_init(pio, pin);
pio_gpio_init(pio, pin + 1);
pio_sm_set_consecutive_pindirs(pio, sm, pin, 2, true);
pio_sm_init(pio, sm, offset, &c);
pio_sm_set_enabled(pio, sm, true);
}
#endif② XIAO C++ Logic (sketch_feb18a.ino)
Acts as the "bridge" between the Mac (Python) and PIO, but incorporates quantum gate-specific ingenuity.
- 1-byte handshake: To prevent the 4-byte command sent rapidly from the Mac from being dropped mid-transmission, an echo-back (sending it back) is performed after receiving each byte to ensure synchronization.
- Thorough PIO Refresh: When performing continuous gate operations, remnants of previous commands may remain inside the PIO. Therefore, we kill the state machine once right before execution and force-jump the program counter to the beginning (
pio_sm_exec) to start the pulse from a "clean state" every time.
#include "pulse_logic.h"
// Defined as global variables (accessible from anywhere)
PIO pio = pio0;
uint sm_gen = 0;
uint off_gen; // Key point: declare here
void setup() {
Serial.begin(115200);
while (!Serial); // Wait for connection with Mac
// Load PIO program and save location to off_gen
off_gen = pio_add_program(pio, &pulse_generator_program);
pulse_generator_program_init(pio, sm_gen, off_gen, 26); // D0 pin
}
void loop() {
// 1. Command Reception (Wait for 4 bytes)
if (Serial.available() > 0) {
uint32_t cmd = 0;
// Assemble byte by byte with echo-back
for (int i = 0; i < 4; i++) {
while (Serial.available() == 0);
uint8_t b = Serial.read();
cmd |= ((uint32_t)b << (i * 8));
Serial.write(b); // Echo-back to Mac
}
// 2. Thorough PIO Refresh
// Eliminate possibility of stopping midway during previous execution
pio_sm_set_enabled(pio, sm_gen, false);
pio_sm_clear_fifos(pio, sm_gen);
pio_sm_restart(pio, sm_gen);
// Forcefully jump instruction execution position to start of program (off_gen)
pio_sm_exec(pio, sm_gen, pio_encode_jmp(off_gen));
pio_sm_set_enabled(pio, sm_gen, true);
// 3. Inject Pulse Command
pio_sm_put_blocking(pio, sm_gen, cmd);
// 4. Wait for Completion Report from PIO
uint32_t result = pio_sm_get_blocking(pio, sm_gen);
// 5. Send Final Result
Serial.write((char*)&result, 4);
Serial.flush();
}
}③ Python Script (test.py)
Serves as the user interface and debug log output.
- Constructs packets at the binary level and monitors communication with the XIAO without any bit errors.
- Calculates the "Ratio" (ratio of theoretical value to measured value) to verify if the hardware is operating correctly.
import serial
import struct
import time
import binascii
SERIAL_PORT = '/dev/cu.usbmodem101'
BAUD_RATE = 115200
def run_quantum_gate():
try:
ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1.0)
time.sleep(2)
ser.reset_input_buffer()
print(f"✅ Connected to {SERIAL_PORT}")
except Exception as e:
print(f"❌ Error: {e}")
return
def send_pulse_debug(p_type, clks, step_name):
print(f"\n--- Executing {step_name} ---")
# Packing and displaying command value
cmd_val = (clks << 2) | p_type
cmd_bytes = struct.pack('<I', cmd_val)
print(f" [Ready to Send] Value: {cmd_val} (Hex: {binascii.hexlify(cmd_bytes)})")
# Send/receive byte by byte (handshake)
echoed_bytes = bytearray()
for i, b in enumerate(cmd_bytes):
ser.write(bytes([b]))
ser.flush()
# Wait for echo from XIAO
r = ser.read(1)
if r:
print(f" [Byte {i}] Sent: 0x{b:02x} -> Received (Echo): 0x{r[0]:02x}")
echoed_bytes.append(r[0])
else:
print(f" [Byte {i}] ❌ No echo received from XIAO")
return None
# Receive PIO execution result (Measured value)
print(" [Waiting for PIO] Waiting for execution completion report...")
res_bytes = ser.read(4)
if len(res_bytes) == 4:
measured = struct.unpack('<I', res_bytes)[0]
print(f" [Complete] Measured: {measured} clk")
return measured
else:
print(f" [Error] Execution result did not arrive as 4 bytes (Received: {len(res_bytes)} bytes)")
return None
# Sequence execution
h_gate = [("H-Step 1", 1, 3), ("H-Step 2", 2, 14), ("H-Step 3", 1, 3)]
for name, p_type, clk in h_gate:
m = send_pulse_debug(p_type, clk, name)
if m is not None:
print(f"✅ {name}: Success (Ratio: {m/clk:.3f})")
else:
print(f"❌ {name}: Failed")
break # Stop on failure
ser.close()
if __name__ == "__main__":
run_quantum_gate()3. Experimental Results: Reproduction of the Hadamard Gate
What was tested this time was the sequence of the Hadamard (H) gate, composed solely of Exchange interactions.
- Step 1 (J12): 3 clk (approx. 96ns)
- Step 2 (J23): 14 clk (approx. 448ns)
- Step 3 (J12): 3 clk (approx. 96ns) *When clkdiv=4.0, driven at 125MHz*
Encoding is required to fully digitally operate semiconductor qubits. The encoding of the H gate is written in this article.
Part 2: Weaving the Ideal H Gate with a Tetrahedron - The Geometry of Gate Synthesis in Exchange-only Qubits
[Contribution] Weaving the Ideal H Gate with a Tetrahedron - Gate Synthesis of Exchange-only Qubits](/post/3891)
Additionally, I created a video about logical qubit operations.
https://x.com/MinatoYuichiro/status/2019195946333253975
--- Executing H-Step 1 ---
[Ready to Send] Value: 13 (Hex: b'0d000000')
[Byte 0] Sent: 0x0d -> Received (Echo): 0x0d
[Byte 1] Sent: 0x00 -> Received (Echo): 0x00
[Byte 2] Sent: 0x00 -> Received (Echo): 0x00
[Byte 3] Sent: 0x00 -> Received (Echo): 0x00
[Waiting for PIO] Waiting for execution completion report...
[Complete] Measured: 3 clk
✅ H-Step 1: Success (Ratio: 1.000)
--- Executing H-Step 2 ---
[Ready to Send] Value: 58 (Hex: b'3a000000')
[Byte 0] Sent: 0x3a -> Received (Echo): 0x3a
[Byte 1] Sent: 0x00 -> Received (Echo): 0x00
[Byte 2] Sent: 0x00 -> Received (Echo): 0x00
[Byte 3] Sent: 0x00 -> Received (Echo): 0x00
[Waiting for PIO] Waiting for execution completion report...
[Complete] Measured: 14 clk
✅ H-Step 2: Success (Ratio: 1.000)
--- Executing H-Step 3 ---
[Ready to Send] Value: 13 (Hex: b'0d000000')
[Byte 0] Sent: 0x0d -> Received (Echo): 0x0d
[Byte 1] Sent: 0x00 -> Received (Echo): 0x00
[Byte 2] Sent: 0x00 -> Received (Echo): 0x00
[Byte 3] Sent: 0x00 -> Received (Echo): 0x00
[Waiting for PIO] Waiting for execution completion report...
[Complete] Measured: 3 clk
✅ H-Step 3: Success (Ratio: 1.000)In the execution log, the Measured values matched the Target perfectly (Ratio 1.000) in all steps.
This means that the quantum gate recipe sent from the Mac was executed at the physical layer with zero clock error.
4. Challenging Limits: 250MHz Overclocking
After achieving "logical success (Ratio 1.000)," the next challenge was breaking the hardware limits.
The rated speed of the RP2040 is 125MHz, but in the world of qubit control, higher pulse width resolution is always advantageous.
Therefore, we boosted the internal voltage from 1.1V to 1.2V, set the system clock to double at 250MHz. Furthermore, by setting the PIO divider ratio to 1.0 (direct connection), we tightened the weight of one clock from 32ns down to just 4ns.
5. Suspicion: Is It "Really" Physically Faster?
Changing software configuration values is instantaneous, but has the clock actually doubled in speed as a physical phenomenon inside the chip?
To confirm this, we used Python's high-precision timer (time.perf_counter) to run a benchmark measuring "how many seconds it takes to execute 100 million clocks of pulses."
- If it failed (stayed at rated speed): It would take approx. 3.2 seconds.
- If it succeeded (driven at 250MHz): It should finish in approx. 0.4 seconds.
6. Shocking Measurement Results: Proof of 4.01ns
Immediately after pressing the execute button, the result returned instantly.
⏱ Execution Time: 0.400779 seconds
📏 Estimated Time per Clock: 4.01 ns
The difference from the theoretical value of 4.00ns is only 0.01ns. This is irrefutable proof that "the PIO is physically running at 250MHz."
It was the moment a 1,000-yen chip completely dominated the fleeting instant where light travels only 1.2 meters.
7. Summary: The "Future of Quantum Control" You Can Get for 1,000 Yen
Normally, controlling pulses with this level of nanosecond precision requires an AWG (Arbitrary Waveform Generator) costing millions of yen.
However, by mastering the RP2040's PIO and combining robust synchronization logic (handshake) with overclocking, we were able to self-build the "heart of the controller" that manipulates qubits with just a 1,000-yen chip.
In the darkness where the "shape of electricity" is invisible, we reached the world of 4ns through dialogue between Python and PIO. From here on out, we will finally enter the phase of flowing these pulses into actual physical quantum devices to manipulate spins.