Giter Club home page Giter Club logo

spi-device's Introduction

Build Status npm Version Downloads Per Month Mentioned in Awesome Node.js

spi-device

SPI serial bus access with Node.js on Linux boards like the Raspberry Pi or BeagleBone. All methods have asynchronous and synchronous forms.

spi-device supports Node.js versions 10, 12, 14, 15 and 16.

Contents

Installation

npm install spi-device

Usage

Determine the temperature using a TMP36 analog temperature sensor wired to channel 5 on an MCP3008 SPI A/D converter.

const spi = require('spi-device');

// The MCP3008 is on bus 0 and it's device 0
const mcp3008 = spi.open(0, 0, err => {
  // An SPI message is an array of one or more read+write transfers
  const message = [{
    sendBuffer: Buffer.from([0x01, 0xd0, 0x00]), // Sent to read channel 5
    receiveBuffer: Buffer.alloc(3),              // Raw data read from channel 5
    byteLength: 3,
    speedHz: 20000 // Use a low bus speed to get a good reading from the TMP36
  }];

  if (err) throw err;

  mcp3008.transfer(message, (err, message) => {
    if (err) throw err;

    // Convert raw value from sensor to celcius and log to console
    const rawValue = ((message[0].receiveBuffer[1] & 0x03) << 8) +
      message[0].receiveBuffer[2];
    const voltage = rawValue * 3.3 / 1023;
    const celcius = (voltage - 0.5) * 100;

    console.log(celcius);
  });
});

spi-device enables low-level access to SPI devices. Often, high-level access is required. When this is the case, high-level packages can be built using spi-device. An example of such a package is mcp-spi-adc which provides a high-level API for accessing an MCP3008 SPI A/D converter and will generally be more useful than the low-level demonstration code shown above.

API Documentation

All methods have asynchronous and synchronous forms.

The asynchronous form always take a completion callback as its last argument. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation was completed successfully, then the first argument will be null or undefined.

When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions or allow them to bubble up.

Functions

Class SpiDevice

Constants

open(busNumber, deviceNumber[, options], cb)

  • busNumber - the number of the SPI bus to open, 0 for /dev/spidev0.n, 1 for /dev/spidev1.n, ...
  • deviceNumber - the number of the SPI device to open, 0 for /dev/spidevn.0, 1 for /dev/spidevn.1, ...
  • options - an optional object specifying device configuration options
  • cb - completion callback

Asynchronous open. Returns a new SpiDevice object. The completion callback gets one argument (err). The SpiDevice object returned should not be used before the completion callback is called.

openSync(busNumber, deviceNumber[, options])

  • busNumber - the number of the SPI bus to open, 0 for /dev/spidev0.n, 1 for /dev/spidev1.n, ...
  • deviceNumber - the number of the SPI device to open, 0 for /dev/spidevn.0, 1 for /dev/spidevn.1, ...
  • options - an optional object specifying device configuration options

Synchronous open. Returns a new SpiDevice object.

device.transfer(message, cb)

  • message - an array of one or more read+write transfers
  • cb - completion callback

Asynchronous message transfer. An SPI message is an array of one or more read+write transfers. The completion callback gets two arguments (err, message). Returns this.

device.transferSync(message)

  • message - an array of one or more read+write transfers

Synchronous message transfer. An SPI message is an array of one or more read+write transfers. Returns this.

device.getOptions(cb)

  • cb - completion callback

Asynchronously read device configuration options. The completion callback gets two arguments (err, options) where options is an object describing the device configuration options. Returns this.

device.getOptionsSync()

Synchronously read device configuration options. Returns an object describing the device configuration options.

device.setOptions(options, cb)

Asynchronously write device configuration options. The completion callback gets one argument (err). Returns this.

device.setOptionsSync(options)

Synchronously write device configuration options. Returns this.

device.close(cb)

  • cb - completion callback

Asynchronous close. Frees system resources used by this instance. The completion callback gets one argument (err). Returns null.

device.closeSync()

Synchronous close. Frees system resources used by this instance. Returns null.

MODE0

SPI mode number 0.

MODE1

SPI mode number 1.

MODE2

SPI mode number 2.

MODE3

SPI mode number 3.

Message

An SPI message is an array of one or more read+write transfers. A transfer is an object with the properties listed below. Most of the properties are optional. Note that although both sendBuffer and receiveBuffer are optional, at least one one of them must be specified.

  • byteLength - number, 32-bit, the number of bytes to transfer
  • sendBuffer - optional Buffer, transmit data
  • receiveBuffer - optional Buffer, receive data
  • speedHz - optional number, 32-bit, override of the device's clock frequency in Hertz
  • microSecondDelay - optional number, 16-bit, delay after the last bit transfer before optionally deselecting the device before the next transfer, default 0
  • bitsPerWord - optional number, 8-bit, override of the device's wordsize
  • chipSelectChange - optional boolean, true to deselect device before starting the next transfer, default false

Configuration Options

Device configuration options can be optionally specified when a device is opened with the open or openSync methods. They can also be specified at a later point with the setOptions or setOptionsSync methods. When calling these methods, only the options that need to be set need to be specified in the options object passed to those methods. All options are optional and the appropriate defaults will be used for options that are not specified.

The options supported varies from system to system and will depend on the device drivers used on those systems.

Configurations options can be read with the getOptions and getOptionsSync methods.

IMPORTANT The semantics of chipSelectHigh have changed with Linux kernel 5. To the best of my knowledge, the chipSelectHigh option no longer serves any purpose when used from user space with Linux kernel 5 and should not be used. With Linux kernel 5, the chip select is assumed to be active low. With Linux kernel 5, if an SPI device has has active high chip select, it's chip select must be controlled manually with a GPIO using a module such as onoff. The chipSelectHigh option has been crossed out below but it's still available for usage on older kernels.

  • mode - number, 2-bit, MODE0, MODE1, MODE2, or MODE3, default MODE0
  • chipSelectHigh - boolean, true for active high chip select, default false
  • lsbFirst - boolean, true for least significant bit first transfer, default false
  • threeWire - boolean, true for shared MISO/MOSI signals, default false
  • loopback - boolean, true for loopback mode, default false
  • noChipSelect - boolean, true for 1 device per bus, no chip select, default false
  • ready - boolean, true if device pulls low to pause, default false
  • bitsPerWord - number, 8-bit, device word size, default 8
  • maxSpeedHz - number, 32-bit, device clock frequency in Hertz, default system specific

spi-device's People

Contributors

fivdi avatar huming2207 avatar maxtruxa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

spi-device's Issues

can't change chipSelectHigh

Looks default chipSelectHigh value is set to true. Updating chipSelectHigh to false either while opening device or using setOptionsSync/setOptions does not change the default and still set to true.

node-gyp fails on armv7 32bit

I'm on Arch Linux ARM for amv7h, 32bit.

node-gyp fails with:

[alarm@lio-sta-001 MySpiTool]$ npm install
npm ERR! code 1
npm ERR! path /home/alarm/MySpiTool/node_modules/spi-device
npm ERR! command failed
npm ERR! command sh -c node-gyp rebuild
npm ERR! make: Entering directory '/home/alarm/MySpiTool/node_modules/spi-device/build'
npm ERR!   CXX(target) Release/obj.target/spi/src/spi.o
npm ERR!   CXX(target) Release/obj.target/spi/src/spidevice.o
npm ERR!   CXX(target) Release/obj.target/spi/src/open.o
npm ERR!   CXX(target) Release/obj.target/spi/src/close.o
npm ERR!   CXX(target) Release/obj.target/spi/src/transfer.o
npm ERR!   CXX(target) Release/obj.target/spi/src/getoptions.o
npm ERR! make: Leaving directory '/home/alarm/MySpiTool/node_modules/spi-device/build'
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using [email protected]
npm ERR! gyp info using [email protected] | linux | arm
npm ERR! gyp info find Python using Python version 3.9.5 found at "/usr/bin/python3"
npm ERR! gyp info spawn /usr/bin/python3
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/usr/lib/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/home/alarm/MySpiTool/node_modules/spi-device/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/usr/lib/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/home/alarm/.cache/node-gyp/14.16.0/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/home/alarm/.cache/node-gyp/14.16.0',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/usr/lib/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/home/alarm/.cache/node-gyp/14.16.0/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/home/alarm/MySpiTool/node_modules/spi-device',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp info spawn make
npm ERR! gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
npm ERR! In file included from ../../nan/nan.h:290,
npm ERR!                  from ../src/getoptions.cc:4:
npm ERR! ../../nan/nan_new.h: In instantiation of ‘typename Nan::imp::Factory<T>::return_t Nan::New(A0) [with T = v8::Uint32; A0 = long unsigned int; typename Nan::imp::Factory<T>::return_t = v8::Local<v8::Uint32>]’:
npm ERR! ../src/getoptions.cc:35:65:   required from here
npm ERR! ../../nan/nan_new.h:208:30: error: call of overloaded ‘New(long unsigned int&)’ is ambiguous
npm ERR!   208 |   return imp::Factory<T>::New(arg0);
npm ERR!       |          ~~~~~~~~~~~~~~~~~~~~^~~~~~
npm ERR! In file included from ../../nan/nan_new.h:189,
npm ERR!                  from ../../nan/nan.h:290,
npm ERR!                  from ../src/getoptions.cc:4:
npm ERR! ../../nan/nan_implementation_12_inl.h:177:1: note: candidate: ‘static Nan::imp::FactoryBase<v8::Uint32>::return_t Nan::imp::Factory<v8::Uint32>::New(int32_t)’
npm ERR!   177 | Factory<v8::Uint32>::New(int32_t value) {
npm ERR!       | ^~~~~~~~~~~~~~~~~~~
npm ERR! ../../nan/nan_implementation_12_inl.h:183:1: note: candidate: ‘static Nan::imp::FactoryBase<v8::Uint32>::return_t Nan::imp::Factory<v8::Uint32>::New(uint32_t)’
npm ERR!   183 | Factory<v8::Uint32>::New(uint32_t value) {
npm ERR!       | ^~~~~~~~~~~~~~~~~~~
npm ERR! make: *** [spi.target.mk:115: Release/obj.target/spi/src/getoptions.o] Error 1
npm ERR! gyp ERR! build error
npm ERR! gyp ERR! stack Error: `make` failed with exit code: 2
npm ERR! gyp ERR! stack     at ChildProcess.onExit (/usr/lib/node_modules/node-gyp/lib/build.js:194:23)
npm ERR! gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:277:12)
npm ERR! gyp ERR! System Linux 5.10.44-1-ARCH
npm ERR! gyp ERR! command "/usr/bin/node" "/usr/lib/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd /home/alarm/MySpiTool/node_modules/spi-device
npm ERR! gyp ERR! node -v v14.16.0
npm ERR! gyp ERR! node-gyp -v v8.1.0
npm ERR! gyp ERR! not ok

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/alarm/.npm/_logs/2021-06-22T13_17_31_561Z-debug.log

Runs fine on Ach Linux ARM for armv8/aarch64, 64bit.
Any ideas howto solve the error call of overloaded ‘New(long unsigned int&)’ is ambiguous?

Uncaught Error: EINVAL, incorrect arguments passed to transferSync(message)

I'm trying to port the Unicorn Hat Mini library to nodejs: https://github.com/pimoroni/unicornhatmini-python/blob/master/library/unicornhatmini/__init__.py

I'm just getting started and these initializations of the LED matrix controllers are giving me issues:

        for device, pin, offset in self.left_matrix, self.right_matrix:
            device.no_cs = True
            device.max_speed_hz = spi_max_speed_hz
            GPIO.setup(pin, GPIO.OUT, initial=GPIO.HIGH)
            self.xfer(device, pin, [CMD_SOFT_RESET])
            self.xfer(device, pin, [CMD_GLOBAL_BRIGHTNESS, 0x01])
            self.xfer(device, pin, [CMD_SCROLL_CTRL, 0x00])
            self.xfer(device, pin, [CMD_SYSTEM_CTRL, 0x00])
            self.xfer(device, pin, [CMD_WRITE_DISPLAY, 0x00] + self.buf[offset:offset + (28 * 8)])
            self.xfer(device, pin, [CMD_COM_PIN_CTRL, 0xff])
            self.xfer(device, pin, [CMD_ROW_PIN_CTRL, 0xff, 0xff, 0xff, 0xff])
            self.xfer(device, pin, [CMD_SYSTEM_CTRL, 0x03])

Right now, I am just using synchronous code to get things working:

    constructor({bus, device, offset}) {
        this.bus = bus;
        this.device = device;
        this.offset = offset;

        this.SpiDevice = spi.openSync(this.bus, this.device, options);
        this.xfer([CMD_SOFT_RESET]);
        this.xfer([CMD_GLOBAL_BRIGHTNESS, 0x01]);
        this.xfer([CMD_SCROLL_CTRL, 0x00]);
        this.xfer([CMD_SYSTEM_CTRL, 0x00]);
        this.xfer([CMD_WRITE_DISPLAY, 0x00] + streambuffer[this.offset + (28 * 8)]);
        this.xfer([CMD_COM_PIN_CTRL, 0xff]);
        this.xfer([CMD_ROW_PIN_CTRL, 0xff, 0xff, 0xff, 0xff]);
        this.xfer([CMD_SYSTEM_CTRL, 0x03]);
    }

    xfer(command) {
        this.SpiDevice.transferSync({sendBuffer : Buffer.from(command), byteLength : command.length});
    }

I'm getting this error on the very first transfer:

Uncaught Error: EINVAL, incorrect arguments passed to transferSync(message)

which appears to come from here:

if (info.Length() < 1 || !info[0]->IsArray()) {
   return Nan::ThrowError(
     Nan::ErrnoException(
       EINVAL,
       "transfer",
       "incorrect arguments passed to transferSync(message)"
     )
   );
 }

My command is 1 byte long - is that the problem?

Help Switch from Arduino sketch to Node

I'm getting data in the read buffer but it is not the correct data and it is not same data consistently from read to read. I am reading data from an AD4116 https://www.analog.com/en/products/ad4116.html, the chip is on AD's evaluation board https://www.analog.com/en/design-center/evaluation-hardware-and-software/evaluation-boards-kits/EVAL-AD4116.html. I can read data using both an Arduino Uno R3 and AD's Evaluation Controller Board EVAL-SDP-CB1Z.

Here is an Arduino sketch that works:

#include <SPI.h>

#define DATAOUT 11 //COPI
#define DATAIN  12 //CIPO
#define SPICLOCK  13 //sck
#define CHIPSELECT05 5 //cs

void setup() {
    pinMode(DATAOUT, OUTPUT);
    pinMode(DATAIN, INPUT);
    pinMode(SPICLOCK,OUTPUT);
    pinMode(CHIPSELECT05,OUTPUT);
    digitalWrite(CHIPSELECT05,HIGH); //disable device
}

void loop() {
    pinMode(CHIPSELECT05,OUTPUT);
    
    delay(50);
   
    SPI.begin();
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE3);
    
    digitalWrite(CHIPSELECT05,LOW); //enable device

    SPI.transfer(B01000111);
    unsigned int n1 = SPI.transfer16(0x00);

    digitalWrite(CHIPSELECT05,HIGH); //disable device
}   

Here is a JavaScript that dosen't works:

try {
  
    // declare it
    var spi = global.get("SPI");

    // The AD4116 is on bus 0 and it's device 0
    const ad4116_ID = spi.open(0, 1, err => {

        const options = {
            mode: spi.MODE3,
            // The semantics of chipSelectHigh have changed in kernel 5 and higher
            //chipSelectHigh: false,
            lsbFirst: false, // pi only supports msb first
            threeWire: false,
            loopback: false, // pi doesn't support loopback
            noChipSelect: false,
            ready: false, // pi doesn't support ready
            bitsPerWord: 8, // pi only supports 8 bit words
            maxSpeedHz: 200
        };


        ad4116_ID.setOptions(options, err =>{
            if (err) {
                node.error(err)
                return msg;
            };
        });

        // An SPI message is an array of one or more read+write transfers
        const message = [{
            sendBuffer: Buffer.from([71]), // Sent to read ID
            receiveBuffer: Buffer.alloc(2),  // Raw data read 
            byteLength: 1,
            speedHz: 200 // Use a low bus speed to get a good reading
        }];

        if (err) {
            node.error(err)
            return msg;
        };

        ad4116_ID.transfer(message, (err, message) => {
            if (err) {
                node.error(err)
                return msg;
            };
        });
        msg.payload = message
    });

    ad4116_ID.close
}
catch (exception_var) {
    msg.stopped = 4;
    node.error(exception_var);
}

return msg;

Use maybe instances to fix compiler warnings

When installing with Node.js v6.9.2 there are compiler warnings. It should be possible to avoid the warnings with maybe instances.

$ npm install spi-device

> [email protected] install /home/pi/spi-device/node_modules/spi-device
> node-gyp rebuild

make: Entering directory '/home/pi/spi-device/node_modules/spi-device/build'
  CXX(target) Release/obj.target/spi/src/spi.o
  CXX(target) Release/obj.target/spi/src/spidevice.o
../src/spidevice.cc: In static member function ‘static v8::Local<v8::Object> SpiDevice::Open(Nan::NAN_METHOD_ARGS_TYPE)’:
../src/spidevice.cc:53:61: warning: ‘v8::Local<v8::Object> v8::Function::NewInstance(int, v8::Local<v8::Value>*) const’ is deprecated (declared at /home/pi/.node-gyp/6.9.2/include/node/v8.h:3269): Use maybe version [-Wdeprecated-declarations]
   v8::Local<v8::Object> instance = cons->NewInstance(0, NULL);
                                                             ^
../src/spidevice.cc: In static member function ‘static v8::Local<v8::Object> SpiDevice::OpenSync(Nan::NAN_METHOD_ARGS_TYPE)’:
../src/spidevice.cc:69:61: warning: ‘v8::Local<v8::Object> v8::Function::NewInstance(int, v8::Local<v8::Value>*) const’ is deprecated (declared at /home/pi/.node-gyp/6.9.2/include/node/v8.h:3269): Use maybe version [-Wdeprecated-declarations]
   v8::Local<v8::Object> instance = cons->NewInstance(0, NULL);
                                                             ^
  CXX(target) Release/obj.target/spi/src/open.o
  CXX(target) Release/obj.target/spi/src/close.o
  CXX(target) Release/obj.target/spi/src/transfer.o
  CXX(target) Release/obj.target/spi/src/getoptions.o
  CXX(target) Release/obj.target/spi/src/setoptions.o
  SOLINK_MODULE(target) Release/obj.target/spi.node
  COPY Release/spi.node
make: Leaving directory '/home/pi/spi-device/node_modules/spi-device/build'
/home/pi/spi-device
└─┬ [email protected] 
  ├── [email protected] 
  └── [email protected] 

npm WARN enoent ENOENT: no such file or directory, open '/home/pi/spi-device/package.json'
npm WARN spi-device No description
npm WARN spi-device No repository field.
npm WARN spi-device No README data
npm WARN spi-device No license field.
$

USB to spi device

I use a USB to spi device, and its device path is /dev/ttyUSB0 instead of /dev/spidev. How to use it?

When working with spi again, a delay of at least 4 seconds is required.

The first time "device.transfer(message, cb)" works well, when called again "device.transfer(message, cb)" is not read or written.
I tried changing the parameters: microSecondDelay: 10 - 10000, etc.
Does not help! The only solution is to wait 4 seconds before repeating "device.transfer(message, cb)".
Cannot be used while device is polling.

Fails to install on Rasperry Pi 2 B

Hi!
I try to install a node-red package (see here). The install fails when installing spi-device with following error messages:

pi@xxx:~ $ npm install spi-device

> [email protected] install /home/pi/node_modules/spi-device
> node-gyp rebuild

make: Verzeichnis „/home/pi/node_modules/spi-device/build“ wird betreten
  CXX(target) Release/obj.target/spi/src/spi.o
cc1plus: error: unrecognized argument in option ‘-mfloat-abi=hard’
cc1plus: note: valid arguments to ‘-mfloat-abi=’ are:   softfp
cc1plus: error: unrecognized argument in option ‘-mfpu=vfp’
cc1plus: note: valid arguments to ‘-mfpu=’ are: auto crypto-neon-fp-armv8 fp-armv8 fpv4-sp-d16 fpv5-d16 fpv5-sp-d16  neon-fp-armv8 neon-fp16        neon-vfpv3 neon-vfpv4  vfp3 vfpv2 vfpv3 vfpv3-d16 vfpv3-d16-fp16 vfpv3-fp16 vfpv3xd vfpv3xd-fp16 vfpv4 vfpv4-d16; did you mean ‘vfp3’?
make: *** [spi.target.mk:119: Release/obj.target/spi/src/spi.o] Fehler 1
make: Verzeichnis „/home/pi/node_modules/spi-device/build“ wird verlassen
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:194:23)
gyp ERR! stack     at ChildProcess.emit (events.js:400:28)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:285:12)
gyp ERR! System Linux 5.10.103-v7+
gyp ERR! command "/usr/bin/node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/pi/node_modules/spi-device
gyp ERR! node -v v14.20.1
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
npm WARN enoent ENOENT: no such file or directory, open '/home/pi/package.json'
npm WARN pi No description
npm WARN pi No repository field.
npm WARN pi No README data
npm WARN pi No license field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/pi/.npm/_logs/2022-11-01T06_06_06_482Z-debug.log

My harware is a Raspberry Pi 2 Model B Rev 1.1 with ARMv7 Processor rev 5 (v7l) with Rasbian 10 (buster).

Node version is v14.20.1

Is there any chance to fix this somehow?
Thanks!

Bump nan

Hi,

Would it be possible you bump nan to latest version 2.15.0?

Many thanks

can't find SPI device channel arguments!

Hi fivdi, I want to thank you for building a great module for SPI interface. Right now this module is the most decent one in whole embedded world using JavaScript. As limitation due to my knowledge I am not sure how can I get the reading of a channel by parameter sendBuffer in message object ! Can I get a documentation in somewhere? Any help is appreciated.

Issue with Max31865

I'm using this lib which uses your lib with current version: https://github.com/MariusRumpf/max31865
Platform: Rpi 3B
The library seems to be working software wise, but somehow strange thing happen on the MISO line. It seems that on every clock edge, there is a very short - 100ns- spike on the MISO line. The timing of events seem OK though, as the read and write functions are called.

Did you observ such behaviour before with any SPI device?
I'm using the Adafruit breakout board with the max31865. Just to check if the baord is faulty, I did it with 2 boards, but the same issue is produced.

Here is a screenshot below. As you can see on Chanel 3, which is the MISO, there are spikes on the line. Also as you can see (did not fit the pic) MISO is kept low for longer time, and CS as well. Is it possible for the SPI driver to recognize this as an error?
Strangely, the Pi is not recognizing data. Printing values are all 0, which means to me that no real value is recognized.
I doubt that it is the lib issue, it should be a SPI related one, but I'm not sure how to start debugging this.
The screenshot actually shows the rtd reading sequence from the Max31865 (address 0x01), as you can see there is -kinda - a valid value.
Clock is measured 312,5kHz. The Max31685 supports both Mode1 and Mode3, tested with both, same result. Screenshot shows Mode1.
image

Can you please help me with this issue not able to install spi-device module

pi@raspberrypi:~/SPI $ npm install spi-device

[email protected] install /home/pi/SPI/node_modules/spi-device
node-gyp rebuild

make: Entering directory '/home/pi/SPI/node_modules/spi-device/build'
make: Warning: File '../../../../.node-gyp/8.9.4/include/node/common.gypi' has modification time 3888180 s in the future
ACTION Regenerating Makefile
make: Warning: File '../../../../.node-gyp/8.9.4/include/node/common.gypi' has modification time 3888179 s in the future
ACTION Regenerating Makefile
make: Warning: File '../../../../.node-gyp/8.9.4/include/node/common.gypi' has modification time 3888178 s in the future
ACTION Regenerating Makefile
make: Warning: File '../../../../.node-gyp/8.9.4/include/node/common.gypi' has modification time 3888177 s in the future
ACTION Regenerating Makefile
make: Warning: File '../../../../.node-gyp/8.9.4/include/node/common.gypi' has modification time 3888176 s in the future
ACTION Regenerating Makefile
make: Warning: File '../../../../.node-gyp/8.9.4/include/node/common.gypi' has modification time 3888174 s in the future
ACTION Regenerating Makefile
make: Warning: File '../../../../.node-gyp/8.9.4/include/node/common.gypi' has modification time 3888173 s in the future
ACTION Regenerating Makefile
make: Warning: File '../../../../.node-gyp/8.9.4/include/node/common.gypi' has modification time 3888172 s in the future
ACTION Regenerating Makefile
make: Warning: File '../../../../.node-gyp/8.9.4/include/node/common.gypi' has modification time 3888171 s in the future
ACTION Regenerating Makefile
make: Warning: File '../../../../.node-gyp/8.9.4/include/node/common.gypi' has modification time 3888170 s in the future
ACTION Regenerating Makefile
make: Warning: File '../../../../.node-gyp/8.9.4/include/node/common.gypi' has modification time 3888168 s in the future
ACTION Regenerating Makefile
make: Warning: File '../../../../.node-gyp/8.9.4/include/node/common.gypi' has modification time 3888167 s in the future
ACTION Regenerating Makefile
^CProcess PoolWorker-3:
Process PoolWorker-4:
Traceback (most recent call last):
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
Process PoolWorker-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
self.run()
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
self._target(*self._args, **self._kwargs)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 102, in worker
File "/usr/lib/python2.7/multiprocessing/pool.py", line 102, in worker
self.run()
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 102, in worker
task = get()

correct values for speedHz and maxSpeedHz settings on Raspberry Pi?

The Raspberry Pi documentation says this about SPI speeds:

The driver supports all speeds which are even integer divisors of the core clock, although as said above not all of these speeds will support data transfer due to limits in the GPIOs and in the devices attached. As a rule of thumb, anything over 50MHz is unlikely to work, but your mileage may vary.

The core clock is usually given as 500Mhz for Raspberry Pi 4 and I've added core_freq_min=500 to my /boot/config.txt as mentioned in many tutorials to prevent drift.
This gives us the following values for speed:

31.25 Mhz
15.625 Mhz
7.8125 Mhz
3.90625 Mhz
1.953125 Mhz
...

I was wondering if this actually applies or if there is something else going on that can set speeds in between?

I've been trying to control a ws281x RGB LED via SPI and I'm getting very confusing results. The correct speed should be 2.35 Mhz in my case but the only reasonable results happen at 9-10 Mhz 😕 which actually should not even exist ...

Any help or ideas would be awesome!

Module did not self-register

Hello,

I am attempting to use this package in an Electron app that will ultimately be run on a Raspberry Pi but I am doing development on MacOS. I suspect that the fact I don't have a spi device on the development machine is the culprit, in which case this issue can be rapidly closed out. But if you have any other thoughts I'd appreciate it. When I added the module here were the messages output:

npm i spi-device

> [email protected] install /Users/adam/Documents/src/project/app/node_modules/spi-device
> node-gyp rebuild

  SOLINK_MODULE(target) Release/spi.node
npm WARN [email protected] No repository field.

+ [email protected]
added 3 packages from 2 contributors, removed 1 package and audited 4 packages in 2.091s
found 0 vulnerabilities

The package is correctly listed within my package.json and webpack has it marked as externals. I have added only this line in my code:

const spi = require('spi-device');

When I run the Electron app from my mac I get this error:

Uncaught Error: Module did not self-register.
    at process.func (electron/js2c/asar.js:138)
    at process.func [as dlopen] (electron/js2c/asar.js:138)
    at Object.Module._extensions..node (internal/modules/cjs/loader.js:828)
    at Object.func (electron/js2c/asar.js:138)
    at Object.func [as .node] (electron/js2c/asar.js:138)
    at Module.load (internal/modules/cjs/loader.js:645)
    at Function.Module._load (internal/modules/cjs/loader.js:560)
    at Module.require (internal/modules/cjs/loader.js:685)
    at require (internal/modules/cjs/helpers.js:16)
    at bindings (/Users/adam/Documents/src/project/app/node_modules/bindings/bindings.js:112)

Thanks in advance!

SPI - question to control a push button with bitmap in SPI

Dear @fivdi

I 'd like to use your library to control this push button from NKK Smartswitch in SPI.

I am not asking to do it but I 'd like just to understand with the information I have found in your sample code to monitor temperature with mcp3008

This is the datasheet

image

I underlined the most important informat and would be sure I am right and could use your lib with success.

switch : GPIO

SW - Terminal of Switch Normally open
SW  - Terminal of Switch Normally open

=> I should use https://github.com/fivdi/onoff for the button with debounce. Is it right ?

LCD : SPI

SDO  - Data Out Data output line for SPI
SDI - Data In Data input line for SPI
SCK - Serial Clock Clock line for SPI that synchronizes commands and data

SS - Slave Select Chip select for SPI; line is active low

I see the cabling

image

=> I should use https://github.com/fivdi/mcp-spi-adc for the SPI with CS or https://github.com/fivdi/spi-device . Is it right?

To be sure Ia m understanding : for the pin layout regarding my raspberry PI4 :

image

SPI0 MISO <=> SDO from my button
SPI0 MOSI <=>SDI from my button
SPI SCLK <-> SCK
SPI CE0 <-> SS but each time I need to send a message I need to force "false" till the message is sent then when terminate I need to force a true the SS. I don't know if SPI CE0 is enabled when false or true?

Thanks for your remarks.

Best Regards,
Youssef

Help with spi-device and THAT5171 chip

Hi!

I´ve made a proto board containing a THAT5171 chip.
http://www.thatcorp.com/datashts/THAT_5171_Datasheet.pdf -spi info on page 12.

I have issues to communicate with the chip using a raspberry pi as master.
I´m pretty sure that all the hardware is wired correctly.
I´ve tried to "modify" the example code but....
My nearest goal is to get som responce from the chip via the register adress, 3bits, CHIP_ ID

Very grateful for some help

const spi = require('spi-device');
 

const pre = spi.open(0, 0, err => { // Is this right for my device?
  // An SPI message is an array of one or more read+write transfers
  const message = [{
    sendBuffer: Buffer.from([0,0,]), //Does binary work here or hex?
    receiveBuffer: Buffer.alloc(1),              
    byteLength: 1, //Prepare master for receiving byteLength? THAT5171 should return 8 bits.
    speedHz: 10000000 // Does this work? 10Mhz or do i get like 7,8
  }];
 
  if (err) throw err;
 
  pre.transfer(message, (err, message) => {
    if (err) throw err;
 
    const data = message[0].receiveBuffer[1];      
   
 
    console.log(data);
  });
});

Having problems getting the example to run

Hey Brian,
I can't get the example code to run on my raspi.

First, I'm getting this error...

/home/pi/Documents/raspi-test/spi-test.js:14
if (err) throw err;
               ^
Error: ENOENT, No such file or directory
    at Error (native)

I have tried commenting out that line, and then I get this error..

home/pi/Documents/raspi-test/spi-test.js:16
  mcp3008.transfer(message, function(err, message) {
          ^
Error: EPERM, device closed, operation not permitted
    at Error (native)
    at /home/pi/Documents/raspi-test/spi-test.js:16:11

I'm totally new to hacking with a pi, and this is the first test that I've tried. So any advice you have to resolve would be helpful. Could it be a problem with my breadboarding?

Fix tests

Some of the tests no longer function as expected on Linux version 5.4.79-v7+ and need to be updated.
See also #16.

Here is the console output shown when the tests are run:

default-options
node:assert:107
  throw new AssertionError(obj);
  ^

AssertionError [ERR_ASSERTION]: default chipSelectHigh incorrect
    at checkDefaultOptions (/home/pi/mcp-spi-adc/node_modules/spi-device/test/default-options.js:8:10)
    at checkOptions (/home/pi/mcp-spi-adc/node_modules/spi-device/test/default-options.js:19:3)
    at Object.<anonymous> (/home/pi/mcp-spi-adc/node_modules/spi-device/test/default-options.js:30:1)
    at Module._compile (node:internal/modules/cjs/loader:1102:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
    at Module.load (node:internal/modules/cjs/loader:967:32)
    at Function.Module._load (node:internal/modules/cjs/loader:807:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47 {
  generatedMessage: false,
  code: 'ERR_ASSERTION',
  actual: true,
  expected: false,
  operator: 'strictEqual'
}
options
options-sync
node:assert:107
  throw new AssertionError(obj);
  ^

AssertionError [ERR_ASSERTION]: can't set chipSelectHigh
    at Object.<anonymous> (/home/pi/mcp-spi-adc/node_modules/spi-device/test/options-sync.js:32:8)
    at Module._compile (node:internal/modules/cjs/loader:1102:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
    at Module.load (node:internal/modules/cjs/loader:967:32)
    at Function.Module._load (node:internal/modules/cjs/loader:807:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47 {
  generatedMessage: false,
  code: 'ERR_ASSERTION',
  actual: false,
  expected: true,
  operator: 'strictEqual'
}
message-size
/home/pi/mcp-spi-adc/node_modules/spi-device/test/message-size.js:30
  mcp3008.transferSync(createMessage(511)); // works
          ^

Error: EMSGSIZE, Message too long
    at transferAsManyAsPossible (/home/pi/mcp-spi-adc/node_modules/spi-device/test/message-size.js:30:11)
    at Object.<anonymous> (/home/pi/mcp-spi-adc/node_modules/spi-device/test/message-size.js:66:1)
    at Module._compile (node:internal/modules/cjs/loader:1102:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
    at Module.load (node:internal/modules/cjs/loader:967:32)
    at Function.Module._load (node:internal/modules/cjs/loader:807:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47 {
  errno: 90,
  code: 'EMSGSIZE',
  syscall: 'transferSync'
}
transfer

Add platform-conditional directive around spidev include

Trying to install this package locally on a mac. Getting this error:

../src/spi.cc:1:10: fatal error: 'linux/spi/spidev.h' file not found
#include <linux/spi/spidev.h>
         ^~~~~~~~~~~~~~~~~~~~
1 error generated.

Makes sense, given that that library wouldn't exist on a mac. I noticed that in the pi-spi package, there's an #if __linux__ conditional around the inclusion of the SPI library. Would it make sense to include something like that in this package as well? Ideally I'd be able to run npm install anywhere without a breakdown.

GPIO pins as chip select

Is it possible to use this library to control a DAC8532 via this "High Precision AD/DA Board"?

I'm getting confused because the board seems to use GPIO pins 23 and 22 as CS for the onboard digital-to-analog and analog-to-digital converters, respectively.

The board schematic doesn't seem to indicate any connection for the SPI CSx pins (GPIO 7 and 8).

I was thinking that this might be the type of scenario where noChipSelect would get used (i.e. use onoff to control chip select directly via the GPIO pins) - but nothing I try seems to work.

Any guidance appreciated. Thanks for this library.

Configure options not working

Options do not change when setting mode, or any other options.

Code to set and check spi options:
let spi_options = [{
mode: 0b10,
chipSelectHigh: true,
lsbFirst: true,
threeWire: true,
loopback: true,
noChipSelect: true,
ready: true,
bitsPerWord: 8,
maxSpeedHz: 125000000
}];

  console.log('Set SPI Options', spi_options)
  
  const pn532 = await spi.openSync(0,0);		// bus 0, device 0
  await pn532.setOptionsSync(spi_options)

  console.log('Check SPI Options', await pn532.getOptionsSync())

Output:
[13/11/2020 20:34:22.057] [LOG] Set SPI Options [ { mode: 2,
chipSelectHigh: true,
lsbFirst: true,
threeWire: true,
loopback: true,
noChipSelect: true,
ready: true,
bitsPerWord: 8,
maxSpeedHz: 125000000 } ]
[13/11/2020 20:34:22.092] [LOG] Check SPI Options { mode: 0,
chipSelectHigh: false,
lsbFirst: false,
threeWire: false,
loopback: false,
noChipSelect: false,
ready: false,
bitsPerWord: 8,
maxSpeedHz: 125000000 }

Crashed on open if options parameter is null or undefined

https://github.com/fivdi/spi-device/blob/master/spi-device.d.ts#L44
declares that options parameter can be null or undefined but node crashes using these values:
With null:

var spi = require("spi-device");
var d = spi.open(0, 0, null, err => console.log(err));
// FATAL ERROR: v8::Object::Cast Could not convert to object

With undefined:

var spi = require("spi-device");
var d = spi.open(0, 0, undefined, err => console.log(err));
// FATAL ERROR: v8::Object::Cast Could not convert to object

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.