PWM

Pulse Width Modulation(PWM), is a common hardware interface and controls analog devices with digital outputs.For more information, please visit here.

Prerequisites

Using PWM

Please read the datasheet to confirm that the interface is PWM.

Configuring driver.json

Please ensure your interface is PWM in driver.json and declare it as PWM. The declaration should be inputs with type as PWM.

{
...
"inputs": {
"pwm": {
"type": "pwm",
"args": {
"frequency": 200
}
},
}
}

Interface Properties

The following properties is accepted by PWM:

  • frequency - setup output square wave frequency.

Writing a Driver

  • PWM has two methods:
    • setDuty - setup duty for PWM. The argument is a float that rangs from 0 to 1.
pwm.setDuty(0.5);
  • setFrequency - setup output square wave frequency, whose unit is Hz.
pwm.setFrequency(300);

Application

LED Module(ky-016)

The LED module has three PWM intefaces (R,G,B) whose output square wave frequency is 800Hz. Please declare them in driver.json.

"models": [
"KY-016"
],
"inputs": {
"pwm-r": {
"type": "pwm",
"args": {
"frequency": 800
}
},
"pwm-g": {
"type": "pwm",
"args": {
"frequency": 800
}
},
"pwm-b": {
"type": "pwm",
"args": {
"frequency": 800
}
}
}

We provides buzzer with four methods:

  • setRGB - setup duty for R, G, B to adjust LED color.
  • getRGB - return to current RGB value.
  • turnOn - setup R, G, B to 1 to make LED white.
  • turnOff - setup R, G, B to 0 to make LED black.
'use strict';

var driver = require('ruff-driver');

module.exports = driver({

attach: function (inputs) {
this._pwmR = inputs['pwm-r'];
this._pwmG = inputs['pwm-g'];
this._pwmB = inputs['pwm-b'];
},

exports: {
setRGB: function (rgb, callback) {
if (Array.isArray(rgb)) {
this._r = rgb[0];
this._g = rgb[1];
this._b = rgb[2];
}

this._pwmR.setDuty(this._r / 0xff);
this._pwmG.setDuty(this._g / 0xff);
this._pwmB.setDuty(this._b / 0xff, callback);
},

getRGB: function (callback) {
return setImmediate(callback, undefined, [this._r, this._g, this._b]);
},

turnOn: function (callback) {
this.setRGB([0xff, 0xff, 0xff], callback);
},

turnOff: function (callback) {
this.setRGB([0x00, 0x00, 0x00], callback);
}
}
});