Skip to content

PWM

An IO class that provides access to the pulse-width modulation capability of pins.

Constructor

PWM

Creates a new PWM object instance.

PWM(options)

Parameters

options

An object of properties used to construct the class.

pin - a pin specifier indicating the GPIO pin to operate as PWM output.

hz (optional) - a number specifying the requested frequency of the PWM output in hertz. The default is device dependent.

Exceptions

If the constructor requires a resource that is already in use — whether by a script or the native host — an Error exception is thrown.

Instance Properties

Includes properties of the IO Class Pattern. Specific to this class:

format

Always returns "number". The string value set by the constructor options or by the script at any time to change how it reads data.

resolution

Read-only property indicates the number of bits of resolution in values passed to the write method, e.g 10.

hz

Read-only property indicates the frequency of the PWM.

Instance Methods

write

Sets the current count on the IO instance.

write(value)

Parameters

value

A number 0 and a maximum value based on the resolution of the PWM output.

Examples

The class can be imported from the embedded namespace or found on the host device global object:

import PWM from "embedded:io/pwm";
const PWM = device.io.PWM;

Hello Dimming Blinky

This example instantiates a PWM output to control an LED based on the global device pin names and fade it on or off using System.setInterval.

const led = new device.io.PWM({
pin: device.io.led,
});
const range = (2 ** led.resolution) - 1;
let step = 5;
let value = 0;
System.setInterval(() => {
value += step;
if (value < 0 || value > range) {
step *= -1;
value += step;
}
led.write(value)
}, 5)

Specifications

Pulse-width modulation