PWM (Pulse Width Modulation)
PWM is a technique used to generate analog-like behavior from a digital pin. By switching a pin ON and OFF very rapidly, you can control the average power delivered to a component.
1. Duty Cycle & Frequency
There are two primary parameters that define a PWM signal:
Frequency (Hz)
How many times per second the pin switches. For LED dimming, 1kHz (1000Hz) is standard to prevent flickering.
Duty Cycle (%)
The percentage of time the pin is HIGH during one cycle. A 50% duty cycle means the pin is ON half the time, resulting in half-brightness.
2. Implementation (LED Dimming)
In this example, we’ll set an LED to 25% brightness using a 1kHz frequency.
import { PWM } from 'intarva';
const led = new PWM('GP25');
led.freq(1000); // Set frequency to 1kHz
led.duty(0.25); // Set duty cycle to 25% (0.0 to 1.0)
from machine import Pin, PWM
led = PWM(Pin(25))
led.freq(1000) # Set frequency to 1kHz
led.duty_u16(16384) # 25% of 65535
3. Use Cases
- LED Dimming: Controlling perceived brightness.
- Servo Control: Positioning motor arms (typically requires 50Hz frequency).
- Audio Generation: Creating simple “beeps” by varying the frequency.
- Motor Speed: Controlling DC motor velocity via a motor driver.