Skip to content

Instantly share code, notes, and snippets.

@4rzael
Created October 15, 2015 09:23
Show Gist options
  • Save 4rzael/e0bb58bbd06bf140f852 to your computer and use it in GitHub Desktop.
Save 4rzael/e0bb58bbd06bf140f852 to your computer and use it in GitHub Desktop.
A litlle example code to read data from a MCP3002 on a RPi using pi-spi
'use strict';
var SPI = require('pi-spi');
var spi = SPI.initialize("/dev/spidev0.0");
// Read value from a MCP3002 (http://ww1.microchip.com/downloads/en/DeviceDoc/21294C.pdf)
function readMCP(channel, callback) {
if (spi === undefined) return;
var mode = (8 + channel) << 4;
var tx = new Buffer([1, mode, 0]);
var rx = new Buffer([0, 0, 0]);
spi.transfer(tx, tx.length, function(err, buffer) {
var value = ((buffer[1] & 3) << 8) + buffer[2];
callback(value);
});
}
setInterval(function () {
readMCP(0, function (value) {
console.log(value);
});
}, 100);
@4rzael
Copy link
Author

4rzael commented Oct 15, 2015

Here is an example of how to connect it (example with a photoresistor)

mcp

Also, here is the datasheet

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