Skip to content

Instantly share code, notes, and snippets.

@mikaelleven
Last active July 23, 2019 05:52
Show Gist options
  • Save mikaelleven/8535ee6ce40d80f43b1f to your computer and use it in GitHub Desktop.
Save mikaelleven/8535ee6ce40d80f43b1f to your computer and use it in GitHub Desktop.
NodeJS example using SPI communication to retrieve analog data through MCP3008 and Raspberry Pi
var rpio = require('rpio');
rpio.spiBegin();
//rpio.spiChipSelect(0); /* Chip select: use CE0 (default) */
//rpio.spiSetCSPolarity(0, rpio.LOW) /* Commonly chip enable (CE) pins are active low, and this is the default. */
//rpio.spiSetClockDivider(256) /* MCP3008 max is ~1MHz, 256 == 0.98MHz */
//rpio.spiSetDataMode(0);
// Prepare TX buffer [trigger byte = 0x01] [channel 0 = 0x80 (128)] [placeholder = 0x01]
var sendBuffer = new Buffer([0x01, (8 + 0 << 4), 0x01]);
// Send TX buffer to SPI MOSI and recieve RX buffer from MISO
var recieveBuffer = rpio.spiTransfer(sendBuffer, sendBuffer.length);
// Extract value from output buffer. Ignore first byte.
var junk = recieveBuffer[0],
MSB = recieveBuffer[1],
LSB = recieveBuffer[2];
// Ignore first six bits of MSB, bit shift MSB 8 positions and
// finally add LSB to MSB to get a full 10 bit value
var value = ((MSB & 3) << 8) + LSB;
console.log('ch' + ((sendBuffer[1] >> 4) - 8), '=', value);
rpio.spiEnd();
@mikaelleven
Copy link
Author

Could you please post the code executed before the rpio.spiTransfer() call? I have not seen this error myself but could be related to the input (txbuf) or output (rxbuf) buffer.

Or if you used my example without alternation maybe you could verify which version of rpio-lib you have installed?

@nick-jonas
Copy link

@mikaelleven I'm using your code unaltered, and with rpio 0.9.7 installed

Copy link

ghost commented Feb 11, 2016

got the exactly same error with this script here:

var rpio = require('rpio');

var rxBuffer = rpio.spiTransfer(new Buffer('HELLOSPI'), 8);

for (var i = 0; i <= 7; i++) { 
 process.stdout.write(String.fromCharCode(rxBuffer[i]) + (i == 7 ? '\n' : ' '));
};

@PrasadBapatla
Copy link

looks like the signature of the spiTransfer() has changed. the rxBuffer is now an argument, not a return value
if you look in the file rpio.js , you see that it it needs 3 parameters now .
the following should work

var rpio = require('rpio');

var rxBuffer = newBuffer(8);
rpio.spiTransfer(new Buffer('HELLOSPI'), rxBuffer, 8);

for (var i = 0; i <= 7; i++) {
process.stdout.write(String.fromCharCode(rxBuffer[i]) + (i == 7 ? '\n' : ' '));
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment