A Pulse Width Modulation (PWM) library for BlueScript on ESP32.
This package allows you to generate PWM signals to control LED brightness, drive servo motors, or generate tones using the ESP32's LEDC peripheral.
Install this package in your BlueScript project:
bscript project install https://github.com/bluescript-lang/pkg-pwm-esp32.git- Simple API: Control duty cycle with a float (
0.0-1.0). - Automatic Resource Management: Automatically allocates and frees hardware timers (0-3) and channels (0-15).
- Smart Timer Reuse: Multiple PWM instances sharing the same frequency will intelligently share the same hardware timer to save resources.
- High Precision: Runs at 13-bit resolution.
import { PWM } from "pwm";
// Configure PWM on GPIO 2 at 5000 Hz
const led = new PWM(2, 5000);
for (let j = 0; j < 10; j++) {
// Fade In
for (let i = 0; i <= 100; i++) {
let duty: float = i / 100.0;
led.write(duty);
time.delay(10);
}
// Fade Out
for (let i = 100; i >= 0; i--) {
let duty: float = i / 100.0;
led.write(duty);
time.delay(10);
}
}
led.close();Standard servos usually operate at 50Hz, with a pulse width between 1ms (0 degrees) and 2ms (180 degrees). Since the period of 50Hz is 20ms:
- 1ms = 1/20 = 0.05 (5% duty)
- 2ms = 2/20 = 0.10 (10% duty)
import { PWM } from "pwm";
// Configure Servo pin (GPIO 14) at 50 Hz
const servo = new PWM(14, 50);
// Rotate to ~0 degrees
servo.write(0.05);
time.delay(1000);
// Rotate to ~180 degrees
servo.write(0.10);
time.delay(1000);
// Clean up resources when done
servo.close();Initializes a PWM channel on the specified pin.
- pin: The GPIO number.
- frequency: The frequency in Hz (e.g.,
5000for LEDs,50for Servos). - Note: This method automatically assigns an available hardware timer and channel.
Sets the duty cycle of the PWM signal.
- duty: A float value between
0.0(0%, always off) and1.0(100%, always on). - Throws a runtime error if the value is out of range.
Updates the frequency dynamically.
- freq: New frequency in Hz.
- Note: This might re-allocate the underlying hardware timer.
Stops the PWM signal, releases the hardware timer/channel, and resets the GPIO pin.
- Always call this when you are finished with the instance to free up resources.
- Resolution: The library is fixed to 13-bit resolution.
- Limits:
- Maximum 16 simultaneous PWM channels (limited by hardware).
- Maximum 4 unique frequencies (limited by hardware timers).
- If you create multiple PWM instances with the same frequency, they share a timer, so you can have up to 16 channels with the same frequency.
- Error Handling: The constructor or methods will throw a runtime error if no hardware resources (timers/channels) are available.