Raspberry Pi Gpio How to Read Variable Input Bytes

Version npm Custom badge

array-gpio

array-gpio is a depression-level javascript library for Raspberry Pi using direct register control.

It maps the ARM peripheral registers in memory using /dev/mem for PWM, I2C, SPI and /dev/gpiomem for GPIO control.

One of its features is the use of array objects for GPIO input/output control.

It has support for i2c, spi and pwm peripheral interface using direct register control.

The module'south GPIO will too work on 64-bit Ubuntu Server xx+ for Raspberry 3B+ and iv models.

For IoT or automobile-to-machine applications, please bank check m2m using assortment-gpio.

ARM Peripheral Support

  • GPIO
  • PWM
  • I2C
  • SPI

Supported Raspberry Pi Devices

  • Model: B+, two, 3, Zero & Zero W, Compute Module iii, 3B+, 3A+, iv (generally all xl-pivot models)

  • The module'southward GPIO will also work on 64-chip Ubuntu Server xx+ for Raspberry 3B+ and iv

GPIO pin numbering

This module uses pin numbers based on the physical pin numbers 1~twoscore from the board header.

Node.js Requirements

  • Node.js version: 8.x, 9.10, 10.x, xi.x, 12.x, 14.x

Installation

Quick Showtime

Example 1

Create a GPIO input and output object

Using in and out method to create an input/output object

                /* Connect a momentary switch push on pivot 11 and an led on pin 33 */                // create a raspberry pi (r) object                const                r                =                require                (                'array-gpio'                )                ;                // prepare pin xi as input switch                let                sw                =                r                .                in                (                eleven                )                ;                // set pin 33 as output led                let                led                =                r                .                out                (                33                )                ;              

Using setInput and setOutput method to create an input/output object

                const                {setInput,                setOutput}                =                require                (                'array-gpio'                )                ;                // fix pin eleven as input switch                let                sw                =                setInput                (                11                )                ;                // fix pin 33 as output led                let                led                =                setOutput                (                33                )                ;              

Monitor the country of an input object

                const                r                =                crave                (                'array-gpio'                )                ;                let                sw                =                r                .                in                (                11                )                ;                let                led                =                r                .                out                (                33                )                ;                // Pressing the switch sw button, the led volition turn on                // Releasing the switch sw button, the led volition turn off                sw                .                watch                (                (                state                )                =>                {                if                (                state                )                {                led                .                on                (                )                ;                }                else                {                led                .                off                (                )                ;                }                }                )                ;              

Monitor multiple input objects

To monitor multiple input objects, you can use the watchInput() method.

                /* Connect momentary switch buttons on pivot 11, 13, fifteen and 19 and an led on pivot 33 and 35 */                const                r                =                require                (                'assortment-gpio'                )                ;                // create multiple input objects                let                sw1                =                r                .                in                (                11                )                ;                permit                sw2                =                r                .                in                (                13                )                ;                permit                sw3                =                r                .                in                (                15                )                ;                permit                sw4                =                r                .                in                (                19                )                ;                let                led1                =                r                .                out                (                33                )                ;                let                led2                =                r                .                out                (                35                )                ;                /* The callback argument of .watchInput() method will be invoked if one of the input's state changes. */                // Press sw1 to plow on the led1, press sw2 to turn off the led1                // Press sw3 to turn on the led2, printing sw4 to plow off the led2                r                .                watchInput                (                (                )                =>                {                if                (                sw1                .                isOn                )                {                led1                .                on                (                )                ;                }                else                if                (                sw2                .                isOn                )                {                led1                .                off                (                )                ;                }                else                if                (                sw3                .                isOn                )                {                led2                .                on                (                )                ;                }                else                if                (                sw4                .                isOn                )                {                led2                .                off                (                )                ;                }                }                )                ;              

Example 2

Using isOn and isOff property to get the electric current state of any input/output object.

isOn and isOff are built-in own properties of input/output objects when they are created.

                const                r                =                require                (                'array-gpio'                )                ;                permit                sw                =                r                .                in                (                11                )                ;                let                led                =                r                .                out                (                33                )                ;                /* Check the electric current state of sw and led object */                console                .                log                (                sw1                .                isOn                )                ;                // fake                panel                .                log                (                led                .                isOn                )                ;                // false                panel                .                log                (                sw1                .                isOff                )                ;                // truthful                console                .                log                (                led                .                isOff                )                ;                // true              

Example iii

