Skip to content
SourcePotPublic

About

RP2040 multi-phase sine PWM with a Raspberry Pi web dashboard

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

31 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Raspberry Pi GPIO and RP2040 PWM web control

The Flask web server runs on a Raspberry Pi 4 Model B. A Raspberry Pi Pico or other RP2040 board connected by USB generates four hardware-PWM channels, each with a complementary high-side and low-side output separated by a dead time, and accepts commands from the server over USB serial.

Hardware and channels

  • Each channel has a high-side and a low-side output on the Pico:

    Channel High side Low side PWM slice Phase shift (start pointer)
    0 GPIO 0 GPIO 1 0 0° (0)
    1 GPIO 2 GPIO 3 1 120° (341)
    2 GPIO 4 GPIO 5 2 240° (683)
    3 GPIO 6 GPIO 7 3 90° (256)

    The high side is the slice's output A; the low side is its output B, inverted. The two sides of a channel are never on at the same time. The phase shift is relative to channel 0 and is set by the channel's start pointer into the 1024-entry sine table (see Waveform). 120° and 240° are rounded: 341 and 683 steps are exactly 119.88° and 240.12°.

  • The PWM frequency is fixed: it is set only by the PWM_FREQUENCY constant at the top of RP2040/main.py (currently 20 kHz). The dashboard shows it but cannot change it. It must be from 20 kHz to 61.03 kHz.

  • The dead time is fixed too: it is set only by the DEAD_TIME_NS constant at the top of RP2040/main.py (currently 1000 ns = 1 µs) and is the same for all four channels. At every switching edge, one side turns off and the other turns on only after the dead time. The resolution is one clock cycle (8 ns); values in between are rounded up, so the dead time is never shorter than DEAD_TIME_NS (for example 1003 ns gives 1008 ns). It must be at least DEAD_TIME_MIN_NS (100 ns) and less than half the PWM period.

  • To change either constant, edit it and copy main.py onto the board again. If a value is invalid, the firmware does not start the PWM: it holds all eight outputs low and answers every server request with an error. The dashboard shows that error as a warning, for example "DEAD_TIME_NS is 50; it must be a whole number of at least 100 ns".

  • If the firmware's command loop ever stops (for example after Ctrl+C in Thonny), the waveform freezes just as with STOP. Unexpected errors while handling a command are reported back to the server instead of stopping the firmware.

  • The PWM slices run in phase-correct (centre-aligned) mode: the counter counts up to TOP and back down, which puts the dead time on both edges of every pulse. The firmware programs the RP2040 PWM registers directly, because MicroPython's PWM class cannot select this mode. It therefore works on the RP2040 only, not on the RP2350 (Pico 2).

  • The PWM counter runs from the 125 MHz RP2040 system clock, which the firmware sets at startup. In phase-correct mode, frequency × 2 × duty-cycle steps = 125 MHz, so the highest allowed PWM_FREQUENCY of 61.03 kHz (125 MHz / 2048) gives exactly 10-bit resolution. At 20 kHz there are 3125 steps; the waveform uses 10-bit levels at every frequency.

  • All four slices start in the same clock cycle, so their PWM periods are aligned.

  • The PWM pins output 3.3V logic only. Use appropriate external drivers for motors, relays, LED strips, or other loads; do not drive loads directly from the Pico pins.

  • Raspberry Pi GPIO outputs: BCM 17, 18, 22, and 23.

  • Raspberry Pi GPIO inputs: BCM 24 and 27, configured with pull_up=False. Connect only 3.3V-compatible signals.

  • The web server explicitly uses the local Raspberry Pi 4 gpiochip0 for these GPIOs. The connected Pi Zero does not provide these GPIO inputs or outputs to this server.

Connect the RP2040 to the Pi by USB. Connect the RP2040 ground to the ground of any externally powered load/driver.

Waveform

  • The RP2040 holds a 1024-entry table containing exactly one sine cycle. Its values are 10-bit PWM levels (switching point = level / 1024 of the period) from 21 to 1003, which is 2.05–97.95%.
  • The dead time is split evenly around each switching point: the high side stops half a dead time before it, and the low side starts half a dead time after it. So both sides lose duty cycle to the dead time. At 20 kHz, the two 1 µs dead times take 4% of each 50 µs period, so high side + low side always add up to 96%. Each side ranges from about 0.03% to 96%.
  • Near the peaks of the sine, the side that is almost off gets very short pulses: at 20 kHz with 1 µs dead time, down to 16–32 ns. Check that your gate drivers handle such short pulses cleanly.
  • At startup the firmware converts each table level to the two compare values of its PWM slice and writes both with a single register write, so the high and low side always update together in the same PWM period.
  • Each channel reads the table through its own pointer. The pointers start at 0, 341, 683, and 256: channels 0–2 are 120° apart (three-phase), and channel 3 is 90° (a quarter of the table) after channel 0.
  • A timer steps all pointers together, forward (increment) or backward (decrement), wrapping at the end of the table. The step period is 10 µs to 1 ms (default 1 ms). The dashboard shows it as a motion frequency, one full sine cycle per 1024 steps: 0.9766 Hz to 97.6563 Hz. It uses four decimal places so every step period survives the round trip unchanged when you click Apply.
  • The steps come from a MicroPython software timer, so short step periods may not be reached exactly. Measure the output if the timing matters.
  • A 16-bit absolute position starts at 32768 and advances or decrements with each table step, wrapping from 65535 to 0 or from 0 to 65535.
  • When the RP2040 starts, all eight outputs are held low while the PWM is set up, then the waveform runs forward at the default settings.
  • Pausing motion from the dashboard, or stopping the web server (which sends STOP), freezes the waveform. Each channel keeps its last high-side and low-side duty cycle, with the dead time.

Project directory

On the Pi, the project lives in your home directory as /home/<user>/PIserver. This top-level folder, the one that contains this README.md, is meant whenever this README says "this directory". It has a subfolder that is also called PIserver, which holds the Python code; do not run the commands in this README from there.

/home/<user>/PIserver/          ← "this directory": run the commands here
├── README.md
├── requirements.txt
├── piserver.service
├── .venv/                       ← created during installation
├── Dashboard/                   ← the dashboard page (index.html)
├── PIserver/                    ← the Python code (app.py, run.py, …)
├── RP2040/                      ← the RP2040 firmware (main.py)
└── tests/

The commands need this folder as the current directory: requirements.txt is there, python PIserver/run.py is a path relative to it, and piserver.service expects the virtual environment at /home/<user>/PIserver/.venv.

Flash the RP2040

  1. Install MicroPython firmware for the RP2040 board.
  2. Copy RP2040/main.py onto the board as its root-level main.py (for example with Thonny), then reboot it. Repeat this whenever RP2040/main.py changes; the board keeps running its old copy until then.
  3. Connect the board to the Pi by USB. The server defaults to /dev/ttyACM0; set PWM_SERIAL_PORT if the device appears elsewhere.

Install and run the web server

Run these commands from the project directory, ~/PIserver (see Project directory):

cd ~/PIserver
sudo apt install python3-lgpio
python3 -m venv --system-site-packages .venv
. .venv/bin/activate
python -m pip install -r requirements.txt
python PIserver/run.py

GPIO Zero uses the system lgpio package to access the Pi 4's local gpiochip0. The --system-site-packages option makes that OS-installed package available inside the virtual environment. If .venv already exists, recreate it with this option and reinstall the requirements before starting the server.

Open http://127.0.0.1:8000 on the Pi. To connect another computer directly to the Pi with an Ethernet cable, you can use the Pi's mDNS hostname instead of typing its IP address. On the Pi, run hostname to see its hostname, then try http://<hostname>.local:8000 in the other computer's browser (for example, http://raspberrypi.local:8000). This uses mDNS name resolution and does not require a separate DNS server. Raspberry Pi OS normally supports mDNS; if needed, install its responder with sudo apt install avahi-daemon.

If the Pi and computer are connected directly with no router or DHCP server, they still need IP addresses: mDNS provides a name for an address, but does not assign one. If both wired adapters support automatic link-local IPv4 addressing, leave them set to automatic and use the .local URL above. If that does not work, configure static addresses on both adapters; for example, set the Pi to 192.168.50.1 and the computer to 192.168.50.2, both with subnet mask 255.255.255.0. No gateway or DNS setting is needed for this direct connection. Use this example subnet only if it does not conflict with another network connected to either computer.

Start the server on the Pi with python PIserver/run.py from this directory. It listens on all IPv4 network interfaces, including Ethernet. If a firewall is enabled on the Pi, allow incoming TCP connections on port 8000 from the connected computer.

Authentication is not required, so anyone who can reach the server can view its status and control its GPIO/PWM outputs. Keep it on a trusted LAN and do not expose it to the internet.

This project and PIclient/piclient/sentinel.py use overlapping Raspberry Pi GPIO pins. Do not run both programs at the same time.

Start at boot with systemd

piserver.service runs the server as a systemd service: it starts at boot, restarts after a crash, and logs to the system journal. Set it up on the Pi as follows; run all commands from this directory.

  1. Install the server first. Follow Install and run the web server so that .venv exists, and check once that python PIserver/run.py works. Then stop it with Ctrl+C: the service and a manually started server cannot run at the same time, because both need port 8000 and the RP2040 serial port.

  2. Give your user access to the hardware. The service runs as a normal user, which must be in the gpio group (GPIO) and the dialout group (USB serial port of the RP2040):

    groups                                   # shows your current groups
    sudo usermod -aG gpio,dialout "$USER"    # only if one is missing

    Log out and back in (or reboot) after usermod, so the new groups apply.

  3. Edit piserver.service. Check these lines and adapt them to your Pi:

    Setting Set it to Default in the file
    User= your login name on the Pi (whoami shows it) pi
    WorkingDirectory= this directory: /home/<user>/PIserver (pwd shows it) /home/pi/PIserver
    ExecStart= the .venv Python in this directory, followed by PIserver/run.py /home/pi/PIserver/.venv/bin/python PIserver/run.py

    On the Pi this directory is PIserver in the home directory of the user who runs the service, so if your login name is not pi, replace pi in all three lines. Both paths must be absolute: systemd does not expand ~ or $HOME here. If the RP2040 is not at /dev/ttyACM0, also add a line in the [Service] section with its stable path, for example:

    Environment=PWM_SERIAL_PORT=/dev/serial/by-id/usb-MicroPython_Board_in_FS_mode_xxxxxxxx-if00

    (ls /dev/serial/by-id/ lists the exact name.)

    For example, for a user named alex with the project in /home/alex/PIserver and the RP2040 set by its stable path, the complete file looks like this:

    [Unit]
    Description=PIserver GPIO and RP2040 PWM web control
    After=network-online.target
    Wants=network-online.target
    
    [Service]
    Type=simple
    User=alex
    WorkingDirectory=/home/alex/PIserver
    ExecStart=/home/alex/PIserver/.venv/bin/python PIserver/run.py
    Environment=PYTHONUNBUFFERED=1
    Environment=PWM_SERIAL_PORT=/dev/serial/by-id/usb-MicroPython_Board_in_FS_mode_e6614103e7xxxxxx-if00
    KillSignal=SIGINT
    TimeoutStopSec=10
    Restart=on-failure
    RestartSec=5
    
    [Install]
    WantedBy=multi-user.target

    Only User=, the two paths and the optional PWM_SERIAL_PORT line differ between Pis; leave the other lines as they are.

  4. Install and start the service:

    sudo install -m 644 piserver.service /etc/systemd/system/piserver.service
    sudo systemctl daemon-reload
    sudo systemctl enable --now piserver

    enable starts the server at every boot; --now also starts it right away.

  5. Check that it runs:

    systemctl status piserver       # should show "active (running)"
    journalctl -u piserver -f       # follow the log; Ctrl+C to leave

    Then open the dashboard as described above. If the status is failed, the last lines of journalctl -u piserver show why. Common causes are a wrong path in WorkingDirectory= or ExecStart=, a missing .venv, a wrong User=, or port 8000 still used by a manually started server.

Everyday commands:

Task Command
Restart after changing the server code sudo systemctl restart piserver
Stop the server (for example to use Thonny on the serial port) sudo systemctl stop piserver
Start it again sudo systemctl start piserver
Do not start it at boot any more sudo systemctl disable --now piserver
Show the log of the current boot journalctl -u piserver -b

After editing piserver.service, install it again with the install command from step 4, then run sudo systemctl daemon-reload and sudo systemctl restart piserver. Editing the copy in this directory alone changes nothing.

To remove the service completely:

sudo systemctl disable --now piserver
sudo rm /etc/systemd/system/piserver.service
sudo systemctl daemon-reload

The service stops the server with SIGINT, the same signal as Ctrl+C, so the shutdown cleanup runs: the GPIO outputs are switched off and the RP2040 waveform is frozen at its last values. This also happens when the Pi shuts down or reboots.

If the RP2040 is not connected, or the connection is lost (for example when the board is unplugged or rebooted), the server keeps running: GPIO keeps working, and the dashboard shows the PWM controls as unavailable with a warning. In the background the server tries to reconnect every 2 seconds, and PWM comes back on the dashboard by itself once the board answers again. No server restart is needed, for example after copying a new RP2040/main.py onto the board. Stop the server while you copy the file, though, if your tool (such as Thonny) needs exclusive access to the serial port.

The server reconnects to the same serial port path. If the board may appear under a different name after a reboot (such as /dev/ttyACM1), set PWM_SERIAL_PORT to its stable /dev/serial/by-id/... path instead.

Tests

The tests use fake GPIO and serial hardware and do not require a Raspberry Pi or RP2040:

python -m unittest discover -s tests

About

RP2040 multi-phase sine PWM with a Raspberry Pi web dashboard

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages