Hardware PWM & Servos
16-channel hardware pulse-width modulation, servo motor angle mapping, and audio tone synthesis in KryonOS.
Hardware PWM & Servos API
The PWM (or System.pwm) object provides control over the ESP32's native LED Control (LEDC) peripheral. It offers 16 independent PWM channels with configurable frequencies up to 40 MHz and resolution up to 16 bits.
Firmware timer configurations are documented in the KryonOS GitHub Repository.
1. Hardware PWM Channels
PWM.attach(pin, channel, freq, resolution)
Binds a GPIO pin to a hardware LEDC PWM timer channel.
- Parameters:
pin(Integer): GPIO pin number.channel(Integer, optional): PWM channel (0 to 15).freq(Integer, optional): Base frequency in Hz (default5000).resolution(Integer, optional): Timer bit resolution (1 to 16, default8for 0-255 range).
- Returns:
Boolean(trueif attached successfully).
PWM.write(pin, duty) / PWM.writeDuty(pin, duty)
Updates the output duty cycle on an attached pin.
- Parameters:
pin(Integer)duty(Integer): 0 to(2^resolution - 1). For 8-bit resolution, 0 to 255.
- Returns:
Boolean
PWM.detach(pin)
Releases the PWM channel and resets the pin to high-impedance input mode.
- Parameters:
pin(Integer) - Returns:
Boolean
2. Servo Motor Control
The PWM engine includes a hardware servo generator running at 50 Hz with 500–2500 microsecond pulse widths.
PWM.writeServo(pin, angle)
Commands a standard hobby servo (e.g. SG90, MG996R) to rotate to a target angle.
- Parameters:
pin(Integer): Servo signal pin.angle(FloatorInteger): Target angle between0and180degrees.
- Returns:
Boolean
// Controlling a Servo on GPIO 14
var SERVO_PIN = 14;
// Sweep servo from 0 to 180 degrees
for (var deg = 0; deg <= 180; deg += 10) {
PWM.writeServo(SERVO_PIN, deg);
System.delay(50);
}
3. Piezo Buzzer & Tone Generation
PWM.writeTone(pin, freq, duration)
Generates an audible square-wave tone on a connected passive buzzer.
- Parameters:
pin(Integer): Buzzer pin.freq(Integer): Tone frequency in Hz (e.g. 440 for A4, 1000 for beep). Set to0to stop tone.duration(Integer, optional): Duration in milliseconds.
- Returns:
Boolean
// Play an alert sound on GPIO 25
function playBeep() {
PWM.writeTone(25, 2000, 100);
System.delay(120);
PWM.writeTone(25, 3000, 150);
}