# NuttX on ESP32-C3: Turn a $5 Microcontroller into a Tiny Unix Server

*Running a blog on a chip smaller than your thumb*

---

## What Is This?

Imagine taking a $5 microcontroller (the **ESP32-C3**) — a chip normally used to blink LEDs or read sensors — and running a **real Unix-like operating system** on it. One that can:

- Serve web pages over WiFi
- Accept SSH connections so you can log in remotely
- Store files in a real filesystem with folders
- Run multiple programs at once

That's what **NuttX** does. It's an operating system for tiny computers (microcontrollers), but unlike most microcontroller software, it speaks **Unix** — the same language as Linux, FreeBSD, and macOS.

---

## What's a Microcontroller? (vs. Your Laptop)

| Your Laptop (x86_64) | ESP32-C3 Microcontroller |
|----------------------|-------------------------|
| **CPU**: Multi-core, 3+ GHz | **CPU**: Single core, 160 MHz (RISC-V) |
| **RAM**: 8–64 GB | **RAM**: 400 KB (yes, kilobytes!) |
| **Storage**: 256 GB+ SSD | **Storage**: 4 MB Flash (like an SD card built-in) |
| **OS**: Linux/FreeBSD/Windows | **OS**: NuttX (or nothing at all) |
| **Power**: 30–100 watts | **Power**: ~0.1 watts |
| **Size**: Big | **Size**: Postage stamp |

**Key difference**: Your laptop runs programs from disk into RAM. The ESP32-C3 runs programs **directly from Flash memory** (XIP — eXecute In Place). No loading step.

---

## What Is NuttX? (vs. Linux/FreeBSD)

```
Linux/FreeBSD          NuttX
────────────────────────────────────────
Full POSIX            →  POSIX subset (enough for servers)
Processes (fork)      →  Threads only (no MMU = no fork)
Virtual memory        →  Flat memory (everything shares RAM)
Drivers in kernel     →  Drivers in kernel
Glibc                 →  Tiny libc (newlib/nuttx libc)
systemd/init          →  Simple rcS script
Ext4/ZFS/btrfs        →  LittleFS/SPIFFS/FAT (for Flash)
```

**Why no fork()?** The ESP32-C3 has no **MMU** (Memory Management Unit). An MMU lets the OS give each process its own private memory space. Without it, everything shares one memory space — so NuttX uses **threads** (pthreads) instead of processes. They're lighter weight anyway.

**What you still get:**
- `open()`, `read()`, `write()`, `close()` — file I/O
- `socket()`, `bind()`, `listen()` — networking
- `pthread_create()`, `pthread_mutex_lock()` — threading
- `stat()`, `opendir()`, `readdir()` — directories
- `mount()` — filesystems

---

## Hardware You Need

| Item | Cost | Purpose |
|------|------|---------|
| ESP32-C3 DevKit | ~$5 | The brain (RISC-V + WiFi + Flash) |
| USB-C cable | ~$2 | Power + data (must support data!) |
| USB-serial adapter* | ~$3 | Backup console (CP2102/FTDI/CH340) |

*Optional but recommended. If WiFi crashes the USB port, this lets you still talk to the board.

---

## Step 1: Flash the Firmware

### What is "flashing"?

Writing a binary program into the chip's permanent Flash memory. Like installing an OS, but it overwrites everything — no dual boot.

### Get the files

```bash
# 1. The NuttX image (pre-built with WiFi + SSH + LittleFS)
wget https://example.com/nuttx-microunix-ssh22-web.bin

# 2. Bootloader + partition table (needed for "standard boot")
mkdir -p ~/esp-bins
cd ~/esp-bins
wget https://github.com/espressif/esp-nuttx-bootloader/releases/download/latest/bootloader-esp32c3.bin
wget https://github.com/espressif/esp-nuttx-bootloader/releases/download/latest/partition-table-esp32c3.bin
```

### What's a bootloader?

A tiny program that runs first, sets up hardware, then loads the main OS. Like GRUB or U-Boot, but tiny. The partition table tells it where things live in Flash.

```
Flash memory layout (4 MB):
┌─────────────────────────────────────┐
│ 0x000000  bootloader (20 KB)        │
│ 0x008000  partition table (3 KB)    │
│ 0x010000  nuttx.bin (~1 MB)         │
│ 0x100000  /data partition (8 MB)*   │
└─────────────────────────────────────┘
* Logical partition, may span multiple sectors
```

### Flash it

You need **esptool** (Espressif's flashing tool). It's in the ESP-IDF SDK:

```bash
# Install ESP-IDF (one time)
mkdir -p ~/esp
cd ~/esp
git clone --depth 1 --recursive https://github.com/espressif/esp-idf.git
cd esp-idf
./install.sh esp32c3
source ./export.sh

# Flash (use the full path to esptool from the venv)
sudo /home/guest/.espressif/python_env/idf6.2_py3.12_env/bin/esptool \
  --chip esp32c3 --port /dev/ttyACM0 --baud 921600 \
  write_flash 0x0 ~/esp-bins/bootloader-esp32c3.bin \
  0x8000 ~/esp-bins/partition-table-esp32c3.bin \
  0x10000 nuttx-microunix-ssh22-web.bin
```

**On FreeBSD:** same command, but port is `/dev/cuaU0`
**On macOS:** same, but port is `/dev/cu.usbserial-*`

### If "permission denied" on /dev/ttyACM0:

```bash
# Linux: add yourself to dialout group
sudo usermod -a -G dialout $USER
# Log out and back in, or:
newgrp dialout
```

---

## Step 2: Connect to the Console

### What is a "console"?

A text interface to the OS. Like a terminal, but built into the board.

### Option A: USB CDC (built-in, preferred)

The board appears as a USB serial device.

```bash
# Linux
sudo minicom -D /dev/ttyACM0 -b 115200
# Exit: press Ctrl+A, then Q

# FreeBSD
cu -l /dev/cuaU0 -s 115200
# Exit: type ~. (tilde + period)
```

### Option B: UART0 (GPIO pins) — backup

Connect a USB-serial adapter:
```
ESP32-C3          USB-Serial Adapter
─────────────     ──────────────────
GPIO 20 (TX)  ──► RX
GPIO 21 (RX)  ◄── TX
GND           ──► GND
```

```bash
sudo minicom -D /dev/ttyUSB0 -b 115200
```

### You should see:

```
NuttShell (NSH) NuttX-13.0.0
nsh>
```

Type `help` to see commands. This is **NSH** — NuttX Shell. Like bash, but tiny.

---

## Step 3: Connect to WiFi

```bash
# Set WiFi password (WPA2-PSK)
nsh> wapi psk wlan0 "your_wifi_password" 3

# Set SSID (network name) and connect
nsh> wapi essid wlan0 "your_network_name" 1

# Get IP via DHCP
nsh> renew wlan0

# Check connection
nsh> ifconfig
wlan0   Link encap:Ethernet HWaddr 84:f7:03:xx:xx:xx
        inet addr:192.168.1.42  DRaddr:192.168.1.1
        Mask:255.255.255.0
```

**If ping drops after a few packets:**
```bash
nsh> wapi psp wlan0 0    # Disable WiFi power save
nsh> wapi txpower wlan0 10   # Lower TX power (saves power, more stable)
```

---

## Step 4: Enable SSH (Dropbear)

The microunix build includes **Dropbear** — a tiny SSH server.

```bash
# Create a user (saved to /data/passwd on LittleFS)
nsh> useradd admin
New password: ********
Retype password: ********

# Now from your laptop:
ssh admin@192.168.1.42
```

**What persists across reboots (stored on /data SPIFFS):**
- `/data/etc/dropbear/dropbear_ecdsa_host_key` — SSH host key
- `/data/passwd` — User accounts
- `/data/blog/` — Your website content

---

## Step 5: Filesystem — LittleFS on /data

### What is LittleFS?

A filesystem designed for **Flash memory** (not hard drives). Features:
- Wear leveling (spreads writes so Flash doesn't wear out)
- Power-loss safe (won't corrupt if power dies mid-write)
- Real directories (nested folders like `/blog/2024/01/`)
- Small overhead (~35%)

### Mount it:

```bash
nsh> mount -t littlefs /dev/mtdblock0 /data
nsh> ls /data
lost+found/  blog/  config/
```

### Partition size

The microunix build uses an **8 MB partition** for `/data` with **4 KB blocks** — good balance for many small text files.

```bash
# In menuconfig (if rebuilding):
CONFIG_FS_LITTLEFS=y
CONFIG_FS_LITTLEFS_BLOCK_SIZE=4096
CONFIG_ESPRESSIF_STORAGE_MTD_SIZE=0x800000  # 8 MB
```

---

## Step 6: Put Your Blog On It

### Directory structure

```
/data/
├── blog/
│   ├── 2024/
│   │   ├── 01/
│   │   │   ├── hello-world.html
│   │   │   └── another-post.md
│   │   └── 02/
│   └── index.html
├── assets/
│   ├── css/style.css
│   ├── js/app.js
│   └── images/hero.jpg
└── www/              # Web root for httpd
    └── index.html -> ../blog/index.html
```

### Option 1: Generate on host, copy via SSH

```bash
# On your laptop
hugo                    # or jekyll, zola, mkblog, etc.
scp -r public/* admin@192.168.1.42:/data/www/
```

### Option 2: Generate on the device (mkblog)

```bash
# If mkblog is built into NuttX
nsh> mkblog -s /data/blog -t /data/templates -o /data/www
```

### Option 3: Edit live via SSH

```bash
ssh admin@192.168.1.42
nsh> vi /data/blog/2024/01/new-post.md
```

---

## Step 7: Run the Web Server

NuttX includes **httpd** — a tiny multi-threaded HTTP server.

```bash
# Start manually
nsh> httpd -p 80 -h /data/www

# Test from laptop
curl http://192.168.1.42/
curl http://192.168.1.42/blog/2024/01/hello.html
```

### Auto-start at boot

Create `/data/init.d/rcS` (runs automatically on boot):

```bash
#!/bin/sh

# Mount filesystem
mount -t littlefs /dev/mtdblock0 /data

# WiFi (credentials can be in wapi.conf or set here)
wapi psk wlan0 "your_password" 3
wapi essid wlan0 "your_ssid" 1
wapi psp wlan0 0          # Disable power save
renew wlan0

# Start services
httpd -p 80 -h /data/www &
dropbear &

# Optional: set time via NTP
ntpdate pool.ntp.org
```

Make it executable:
```bash
nsh> chmod +x /data/init.d/rcS
```

---

## How This Differs From Fedora/FreeBSD

| Task | Fedora/FreeBSD | NuttX on ESP32-C3 |
|------|----------------|-------------------|
| **Install OS** | ISO → disk, 5–30 min | Flash binary, 10 sec |
| **Boot time** | 10–60 seconds | < 1 second |
| **Config files** | /etc/everything | /data/init.d/rcS + wapi.conf |
| **Package manager** | dnf/pkg/apt | None (compile into image) |
| **Add software** | `dnf install` | Recompile kernel + apps |
| **Logs** | journalctl/syslog | `dmesg` + serial console |
| **Users/groups** | /etc/passwd, /etc/group | /data/passwd (flat file) |
| **Firewall** | firewalld/nftables/ipfw | None (minimal TCP stack) |
| **Time sync** | chrony/ntpd | `ntpdate` once at boot |
| **Filesystem** | ext4/ZFS/btrfs | LittleFS (Flash-optimized) |
| **SSH keys** | /etc/ssh/ssh_host_* | /data/etc/dropbear/... |
| **Web server** | nginx/Apache/Caddy | httpd (built-in, tiny) |

**Key mental shift:** You don't "install packages." You **configure the build** (`make menuconfig`), compile, and flash a new monolithic image. The OS + your apps = one binary.

---

## Troubleshooting

| Symptom | Likely Cause | Fix |
|---------|--------------|-----|
| `cannot open /dev/ttyACM0` | USB CDC crashed | Use UART0 adapter (GPIO 20/21) |
| WiFi connects then drops | Power save / brownout | `wapi psp wlan0 0`; add 470μF cap on 5V |
| "No space left" on /data | LittleFS full | Increase partition; delete old posts |
| SSH "connection refused" | Dropbear not running | Check `ps`; start `dropbear &` |
| Flash fails | Bad USB cable / port | Try USB 2.0 port; hold BOOT button |
| Board reboots under load | Power supply weak | Powered hub; external 5V/2A supply |

---

## Performance Reality Check

| Metric | Expectation |
|--------|-------------|
| Static page (15 KB) | ~50 ms |
| Concurrent connections | 4–8 (single core) |
| Throughput | ~500 KB/s |
| Uptime | Weeks (watchdog recommended) |
| Power | ~100 mA idle, ~300 mA WiFi TX |

**Not suitable for:** High traffic, dynamic apps, databases.
**Perfect for:** Personal blog, documentation, IoT dashboard, config UI.

---

## Why Do This?

| Reason | Explanation |
|--------|-------------|
| **Learn OS internals** | Tiny codebase you can read |
| **Embedded Unix skills** | Valuable for IoT/edge jobs |
| **Ultra-low power** | Runs on battery for months |
| **No SD card corruption** | LittleFS is power-loss safe |
| **Cost** | $5 vs $35+ for Pi Zero |
| **Instant boot** | No filesystem check, no systemd |

---

## Resources

| Topic | Link |
|-------|------|
| NuttX docs | https://nuttx.apache.org/docs/latest/ |
| ESP32-C3 port | https://nuttx.apache.org/docs/latest/platforms/risc-v/esp32c3/index.html |
| Board configs | `./tools/configure.sh -L esp32c3-devkit` |
| LittleFS tuning | `CONFIG_FS_LITTLEFS_BLOCK_SIZE=4096` |
| Bootloader binaries | https://github.com/espressif/esp-nuttx-bootloader/releases |
| ESP-IDF (toolchain) | https://github.com/espressif/esp-idf |

---

## What's Next?

1. **Add HTTPS** — Enable mbedTLS + `CONFIG_HTTPD_TLS`
2. **CGI scripts** — Dynamic content with `CONFIG_HTTPD_CGI`
3. **OTA updates** — MCUboot for signed firmware upgrades
4. **RTC + coin cell** — Keep time without NTP
5. **Sensors** — I2C/SPI drivers built in (BME280, sensors, etc.)

---

## Summary

You took a $5 chip, flashed a 1 MB binary, and got:
- ✅ WiFi + DHCP
- ✅ SSH access (Dropbear)
- ✅ Real filesystem with directories (LittleFS)
- ✅ Web server (httpd)
- ✅ POSIX API (threads, sockets, files)
- ✅ All in 400 KB RAM, < 1 second boot

**That's a microUnix machine.** Not a Linux *replacement* — but a Unix *peer* that fits in your pocket.

---

*Questions? The NuttX community is friendly: #nuttx on Libera IRC, or the mailing list.*

---

## Appendix: SSH In and Use Familiar Commands

Once SSH is working, you get a surprisingly normal Unix environment:

```bash
$ ssh admin@192.168.1.42
admin@192.168.1.42's password:
nsh> 
```

### Files & directories
```bash
nsh> ls /data/blog/2024/01/
hello-world.html    another-post.md

nsh> ls -la /data/www/
total 48
drwxr-xr-x  2 root root  4096 Jan  1 12:00 .
drwxr-xr-x  3 root root  4096 Jan  1 12:00 ..
-rw-r--r--  1 root root 15234 Jan  1 12:00 index.html
drwxr-xr-x  2 root root  4096 Jan  1 12:00 blog/

nsh> find /data/blog -name "*.html" | head -5
/data/blog/index.html
/data/blog/2024/01/hello.html
/data/blog/2024/01/another.html

nsh> mkdir -p /data/blog/2024/03
nsh> cp /data/blog/2024/01/hello.html /data/blog/2024/03/
nsh> rm /data/blog/2024/01/old.html
```

### Search & view files
```bash
nsh> grep -r "NuttX" /data/blog/
/data/blog/index.html:NuttX on ESP32-C3
/data/blog/2024/01/hello.html:Running NuttX on a $5 chip

nsh> cat /data/blog/2024/01/hello.html
<html>...</html>

nsh> head -20 /data/blog/index.html
nsh> tail -f /data/logs/access.log    # if you add logging
```

### Processes & system
```bash
nsh> ps
  TID   PID  PPID PRI POLICY   TYPE    NPX STATE    EVENT     STACK COMMAND
    0     0     0   0 FIFO     Kthread   - Ready              2016 Idle_Task
    2     2     0 100 RR       Task      - Running            1984 nsh_main
    5     5     0 100 RR       Task      - Waiting            4096 httpd
    6     6     0 100 RR       Task      - Waiting            4096 httpd
    7     7     0 100 RR       Task      - Waiting            8192 dropbear

nsh> free
      total       used       free    maxused    maxfree  nused  nfree name
     361104       5968     355136       6744     354728     30      2 Umem

nsh> df
Filesystem     1K-blocks      Used Available Use% Mounted on
/dev/mtdblock0      8192      1245      6947  15% /data

nsh> uname -a
NuttX 13.0.0 cec617df Sep 17 2026 15:48:13 risc-v esp32c3-devkit

nsh> dmesg | tail -5
[   12.3] httpd: started on port 80
[   12.4] dropbear: listening on port 22
```

### Process control
```bash
nsh> kill 5        # Kill httpd (SIGTERM)
nsh> kill -9 5     # Force kill (SIGKILL)
nsh> pkill httpd   # Kill by name (if built in)
```

### Network
```bash
nsh> ifconfig
wlan0   inet addr:192.168.1.42  DRaddr:192.168.1.1
        Mask:255.255.255.0

nsh> netstat -t
Active Internet connections
Proto Local Address    Foreign Address    State
TCP   0.0.0.0:80       0.0.0.0:*          LISTEN
TCP   0.0.0.0:22       0.0.0.0:*          LISTEN

nsh> ping 192.168.1.1
PING 192.168.1.1 56 bytes of data
64 bytes from 192.168.1.1: seq=0 ttl=64 time=2.3 ms
64 bytes from 192.168.1.1: seq=1 ttl=64 time=1.8 ms
```

### What's missing vs. Fedora/FreeBSD?
| Command | Status | Notes |
|---------|--------|-------|
| `ls`, `cp`, `mv`, `rm`, `mkdir`, `rmdir` | ✅ | Full support |
| `cat`, `head`, `tail`, `grep`, `find` | ✅ | Built-in |
| `ps`, `free`, `df`, `kill` | ✅ | NSH built-ins |
| `ping`, `ifconfig`, `netstat` | ✅ | Network utils |
| `ssh`, `scp`, `sftp` | ✅ | Dropbear client |
| `vi` / `nano` | ⚠️ | `vi` yes, `nano` no |
| `systemctl`, `journalctl` | ❌ | No systemd |
| `dnf`, `pkg`, `apt` | ❌ | No package manager |
| `sudo` | ❌ | Single user (root) |
| `cron` | ❌ | No cron daemon |
| `tar`, `gzip` | ⚠️ | Limited / not built |

---

*Tip: The `help` command in NSH lists all available built-ins. Most feel familiar if you know bash.*
