Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including analog-reader with all npm packages installed. Try it out:

var analogReader = require("analog-reader")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

analog-reader v1.0.3

An event based analog input reader for your GPIO.

Analog Reader

An event based analog input reader with sampling for less jittery values. Currently only tested using a Raspberry Pi 2 along with an MCP3008. Might work with other SPI setups as well. Heavily based on Ladyada's python code.


npm i --save analog-reader


For instructions on wiring the MCP3008 to a Raspberry Pi, see here.

After that, configure the pins to be used and initialize the reader

const AnalogReader = require('analog-reader');
const CLOCKPIN = 18;
const MOSIPIN = 24;
const MISOPIN = 23;
const CSPIN = 25;

var reader = new AnalogReader(CLOCKPIN,MOSIPIN,MISOPIN,CSPIN);

After initializing you can change some properties, such as the readDelay, sampleSize and watch/unwatch inputs.

// Sets how often (milliseconds) should we poll for data, defaults to 2 ms.
// I'm not sure how to get how low can you go, as it will depend on the setup.
reader.readDelay = 2;

// Setting a higher sample size will take longer. It's a tradeoff between accuracy and speed. Defaults to 50.

reader.sampleSize = 50;

Watching / unwatching

// Watch input 0, 1 and 2;;;

// Stop watching input 1

Set up a listener

reader.on('value', function(evt){
        value: 14, // Sampled value
        buffer: [...], // Values sampled for this reading
        num: 0 // ADC Number

// Starts reading!

Finally, to stop reading, try

// Stops reading! Can be resumed later!

To manually destroy the reader, use the following. This will unexport and free up the used pins. It should be automatically called when stopping your program (SIGINT) as well.

Once done you can't start listening again with the same reader.



Use npm install and then run npm start to compile from coffeescript.


TODO proper testing.

npm run test currently runs a webpack-dev-server with a mocked up read method to test the sampling behaviour.


RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free