← Back to Lab Hub RP2040 MicroPython Actuator Lab

PWM Signal & Dynamic Bit-Width Converter

16-bit RP2040 Hardware Registers to 8-bit, 10-bit, 12-bit & 14-bit Multi-Resolution Conversion

⚡ RP2040 Hardware Registers & Dynamic Bit-Resolution Bit-Shifting
RP2040 PWM Register Architecture: The RP2040 microcontroller utilizes 16-bit registers (0 to 65,535 via duty_u16). However, external sensors, DACs, ADCs, and communication protocols operate at various bit depths: 8-bit (0–255), 10-bit (0–1,023 RP2040 ADC default), 12-bit (0–4,095 high-res DAC/sensors), and 14-bit (0–16,383 precision sensors).

Bit-Shift Formula: To scale a 16-bit RP2040 value down to an N-bit target, perform a right bit-shift: target_val = duty_u16 >> (16 - N). 16-Bit Register: 0–65,535 Target: 8-Bit (>> 8) Bidirectional PWM Pins
Duty Cycle (16-Bit RP2040 Register): 32,768 u16 (50.0%)
Select Target Bit-Width Resolution (N-bit): Shift: >> 8 bits
8-bit
10-bit
12-bit
14-bit
Signal Frequency (Hz): 1,000 Hz (Period: 1.00 ms)
📊 Multi-Resolution Conversion Table Selected Target: 8-Bit
16-Bit Source Value (u16): 32,768 / 65,535
8-Bit Value (u16 >> 8): 128 / 255
10-Bit Value (u16 >> 6): 512 / 1,023
12-Bit Value (u16 >> 4): 2,048 / 4,095
14-Bit Value (u16 >> 2): 8,192 / 16,383
Equivalent Analog Voltage (3.3V Pin): 1.65 V
🐍 MicroPython Code: Dynamic Bit Conversion Functions
from machine import Pin, PWM

# 1. RP2040 PWM Output Setup (16-bit u16)
pwm_out = PWM(Pin(15))
pwm_out.freq(1000)
pwm_out.duty_u16(32768)

# 2. Convert Any N-Bit Sensor Input to 16-bit u16
def scale_to_u16(sensor_val, bits):
  shift = 16 - bits
  return sensor_val << shift

# 3. Convert 16-Bit u16 Register to Target N-Bit
def scale_from_u16(u16_val, target_bits):
  shift = 16 - target_bits # 16 - 8 = 8
  return u16_val >> shift # Result: 128
📝 Dynamic Bit-Conversion Quiz
If an RP2040 receives a 12-bit sensor value (range 0 to 4095), how do we scale it up to a 16-bit `duty_u16` register, and what shift operator is used?