Turning on and off a GPIO output with a filibuster

                /* With momentary switch buttons continued on pivot 11 and thirteen and an led on pivot 33 */                const                {setInput,                setOutput,                watchInput}                =                crave                (                'array-gpio'                )                ;                permit                sw1                =                setInput                (                11                )                ;                permit                sw2                =                setInput                (                13                )                ;                let                led                =                setOutput                (                33                )                ;                watchInput                (                (                )                =>                {                if                (                sw1                .                isOn                )                {                // pressing sw1, the led will turn on after 1000 ms or 1 sec delay                led                .                on                (                yard                )                ;                }                else                if                (                sw2                .                isOn                )                {                // pressing sw2, the led will plough off after 500 ms or 0.5 sec delay                                led                .                off                (                500                )                ;                }                }                )                ;              

Example 4

Create an input/output array object

                /* Connect a momentary switch push button for each input pin and an led for each output pin */                const                r                =                crave                (                'array-gpio'                )                ;                const                sw                =                r                .                in                (                {                pivot:[                xi                ,                13                ]                ,                alphabetize:'pin'                }                )                ;                const                led                =                r                .                out                (                {                pin:[                33                ,                35                ,                37                ,                36                ,                38                ,                40                ]                ,                index:'pivot'                }                )                ;                // turn on the led'due south sequentially                let                LedOn                =                (                )                =>                {                let                t                =                0                ;                // initial on fourth dimension delay in ms                for                (                let                x                in                led                )                {                t                +=                50                ;                led                [                x                ]                .                on                (                t                )                ;                }                }                // plough off the led's sequentially                let                LedOff                =                (                )                =>                {                let                t                =                0                ;                // initial off time delay in ms                for                (                allow                x                in                led                )                {                t                +=                l                ;                led                [                10                ]                .                off                (                t                )                ;                }                }                r                .                watchInput                (                (                )                =>                {                if                (                sw                [                11                ]                .                isOn                )                {                LedOn                (                )                ;                }                else                if                (                sw                [                13                ]                .                isOn                )                {                LedOff                (                )                ;                }                }                )                ;              

Using forEach to iterate over assortment objects

                const                {setInput,                setOutput,                watchInput}                =                require                (                'array-gpio'                )                ;                const                sw                =                setInput                (                {                pivot:[                xi                ,                13                ]                ,                alphabetize:'pin'                }                )                ;                const                led                =                setOutput                (                {                pin:[                33                ,                35                ,                37                ,                36                ,                38                ,                40                ]                ,                index:'pin'                }                )                ;                let                LedOn                =                (                )                =>                {                let                t                =                0                ;                led                .                forEach                (                (                output                )                =>                {                t                +=                50                ;                output                .                on                (                t                )                ;                }                )                }                let                LedOff                =                (                )                =>                {                let                t                =                0                ;                led                .                forEach                (                (                output                )                =>                {                t                +=                l                ;                output                .                off                (                t                )                ;                }                )                }                watchInput                (                (                )                =>                {                sw                .                forEach                (                (                input                )                =>                {                if                (                input                .                pin                ===                xi                &&                input                .                isOn                )                {                ledOn                (                )                ;                }                else                if                (                input                .                pivot                ===                13                &&                input                .                isOn                )                {                ledOff                (                )                ;                }                }                )                }                )                ;              

Example 5

Create a elementary GPIO output pulse

                /* With momentary switch buttons connected on pin 11, 13, xv and an led on pivot 33 */                const                {setInput,                setOutput,                watchInput}                =                require                (                'array-gpio'                )                ;                let                sw1                =                setInput                (                11                )                ;                permit                sw2                =                setInput                (                13                )                ;                permit                sw3                =                setInput                (                15                )                ;                allow                led                =                setOutput                (                33                )                ;                watchInput                (                (                )                =>                {                // press sw1 to pulse the led with a duration of 50 ms                                if                (                sw1                .                isOn                )                {                led                .                pulse                (                l                )                ;                }                // press sw2 to pulse the led with a duration of 200 ms                else                if                (                sw2                .                isOn                )                {                led                .                pulse                (                200                )                ;                }                // printing sw3 to pulse the led with a elapsing of thousand ms or 1 sec                else                if                (                sw3                .                isOn                )                {                led                .                pulse                (                1000                )                ;                }                }                )                ;              

API

Notation:

This module uses pin numbering based on the physical pivot numbers one~40 from the board header.

setInput(arg)

or

in(arg)

Sets a GPIO pin or group of GPIO pins as input object.

arg

Whatever valid GPIO pin number or an input option argument.

Single Object

                const                r                =                require                (                'assortment-gpio'                )                ;                let                input                =                r                .                setInput                (                eleven                )                ;                // or                let                input                =                r                .                in                (                11                )                ;              

Array Object

                const                r                =                require                (                'array-gpio'                )                ;                let                inputOption                =                {                pin:                [                11                ,                13                ,                15                ]                }                ;                const                input                =                r                .                setInput                (                inputOption                )                ;                // or                const                input                =                r                .                in                (                inputOption                )                ;                // By default, the array object created is indexed using zero-based indexing                // (indexed from 0 to n-1, where due north is the array.length).                /* Become the current logical state of each input element */                console                .                log                (                input                [                0                ]                .                country                )                ;                console                .                log                (                input                [                one                ]                .                state                )                ;                panel                .                log                (                input                [                2                ]                .                state                )                ;              

To use the pivot equally index, add an index property to the object argument and set the value to 'pivot'.

                permit                inputOption                =                {                pivot:[                11                ,                thirteen                ,                15                ]                ,                index:                'pivot'                }                ;                const                input                =                r                .                setInput                (                inputOption                )                ;                /* Go the current logical state of each input chemical element using pin equally index */                panel                .                log                (                input                [                xi                ]                .                state                )                ;                console                .                log                (                input                [                13                ]                .                land                )                ;                console                .                log                (                input                [                fifteen                ]                .                state                )                ;                /* Iterate over the array object in both cases to access each input element */                for                (                let                x                in                input                )                {                console                .                log                (                input                [                ten                ]                .                isOn                )                ;                }                // or                input                .                forEach                (                part                (                inputObject                )                {                panel                .                log                (                inputObject                .                isOn                )                ;                }                )                ;              

country

input/output property

Gets the current digital logical state of an input/output object during runtime. It is a getter merely belongings.

Returns true if the object logical state is high or ON.

Returns false if the object logical state is low or OFF.

Example 1
                const                r                =                require                (                'array-gpio'                )                ;                permit                sensor                =                r                .                in                (                11                )                ;                // returns the current state of the sensor                console                .                log                (                sensor                .                state                )                ;                // false              
Instance 2
                const                r                =                require                (                'array-gpio'                )                ;                let                sw                =                r                .                in                (                11                )                ;                let                led                =                r                .                out                (                33                )                ;                sw                .                watch                (                function                (                )                {                if                (                sw                .                land                &&                !                led                .                land                )                {                console                .                log                (                sw                .                state                )                ;                // true                console                .                log                (                led                .                state                )                ;                // fake                led                .                on                (                )                ;                console                .                log                (                sw                .                state                )                ;                // true                panel                .                log                (                led                .                land                )                ;                // true                }                }                )                ;              

isOn and isOff

input/output holding

Similar with the state property, it will render the current digital logical state of an input/output object with explicit context.

isOn - returns truthful if the object logical state is high or ON, otherwise it returns false.

isOff - returns true if the object logical state is depression or OFF, otherwise it returns imitation.

Instance
                const                r                =                crave                (                'array-gpio'                )                ;                allow                sw1                =                r                .                in                (                11                )                ;                let                sw2                =                r                .                in                (                xiii                )                ;                allow                led                =                r                .                out                (                33                )                ;                r                .                watchInput                (                (                )                =>                {                // turns on led if sw1 is on and if led is off                if                (                sw1                .                isOn                &&                led                .                isOff                )                {                led                .                on                (                )                ;                }                // turns off led if sw2 is on and if led is on                else                if                (                sw2                .                isOn                &&                led                .                isOn                )                {                led                .                off                (                )                ;                }                }                )                ;              

sentinel (edge, callback, [s])

input method

Watches the logical country of an input object for changes or land transitions.

edge

1 - sentinel state changes from low to loftier (fake to true) or rising border transition

0 - lookout man state changes from loftier to low (true to false) or falling edge transition

'both' - watches both state transitions

If edge argument is not provided, it volition lookout both transitions same as 'both'.

callback

The callback argument will be chosen asynchronously everytime a state transition is detected based on the in a higher place conditions.

You can passed an optional parameters country and pin respectively to the callback argument for any fine-grained awarding logic execution.

southward

This is an an optional browse rate statement in ms (milliseconds). If not provided, scan rate will default to 100 ms, minimum is 1 ms.

A lower value volition brand your input more responsive but contact bounce will increment. A higher value will make information technology less responsive merely with a lower contact bounciness.

Example1
                const                r                =                require                (                'array-gpio'                )                ;                let                sw                =                r                .                in                (                xi                )                ;                function                pinEvent                (                )                {                panel                .                log                (                'pinEvent invoked'                )                ;                }                // pinEvent will be invoked if sw state changes from imitation to truthful                sw                .                lookout man                (                i                ,                pinEvent                )                ;                // pinEvent will be invoked if sw country changes from true to false                sw                .                sentry                (                0                ,                pinEvent                )                ;                // border argument is not provided,                // pinEvent will be invoked if sw land changes from true to fake and vice versa                sw                .                watch                (                pinEvent                )                ;                // using a browse charge per unit of ten ms                sw                .                watch                (                pinEvent                ,                10                )                ;              
Instance ii
                const                r                =                require                (                'assortment-gpio'                )                ;                permit                sw1                =                r                .                in                (                11                )                ;                let                led                =                r                .                out                (                33                )                ;                // pressing the sw1 button will turn on the led then turns off afterward 1000 ms delay                // releasing the sw1 button will do cipher                sw1                .                watch                (                ane                ,                (                country                )                =>                {                if                (                country                )                {                led                .                on                (                )                ;                led                .                off                (                one thousand                )                ;                }                }                )                ;              

unwatch()

input method

Stops monitoring an input object from the .scout() method.

read([callback])

input/output method

The conventional style of getting the current logical state condition of an input/output object.

Returns logical 1 value if the object state is in high or ON country condition and 0 for low or OFF state condition.

The optional callback parameter will exist invoked asynchronously later on returning the object state condition.

This method is similar to country property only as a method holding, yous can use a callback statement to execute any additional application logic based on the object state condition.

Example
                const                r                =                require                (                'array-gpio'                )                ;                permit                sw                =                r                .                setInput                (                eleven                )                ;                let                solenoid                =                r                .                setOutput                (                35                )                ;                sw                .                read                (                (                state                )                =>                {                if                (                country                ===                i                )                solenoid                .                on                (                )                ;                else                solenoid                .                off                (                )                ;                }                )                ;              

pin

input/output property

Returns the GPIO pin used from whatever input/output objects.

Example
                const                r                =                require                (                'array-gpio'                )                ;                let                sw                =                r                .                setInput                (                11                )                ;                permit                led                =                r                .                setOutput                (                33                )                ;                console                .                log                (                sw                .                pin                )                ;                // 11                console                .                log                (                led                .                pivot                )                ;                // 33              

close()

input/output method

Closes an input/output object. Removes any events (pin watching) from the object and resets the pin to GPIO input.

Example 1
                const                r                =                require                (                'array-gpio'                )                ;                permit                sw                =                r                .                setInput                (                11                )                ;                let                led                =                r                .                setOutput                (                33                )                ;                sw                .                close                (                )                ;                led                .                close                (                )                ;              
Example 2
                const                r                =                crave                (                'array-gpio'                )                ;                let                input                =                r                .                setInput                (                {                pin:[                eleven                ,                xiii                ]                }                )                ;                permit                output                =                r                .                setOutput                (                {                pin:[                33                ,                35                ]                }                )                ;                role                appExitProcess                (                )                {                console                .                log                (                'closing all I/O objects'                )                ;                for                (                allow                x                in                input                )                {                input                [                x                ]                .                close                (                )                ;                }                for                (                allow                x                in                output                )                {                output                [                x                ]                .                shut                (                )                ;                }                }                // using Ctrl-C for app exit                procedure                .                on                (                'SIGINT'                ,                function                (                )                {                appExitProcess                (                )                ;                process                .                exit                (                0                )                ;                }                )                ;              

setR(value)

input method

Sets the internal resistor of an input pin using either pull up or pull down resistor.

value

'pu' or 1 - Enable internal pull up resistor.

'pd' or 0 - Enable internal pull down resistor.

If argument is not provided, no internal resistor will exist used.

Example
                const                r                =                require                (                'array-gpio'                )                ;                allow                sw                =                r                .                setInput                (                {                pin:[                xi                ,                13                ,                15                ]                }                )                ;                // using pull up resistor                sw                [                0                ]                .                setR                (                'pu'                )                ;                // using pull down resistor                sw                [                one                ]                .                setR                (                0                )                ;                // no internal resistor is used                sw                [                2                ]                .                setR                (                )                ;              

watchInput(callback, [s])

main module method

Monitor multiple input objects all at once from the main module using .watchInput() method.

It will lookout man both state transistions from low to high and vice versa for all inputs.

The callback argument is shared by all input objects. It will be invoked asynchronously if whatsoever of the input objects changes country.

You can passed an optional parameters - state and pin respectively to the callback argument for any fine-grained application logic execution.

s is an optional scan rate statement in ms (milliseconds). If not provided, scan rate volition default to 100 ms, minimum is one ms. A lower value will brand your input more responsive just contact bounce will increase. A higher value will get in less responsive but with a lower contact bounce.

To capture which input object state has changed, you tin can utilize each object's state or isOn property. Or use the pin argument from the callback when it is invoked for whatever state transitions.

Example 1
                const                r                =                require                (                'array-gpio'                )                ;                let                sw                =                r                .                in                (                {                pin:[                11                ,                13                ,                15                ]                ,                index:'pin'                }                )                ;                allow                led                =                r                .                out                (                {                pivot:[                33                ,                35                ]                ,                index:'pivot'                }                )                ;                r                .                watchInput                (                (                )                =>                {                // if sw[xi] is on, led[33] will plough on                if                (                sw                [                11                ]                .                isOn                )                {                led                [                33                ]                .                on                (                )                ;                }                // if sw[13] is on, led[35] will turn on                else                if                (                sw                [                13                ]                .                isOn                )                {                led                [                35                ]                .                on                (                )                ;                }                // if sw[xv] is on, both led[33] and led[35] will turn off                else                if                (                sw                [                15                ]                .                isOn                )                {                led                [                33                ]                .                off                (                )                ;                led                [                35                ]                .                off                (                )                ;                }                }                )                ;              
Example two
                const                r                =                crave                (                'array-gpio'                )                ;                permit                sw1                =                r                .                in                (                11                )                ;                let                sw2                =                r                .                in                (                13                )                ;                permit                led                =                r                .                out                (                35                )                ;                r                .                watchInput                (                (                state                ,                pin                )                =>                {                if                (                state                &&                sw1                .                pin                ===                pin                )                {                led                .                on                (                )                ;                }                else                if                (                state                &&                sw2                .                pin                ===                pivot                )                {                led                .                off                (                )                ;                }                }                )                ;              

unwatchInput()

main module method

Stop monitoring all the input objects from .watchInput() method. It will cease invoking the shared callback statement for whatever input state changes.

Instance
                const                r                =                require                (                'assortment-gpio'                )                ;                permit                sw1                =                r                .                in                (                xi                )                ;                let                sw2                =                r                .                in                (                xiii                )                ;                let                sw3                =                r                .                in                (                15                )                ;                let                led1                =                r                .                out                (                33                )                ;                allow                led2                =                r                .                out                (                35                )                ;                r                .                watchInput                (                (                )                =>                {                if                (                sw1                .                state                )                {                return                led1                .                on                (                )                ;                }                if                (                sw2                .                state                )                {                return                led2                .                on                (                )                ;                }                if                (                sw3                .                land                )                {                led1                .                off                (                )                ;                led2                .                off                (                )                ;                }                }                )                ;                // stops all input pin monitoring afterward 15 secs                setTimeout                (                (                )                =>                r                .                unwatchInput                (                )                ,                15000                )                ;              

setOutput(arg)

or

out(arg)

main module method

Sets a GPIO pin or group of GPIO pins as output object.

arg

Any valid GPIO pin number or an output option statement.

Single Object

                const                r                =                require                (                'array-gpio'                )                ;                /* creates a single output object */                allow                led                =                r                .                setOutput                (                33                )                ;                // or                let                led                =                r                .                out                (                33                )                ;                /* turn on the led */                led                .                on                (                )                ;              

Array Object

                const                r                =                require                (                'array-gpio'                )                ;                /* creates an array output object */                let                outputOption                =                {                pivot:[                33                ,                35                ,                36                ]                }                ;                const                output                =                r                .                setOutput                (                outputOption                )                ;                // or                const                output                =                r                .                out                (                outputOption                )                ;                // Similar with input, the array object created is indexed using zero-based indexing                // (indexed from 0 to n-1, where n is the array.length).                /* Get the electric current logical state of each output element */                console                .                log                (                output                [                0                ]                .                state                )                ;                panel                .                log                (                output                [                one                ]                .                state                )                ;                console                .                log                (                output                [                ii                ]                .                state                )                ;              

To employ the pin every bit alphabetize, add together an index property to the object statement and set up the value to 'pin'.

                let                outputOption                =                {                pivot:[                33                ,                35                ,                36                ]                ,                index:'pin'                }                ;                const                output                =                r                .                setOutput                (                outputOption                )                ;                /* Go the current logical state of each output element using pivot as index */                console                .                log                (                output                [                33                ]                .                country                )                ;                panel                .                log                (                output                [                35                ]                .                state                )                ;                console                .                log                (                output                [                36                ]                .                state                )                ;                // iterate over the assortment object in both cases to admission each output element                for                (                let                ten                in                output                )                {                output                [                ten                ]                .                on                (                )                ;                }                // or                output                .                forEach                (                function                (                outputObject                )                {                outputObject                .                on                (                )                ;                }                )                ;              

on([t],[callback]) and off([t],[callback])

output method

Sets the state of an output object to logical loftier land status (true) or low land status (simulated).

t is an optional fourth dimension delay in milliseconds.

The state will change later on the duration of time filibuster t.

callback

The optional callback argument volition exist invoked asynchronously later the output state has changed.

You can passed an optional parameter state for any fine-grained application logic execution.

Example
                const                r                =                crave                (                'array-gpio'                )                ;                let                sw1                =                r                .                in                (                11                )                ;                allow                sw2                =                r                .                in                (                thirteen                )                ;                let                actuator1                =                r                .                out                (                33                )                ;                let                actuator2                =                r                .                out                (                35                )                ;                r                .                watchInput                (                (                )                =>                {                if                (                sw1                .                isOn                &&                actuator1                .                isOff                )                {                actuator1                .                on                (                200                )                ;                // turns on subsequently 200 ms delay                actuator2                .                on                (                (                land                )                =>                {                if                (                state                )                {                console                .                log                (                'actuator2 is on'                )                ;                }                }                )                ;                }                else                if                (                sw2                .                isOn                &&                actuator2                .                isOn                )                {                actuator1                .                off                (                50                )                ;                // turns off afterward 50 ms delay                actuator2                .                off                (                (                state                )                =>                {                if                (                !                state                )                {                console                .                log                (                'actuator2 is off'                )                ;                }                }                )                ;                }                }                )                ;              

write(bit [,callback])

output method

This is the conventional way of setting the ouput state to high or low land condition.

bit - command bit value.

1 or true - loftier or ON state

0 or false - low or OFF land

callback

The optional callback argument will exist invoked asynchronously afterward the output state has changed.

Yous can passed an optional parameter country for whatever fine-grained application logic execution.

Example
                const                {setInput,                setOutput,                watchInput}                =                crave                (                'assortment-gpio'                )                ;                const                sw                =                setInput                (                11                ,                thirteen                )                ;                const                motor                =                setOutput                (                33                ,                35                )                ;                let                sw1                =                sw                [                0                ]                ;                let                sw2                =                sw                [                1                ]                ;                let                motorA                =                motor                [                0                ]                ;                permit                motorB                =                motor                [                ane                ]                ;                watchInput                (                (                state                )                =>                {                if                (                sw1                .                read                (                )                )                {                motorA                .                write                (                state                ,                (                )                =>                motorB                .                write                (                !                land                )                )                ;                }                if                (                sw2                .                read                (                )                )                {                motorB                .                write                (                state                ,                (                )                =>                motorA                .                write                (                !                country                )                )                ;                }                }                )                ;              

pulse(pow [,callback])

output method

Generates a single square moving ridge pulse with a elapsing of pw.

pw

This is the pulse width in milliseconds or the time duration of the pulse.

callback

The optional callback argument will be invoked asynchronously when pw time duration expires.

Instance
                const                r                =                require                (                'array-gpio'                )                ;                let                sw1                =                r                .                in                (                xi                )                ;                let                sw2                =                r                .                in                (                thirteen                )                ;                let                actuator                =                r                .                out                (                {                pivot:[                33                ,                35                ]                }                )                ;                r                .                watchInput                (                (                )                =>                {                // starts a unmarried pulse w/ a duration of 1 sec                if                (                sw1                .                isOn                &&                actuator                [                0                ]                .                isOff                )                {                actuator                [                0                ]                .                pulse                (                thou                )                ;                }                // starts a single pulse w/ a elapsing of 2 secs                else                if                (                sw2                .                isOn                &&                actuator                [                one                ]                .                isOff                )                {                console                .                log                (                'start of actuator[one] pulse'                )                ;                actuator                [                ane                ]                .                pulse                (                3000                ,                (                )                =>                {                panel                .                log                (                'cease of actuator[i] pulse'                )                ;                }                )                ;                }                }                )                ;              

Note: Currently PWM will piece of work on all Raspberry Pi models except on Raspberry Pi 4B model due to firmware bug. Hopefully, it volition be stock-still in the side by side latest release of Raspbian Bone.

setPWM(pin)

Sets GPIO pins 12 and 33 to alternating office 0 (ALT0) and sets pins 12 and 35 to alternate part v (ALT5) for PWM operations.

Creates a pwm object to start PWM to the provided GPIO pin.

This operation requires root access.

pivot

Channel one - pins 12 and 32.

Channel 2 - pins 33 and 35.

You can only command 2 peripherals independently, one from channel ane and one from channel 2. If both peripherals are from the same channel, you can control both channels using but the command values (setRange and setData) from one of the peripherals.

setClockFreq(div)

div

The divisor value to calculate the desired clock frequency from a fixed oscillator freq of 19.two MHz.

(0 to 4095)

freq = 19200000/div

setRange(range)

Sets the menstruation T of the pwm pulse.

range The period T of the pulse

setData(information)

Sets the prisoner of war (pulse width) of the pwm pulse.

data The pulse width of the pulse

stop()

Stops temporarily the pulse generation from the system 19.2 MHz clock oscillator.

You tin restart the pulse generation at anytime by calling the .pulse() or .setData() method.

close()

Stops PWM operations on the GPIO pin. Resets the pin to GPIO input.

Example 1

                /* Connect an led to pin 12. */                /* r for raspberry pi */                const                r                =                require                (                'array-gpio'                )                ;                /* create a pwm object using pivot 12 */                var                pwm                =                r                .                setPWM                (                12                )                ;                /* set the pwm clock frequency using a div value of 1920 */                pwm                .                setClockFreq                (                1920                )                ;                // sets clock freq to 10kHz or 0.one ms time resolution for T and pw                /* set period (T) of the pulse */                pwm                .                setRange                (                m                )                ;                // k x 0.1 ms = 100 ms (bodily period T)                /*                                  * prepare pw (pulse width) of the pulse and beginning the pulse generation for 2 seconds                                  *                                  * The led attached to pin 12 should glimmer for two seconds                                  */                pwm                .                setData                (                100                )                ;                // 100 ten 0.1 ms = 10 ms (actual pw)                /* stop the pwm operation and reset pivot 12 to GPIO input afterwards two secs */                setTimeout                (                function                (                )                {                pwm                .                stop                (                )                ;                pwm                .                close                (                )                ;                }                ,                2000                )                ;              

setPWM(pivot, freq, T, pw)

Creates a pwm object from a predefined clock frequencies of 10, 100, or 1000 kHz that volition provide different time resolutions for the T (menstruation) and pw (pulse width) of your desired pwm pulse.

pin

Choose from channel 1 (12, 32) or channel ii (33, 35).

freq (kHz)

Choose a predefined clock oscillator frequency of 10, 100, or one thousand kHz

x kHz provides 0.1 ms resolution

100 kHz provides 0.01 ms resolution

thousand kHz provides 0.001 ms or one u.s. (microsecond) resolution

T (ms)

The initial bicycle menstruation of the pulse.

pw (ms)

The initial pulse width of the pulse.

The ratio of pw over T is the pulse duty cycle (pw/T) 10 100%.

pulse([pw])

Beginning the pulse generation or generates a new pulse using the pw argument provided. If pw statement is not provided, information technology volition use the initial pw argument used in .setPWM() constructor and offset the pulse generation.

prisoner of war (ms) is the pulse width that will be used to generate a new pulse.

You tin can change the menstruum T of the pulse using the .setRange() and the pulse width prisoner of war using .setData() or .pulse() method at anytime in your application.

Even so in servo motor applications, the catamenia T is usually fixed while changes in pulse width pw controls the rotational position of your servo motors.

Example 2

                /* Using a generic micro servo motor (~4.8 to half dozen.0 Five)                                  *                                  * T = 20 ms (pulse period)                                  *                                  * pw (pulse width) needed for diverse servo positions                                  *                                  * pow 1.0 ms - pos ane, domicile position                                  * pw ane.five ms - pos 2, rotates xl degrees cw (clockwise) from pos 1                                  * pw two.0 ms - pos 3, rotates fourscore degress cw from pos i                                  * pw 2.v ms - pos 4, rotates 120 degress cw from pos i                                  *                                  */                const                r                =                require                (                'array-gpio'                )                ;                var                pin                =                33                ;                /* pin from aqueduct ii */                var                freq                =                ten                ;                /* using x kHz clock frequency that will provide a 0.i ms fourth dimension resolution */                var                T                =                200                ;                /* Use 200 to go the 20 ms menstruation (200 x 0.1 ms = twenty ms) */                var                prisoner of war                =                ten                ;                /* Use 10 to get an initial pulse width of 1.0 ms (ten 10 0.one ms = 1.0 ms), home position */                /* initialize PWM using with above pin, freq, T and pw details */                var                pwm                =                r                .                setPWM                (                pin                ,                freq                ,                T                ,                pow                )                ;                /* create four push buttons sw[0], sw[ane], sw[ii] and sw[4] */                const                sw                =                r                .                setInput                (                {                pin:[                xi                ,                thirteen                ,                15                ,                19                ]                }                )                ;                r                .                watchInput                (                (                )                =>                {                /* Press sw[0] push to rotate the servo motor to pos ane or habitation position */                if                (                sw                [                0                ]                .                isOn                )                {                pwm                .                pulse                (                10                )                ;                // 1.0 ms pow                }                /* Press sw[1] button to rotate to pos 2 */                else                if                (                sw                [                ane                ]                .                isOn                )                {                pwm                .                pulse                (                15                )                ;                // 1.5 ms pw                }                /* Press sw[2] button to rotate to pos iii */                else                if                (                sw                [                ii                ]                .                isOn                )                {                pwm                .                pulse                (                20                )                ;                // 2.0 ms pw                }                /* Press sw[3] button to rotate to pos 4 */                else                if                (                sw                [                three                ]                .                isOn                )                {                pwm                .                pulse                (                25                )                ;                // 2.5 ms pw                }                }                )                ;                const                appExitProcess                =                (                )                =>                {                console                .                log                (                'endmost all sw and pwm objects'                )                ;                for                (                let                ten                in                sw                )                {                sw                [                x                ]                .                shut                (                )                ;                }                pwm                .                shut                (                )                ;                process                .                exit                (                0                )                ;                }                process                .                on                (                'SIGINT'                ,                (                )                =>                {                panel                .                log                (                '\napp terminated using Ctrl-C'                )                ;                appExitProcess                (                )                ;                }                )                ;              

setI2C()

Sets i2c pins 03 (SDA) and 05 (SCL) to its alternate function (ALT0) for i2c operation.

Returns an i2c object with properties to configure the I2C interface to start the i2c data transfer operation.

This operation requires root access.

brainstorm()

Starts i2c functioning in your application. This operation is integrated in setI2C() method, so there is no need to phone call it explicitly to commencement the i2c functioning.

end()

Stops i2c operation and resets i2c pins 03 (SDA) and 05 (SCL) to GPIO input pins.

setTransferSpeed(baud)

Sets the i2c clock frequency by converting the baud argument to the equivalent i2c clock divider value.

setClockFreq(div)

Sets the i2c clock speed based on the div divisor value. Check the diverse div values below and the possible clock speeds that will be generated.

              div 2500 => 10us => 100 kHz div 626  => 2.504us => 399.3610 kHz div 150  => 60ns => 1.666 MHz (default at reset) div 148  => 59ns => 1.689 MHz                          

selectSlave(addr)

Sets the i2c address of the slave device.

addr

The i2c address of the slave device.

write(wbuf, len)

Write a number of bytes to the currently selected i2c slave device.

wbuf The actual data bytes to send/write to the selected i2c slave device.

len The length of bytes or full number of bytes to send/write to the selected i2c slave device.

read(rbuf, len)

Read a number of bytes from the currently selected i2c slave device.

rbuf The actual data bytes to read/receive from the selected i2c slave device.

len The length of bytes or total number of bytes to read/receive from the selected i2c slave device.

Example

                /* Using MCP9808 Temperature Sensor                                  *                                                  * Please read the MCP9808 datasheet on how to configure the flake for more details.                                  */                const                r                =                crave                (                'array-gpio'                )                ;                var                i2c                =                r                .                setI2C                (                )                ;                /* set up data transfer speed to 400 kHz */                i2c                .                setTransferSpeed                (                400000                )                ;                /* MCP9808 hardware device accost */                let                addr                =                0x18                ;                /* select the MCP9808 device for data trasfer */                i2c                .                selectSlave                (                addr                )                ;                /* setup the application read and write data buffer */                const                wbuf                =                Buffer                .                alloc                (                16                )                ;                // write buffer                const                rbuf                =                Buffer                .                alloc                (                16                )                ;                // read buffer                /* accessing the internal 16-bit manufacturer ID register within MCP9808 */                wbuf                [                0                ]                =                0x06                ;                // from the MCP9808 datasheet, ready the accost of the manufacturer ID annals to the write buffer                i2c                .                write                (                wbuf                ,                1                )                ;                // writes 1 information byte to the slave device selecting the MCP9808 manufacturer ID register for data access                /* master (rpi) device volition now read the content of the 16-flake manufacturer ID register (should be 0x54 as per datasheet) */                /* reading 2 data bytes - the upper byte (rbuf[0]) and lower byte (rbuf[1]) from the manufacturer ID register, ID value is on the lower byte from the datasheet */                i2c                .                read                (                rbuf                ,                two                )                ;                console                .                log                (                'MCP9808 ID: '                ,                rbuf                [                ane                ]                .                toString                (                16                )                )                ;                // convert the ID value to hex value                /* Based on MCP9808 datasheet, compute the temperature data equally follows */                part                getTemp                (                )                {                /* variable for temperature information */                let                Temp                ;                let                UpperByte                =                rbuf                [                0                ]                ;                let                LowerByte                =                rbuf                [                one                ]                ;                UpperByte                =                UpperByte                &                0x1F                ;                // Clear flag bits                /* Temp < 0 C */                if                (                (                UpperByte                &                0x10                )                ==                0x10                )                {                UpperByte                =                UpperByte                &                0x0F                ;                // Clear SIGN                Temp                =                256                -                (                (                UpperByte                *                xvi                )                +                (                LowerByte                /                16                )                )                ;                /* Temp > 0 C */                }                else                {                Temp                =                (                (                UpperByte                *                sixteen                )                +                (                LowerByte                /                16                )                )                ;                }                /* Impress out temperature information */                console                .                log                (                'Temp: '                ,                Temp                )                ;                }                /* get temperature readings every ii seconds */                setInterval                (                office                (                )                {                /* accessing the internal 16-flake configuration annals within MCP9808                                  You lot can skip accessing this register using default settings */                wbuf                [                0                ]                =                0x01                ;                // address of the configuration annals                /* change content of configuration register */                wbuf                [                i                ]                =                0x02                ;                // register upper byte, THYST set with +1.5 C                wbuf                [                ii                ]                =                0x00                ;                // annals lower byte (ability up defaults)                i2c                .                write                (                wbuf                ,                iii                )                ;                /* accessing the internal sixteen-chip ambient temp register within MCP9808 */                wbuf                [                0                ]                =                0x05                ;                // accost of ambience temperature register                i2c                .                write                (                wbuf                ,                1                )                ;                /* read the content of ambient temp register */                i2c                .                read                (                rbuf                ,                ii                )                ;                // read the UpperByte and LowerByte data                /* go temperature information and impress out the results */                getTemp                (                )                ;                }                ,                2000                )                ;                process                .                on                (                'SIGINT'                ,                part                (                )                {                console                .                log                (                '\napp terminated using Ctrl-C'                )                ;                i2c                .                stop                (                )                ;                process                .                exit                (                0                )                ;                }                )                ;              

setSPI()

Sets SPI0 bus pins nineteen (MOSI), 21 (MISO), 23 (CLK), 24 (CE0) and 26 (CE1) to its alternating part (ALT0) for spi functioning.

Returns an spi object with backdrop to configure the SPI interface.

This operation requires root access.

begin()

Initializes the SPI0 passenger vehicle pins for spi functioning. This procedure is integrated in setSPI() method, so in that location is no need to call it explicitly to start the spi operation.

setClockFreq(div)

Sets the SPI clock frequency using a divisor value.

Clock is based on the nominal core clock charge per unit of 250MHz on RPi1 and RPi2, and 400MHz on RPi3.

div

The SPI divisor to generate the SPI clock frequency.

The data beneath shows the various div value and the clock frequency in kHz that will be generated.

              SPI div  2048  = 122.0703125kHz on Rpi2, 195.3125kHz on RPI3 SPI div  1024  = 244.140625kHz on Rpi2, 390.625kHz on RPI3 SPI div  512   = 488.28125kHz on Rpi2, 781.25kHz on RPI3 SPI div  256   = 976.5625kHz on Rpi2, 1.5625MHz on RPI3 SPI div  128   = i.953125MHz on Rpi2, 3.125MHz on RPI3 (default) SPI div  64    = 3.90625MHz on Rpi2, vi.250MHz on RPI3 SPI div  32    = 7.8125MHz on Rpi2, 12.5MHz on RPI3 SPI div  16    = xv.625MHz on Rpi2, 25MHz on RPI3 SPI div  8     = 31.25MHz on Rpi2, 50MHz on RPI3                          

chipSelect(cs)

Sets the chip select pivot(s).

When data transfer starts, the selected pin(s) will exist asserted or held in agile state (normally active low) during information transfer.

cs

Cull from i of cs values beneath.

              cs = 0,  Fleck Select 0 cs = 1,  Chip Select 1 cs = 2,  Chip Select ii cs = 3,  No Chip Select                          

setCSPolarity(cs, agile)

Change the active state of the bit select pin.

cs

The chip select pivot you want to change the active country.

active

Select 0 for active low or 1 for active high country.

setDataMode(mode)

Sets the SPI data mode, the clock polariy (CPOL) and phase (CPHA).

mode

Cull from one of SPI mode beneath.

              mode = 0,  CPOL = 0, CPHA = 0 mode = i,  CPOL = 0, CPHA = 1 mode = two,  CPOL = one, CPHA = 0 manner = 3,  CPOL = ane, CPHA = 1                          

transfer(wbuf, rbuf, len)

Transfers whatsoever number of bytes to and from the currently selected spi slave device. This method makes it possible to perform simultaneous write and read operations for engagement transfer.

Selected CS pins (every bit previously set past chipSelect) volition be held in active state during the data transfer.

wbuf The actual data bytes to send/write to the selected spi slave device.

rbuf The bodily data bytes to read/receive from the selected spi slave device.

len The length of bytes or full number of bytes to send/receive from/to the selected spi device.

write(wbuf, len)

Write a number of bytes to the currently selected spi slave flake.

Asserts the currently selected CS pins (as previously gear up by chipSelect) during the information transfer operations.

wbuf The actual bytes to write/send to the selected spi slave device.

len The length of bytes or total number of bytes to write/send to the selected spi slave device.

read(rbuf, len)

Read a number of bytes from the currently selected spi slave device.

rbuf The actual data bytes to read/receive from the selected spi slave device.

len The length of bytes or full number of bytes to read/receive from the spi slave device.

end()

Stops the SPI data transfer operations. SPI0 pins 19 (MOSI), 21 (MISO), 23 (CLK), 24 (CE0) and 26 (CE1) are reset to GPIO input pins.

Example

                /* Using MCP3008 10-bit A/D Converter Fleck                                  *                                  * In this example, nosotros will connect the Vdd and Vref pins to the Raspberry Pi's 3.3 5.                                  * Channel 0 (pin 1) will be used for analog input voltage using unmarried-ended mode.                                  *                                  * Please read the MCP3008 datasheet on how to configure the chip for more details.                                  */                const                r                =                crave                (                'array-gpio'                )                ;                var                spi                =                r                .                setSPI                (                )                ;                spi                .                setDataMode                (                0                )                ;                spi                .                setClockFreq                (                128                )                ;                spi                .                setCSPolarity                (                0                ,                0                )                ;                spi                .                chipSelect                (                0                )                ;                /* setup write and read data buffer */                const                wbuf                =                Buffer                .                alloc                (                sixteen                )                ;                // write buffer                const                rbuf                =                Buffer                .                alloc                (                16                )                ;                // read buffer                /* configure the fleck to employ CH0 in single-concluded mode */                wbuf                [                0                ]                =                0x01                ;                // start bit                wbuf                [                one                ]                =                0x80                ;                // using channel 0, single ended                wbuf                [                2                ]                =                0x00                ;                // don't care information byte every bit per datasheet                spi                .                write                (                wbuf                ,                iii                )                ;                // write 3 bytes to slave                /* alternative manner to write and read to a slave at the same fourth dimension */                //spi.transfer(wbuf, rbuf, iii); // iii bytes volition be sent to slave and 3 bytes to read                spi                .                read                (                rbuf                ,                three                )                ;                // read iii bytes from slave                /* read A/D conversion result */                /* the 1st byte received through rbuf[0] will exist discarded every bit per datasheet */                var                data1                =                rbuf                [                1                ]                <<                8                ;                // 2nd byte, using just ii bits data                var                data2                =                rbuf                [                2                ]                ;                // tertiary byte, eight bits data                var                value                =                data1                +                data2                ;                // combine both information to create a 10-fleck digital output code                console                .                log                (                "* A/D digital output code: "                ,                value                )                ;                /* compute the output voltage */                var                vout                =                (                value                *                3.3                )                /                1024                ;                console                .                log                (                "* A/D voltage output: "                ,                vout                )                ;                spi                .                end                (                )                ;              

tranmookedis.blogspot.com

Source: https://www.npmjs.com/package/array-gpio

0 Response to "Raspberry Pi Gpio How to Read Variable Input Bytes"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel