Module: j5e/switch

Description

A module for working with switches. It will emit open and close events when the state of a mechanical switch changes.

In electrical engineering, a switch is an electrical component that can disconnect or connect the conducting path in an electrical circuit, interrupting the electric current or diverting it from one conductor to another. The most common type of switch is an electromechanical device consisting of one or more sets of movable electrical contacts connected to external circuits. When a pair of contacts is touching current can pass between them, while when the contacts are separated no current can flow.Read more on Wikipedia

Requires


Class: Switch

The Switch class allows for control of digital switches

Constructor

new Switch(io, io.mode)

Parameters

Name
Type
Description
io
(required)
number, string, or object

Description:
Pin identifier or IO Options (See instantiation)

io.mode
number, or string

Description:
Device configuration options. If a number, a valid value based on the Provider's constants. If a string, one of "Input", "InputPullUp", or "InputPullDown"
Default: Input

Example

// Use a switch to control an LED
import Switch from "j5e/switch";
import LED from "j5e/led";

const mySwitch = await new Switch(12);
const led = await new LED(13);

mySwitch.on("open", function() {
  led.off();
});

mySwitch.on("close", function() {
  led.on();
});

Properties

Name
Type
Description
isClosed
(read only)
True if the switch is closed (current is flowing)
isOpen
(read only)
True if the switch is open (current is not flowing)

Events

  • Switch#event:open
  • Switch#event:close

Methods

Switch.on

Create an event listener

switch.on(event, listener);

Parameters

Name
Type
Description
event
(required)
string

Description:
The name of the event to listen for

listener
(required)
function

Description:
A callback to run when the event is fired.


Switch.removeListener

Remove an event listener

switch.removeListener(event, listener);

Parameters

Name
Type
Description
event
(required)
string

Description:
The name of the event that we are removing a listener from

listener
(required)
function

Description:
The callback that we are removing


Switch.emit

Note: This method is not part of the public API, and is subject to change.

Emit an event

switch.emit(event);

Parameters

Name
Type
Description
event
(required)
string

Description:
The name of the event to emit


Switch.once

Create an event listener that will only fire one time.

switch.once(event, listener);

Parameters

Name
Type
Description
event
(required)
string

Description:
The name of the event to listen for

listener
(required)
function

Description:
A callback to run when the event is fired.