Skip to main content

USB Serial Control (CDC)

The Type-C port on the Beetle S1 is the chip's native USB. Plug it into a computer and the computer sees two devices at once: a USB drive (holding firmware, apps and assets) and a virtual serial port (CDC). This serial port needs no driver at all — on the device side it is simply the ordinary sys.stdin / sys.stdout. Read a line, write a line, and one round of communication with the computer is done.

Works as soon as you plug it in

Driver-free on Windows 10+ / macOS / Linux. CDC runs over USB, so whatever baud rate you enter makes no difference.

Read a line, write a line

sys.stdin.readline() reads a command sent by the computer; print() sends data back to the computer.

Shares its buffer with the REPL

Bytes arriving over USB go into the same input buffer as the REPL — when your program is not running, what you type is handled by the REPL.

Type-C provides two devices at once​

Beetle S1 USB-CDC serial interface diagram

Device seen by the computerPurposeWhat it is on the device side
USB drive (MSC)Holds firmware, apps, images and config filesFAT partition, mounted at /sd
Serial port (CDC)Send commands, receive logs, debugsys.stdin (read) / sys.stdout (write)

This page only covers the serial port (CDC). The two devices do not interfere with each other: writing files goes over the USB drive path, transferring data goes over the serial path.

Hardware and interface​

ItemValue
InterfaceType-C, chip's native USB (TinyUSB)
Device-side objectssys.stdin (read), sys.stdout (write)
Driver requiredNo (driver-free on Windows 10 and above, macOS and mainstream Linux)
Baud rateIgnored. CDC runs on the USB full-speed bus; entering 115200 in a serial terminal only avoids being rejected
Input bufferUSB-CDC and the UART0 REPL share the same input buffer
When the host is closed / not connectedWritten data is simply dropped (the firmware only sends while a CDC connection exists)
Single write timeoutAt most 500 milliseconds, after which the remaining data is dropped; the program is never stuck forever
Interrupt characterCtrl-C (0x03) is turned directly into KeyboardInterrupt by the firmware — your program never sees this byte

Quick start​

Paste the lines below straight into the REPL, or put them in boot.py on the SD card:

import sys

print("Beetle S1 ready") # the serial terminal on the computer shows this line immediately

while True:
line = sys.stdin.readline() # block until the computer sends one whole line
print("got:", line)

What you'll see: send hello from the serial terminal on your computer with "send newline" enabled, and the device immediately echoes got: hello.

API reference​

There is no extra cdc module on the device side: it uses the standard MicroPython sys.stdin / sys.stdout. The interfaces below have all been verified in the official App.

Read a line sys.stdin.readline()​

line = sys.stdin.readline()

Reads one whole line from the computer and returns a str.

  • Blocking: while the buffer holds no newline, this call waits indefinitely and the code after it never runs.
  • The returned string includes the trailing newline, so it is usually followed by a .strip().
  • The serial terminal must have "send newline" enabled (\n or \r\n), otherwise readline() never returns.
  • After your program exits and control returns to the REPL, whatever you type into the serial port is consumed by the REPL and no longer reaches your code.

Write a line print() / sys.stdout.write()​

print("data") # newline added automatically
sys.stdout.write("data\n") # no newline added, write \n yourself

Sends data to the computer and returns the number of characters written (print() returns None).

  • Serial terminals usually refresh line by line, so remember to include \n after each message.
  • Data is dropped when the host is not connected, with no error — if debug logs do not show up, first check that the serial port is really open.
  • A single write waits at most 500 milliseconds: if the host port is open but nobody reads it and the buffer fills up, the rest of the data is discarded instead of waiting forever.
  • This is also the REPL's output channel, so printing while your program runs shows up on the same serial port.

Non-blocking reads select.poll()​

readline() blocks. If the device also has to keep rendering light effects and reading buttons, use select.poll() to ask "is there any data?" first:

import select
import sys

poll = select.poll()
poll.register(sys.stdin, select.POLLIN)

events = poll.poll(0) # argument is the timeout in milliseconds; 0 = return immediately
if events:
cmd = sys.stdin.readline().strip()
print("got:", cmd)

This is the pattern used by the official App: call poll(0) in the main loop, only readline() when data is available, and keep rendering frames when there is none.

Interrupt Ctrl-C​

A Ctrl-C received over USB (byte 0x03) is turned directly into a keyboard interrupt by the firmware, which is why a loop such as while True: sys.stdin.readline() can be stopped with Ctrl-C:

try:
while True:
cmd = sys.stdin.readline().strip()
except KeyboardInterrupt:
print("stopped")

Note that this byte never appears in the readline() return value, so you cannot handle it as an ordinary command.

Common pitfalls​

PitfallCause and the right approach
Command sent but the device does nothing"Send newline" not enabled in the serial terminal → readline() needs a newline before it returns
The program appears "frozen"Execution reached readline() and is waiting for input → use non-blocking poll() when you want to receive commands while running
Want to use Ctrl-C as a commandThe firmware swallows it as a keyboard interrupt → use ESC or a custom string (such as quit) as the exit command
print() output is emptyThe host serial port is not open → data is only sent to a connected CDC and dropped otherwise
Characters lost under heavy logging500-millisecond single-write timeout → log less often, or write logs to a file
Typed characters turn into REPL errorsYour program has exited and the REPL took over input → run your script again
Garbled non-ASCII textThe device sends UTF-8 bytes → switch the serial terminal to UTF-8 encoding
The serial terminal will not connect / baud rate errorBaud rate has no effect on CDC → any value such as 115200 works; if it still will not connect, try another data cable (not a charge-only cable)

More recipes​

Command dispatch (the most common skeleton)​

import sys

while True:
cmd = sys.stdin.readline().strip().lower()
if not cmd:
continue
if cmd == "ping":
print("pong")
elif cmd == "ver":
print("Beetle S1")
elif cmd == "quit":
print("bye")
break
else:
print("unknown command:", cmd)

Sending commands from Python on the computer​

Install pyserial on the host (pip install pyserial) and replace COM3 with your port name (on macOS / Linux it looks like /dev/tty.usbmodem*):

import serial
import time

port = serial.Serial('COM3', 115200, timeout=1)
time.sleep(0.5) # wait for the device-side CDC to be ready

port.write(b'ping\n') # note: must end with a newline
print(port.readline().decode().strip())

port.close()

Debug logging with a single switch​

import sys

DEBUG = True


def log(*args):
if DEBUG:
print("[log]", *args)

log() goes over the same CDC and is visible directly in the serial terminal; turn DEBUG off and it goes completely silent.

Complete example​

Beetle S1 apps live on the SD card under /sd/apps/<app-directory>/, with boot.py as the entry point. Put the following into /sd/apps/my-cdc-app/boot.py: non-blocking command reception, ping echo, beep triggering the buzzer, and quit to exit.

import select
import sys
import time

import beep

poll = select.poll()
poll.register(sys.stdin, select.POLLIN)

print("my-cdc-app started, type help")

running = True
while running:
events = poll.poll(0)
if events:
cmd = sys.stdin.readline().strip().lower()
if cmd == "help":
print("commands: ping / beep / help / quit")
elif cmd == "ping":
print("pong")
elif cmd == "beep":
beep.tone(2000, 200)
print("beep!")
elif cmd == "quit":
print("bye")
running = False
elif cmd:
print("unknown command:", cmd)

time.sleep(0.02) # light-effect rendering and similar work goes here

beep.stop()

Troubleshooting​

SymptomCause / fix
No serial port appears on the computerA charge-only cable was used (no data wires) → try a data cable; or try another USB port / another computer to narrow it down
The port exists but sending anything does nothing"Send newline" not enabled in the serial terminal → enable it and send again
Device logs arrive, but commands have no effectThe program has exited to the REPL and the REPL took over input → run the script again
Repeated >>> prompts appearYou interrupted into the REPL prompt → press Ctrl-D to soft-reset, then run the script
Output is missing or lines are droppedPrinting too often hits the 500-millisecond write timeout → slow down the rate or write to a file
OSError / crash on the device sideThe read was interrupted or the device was hot-plugged → wrap the main loop in try/except
Non-ASCII text turns into question marksThe serial terminal is not set to UTF-8 → switch it to UTF-8 encoding

Related modules: Buzzer (beep) · Button Control (button) · LED Control (WS2812) · Display (ST7789)

AI usage (coming soon)​

Soon you will not have to write the command-dispatch skeleton yourself, or memorise how poll() works: describe the interaction you want in plain language and the Agent will follow the APIs on this page to generate a complete program that runs on the Beetle S1.

For example, just tell it:

When the computer sends beep 2000 200 over the serial port, sound the buzzer at that frequency for that long; when it sends img on, show an image; when it sends quit, exit.

It will then combine sys.stdin, select.poll(), beep and the display interface into a working program and place it on the SD card under /sd/apps/.

Agent entry (coming soon)

The entry link will go here. Once it is live, one click takes you straight to describing the app you want.