IO: Add an 8-channel ADC example using the MCP3008

This commit is contained in:
gohai
2016-04-03 17:32:30 +02:00
parent 50be2983e2
commit 29f797bb79
2 changed files with 42 additions and 0 deletions
@@ -0,0 +1,27 @@
import processing.io.SPI;
// MCP3008 is a Analog-to-Digital converter using SPI
// other than the MCP3001, this has 8 input channels
// datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/21295d.pdf
class MCP3008 extends SPI {
MCP3008(String dev) {
super(dev);
super.settings(500000, SPI.MSBFIRST, SPI.MODE0);
}
float getAnalog(int channel) {
if (channel < 0 || 7 < channel) {
System.err.println("The channel needs to be from 0 to 7");
throw new IllegalArgumentException("Unexpected channel");
}
byte[] out = { 0, 0, 0 };
// encode the channel number in the first byte
out[0] = (byte)(0x18 | channel);
byte[] in = super.transfer(out);
int val = ((in[1] & 0x03) << 8) | (in[2] & 0xff);
// val is between 0 and 1023
return val/1023.0;
}
}
@@ -0,0 +1,15 @@
import processing.io.*;
MCP3008 adc;
// see setup.png in the sketch folder for wiring details
void setup() {
//printArray(SPI.list());
adc = new MCP3008(SPI.list()[0]);
}
void draw() {
background(adc.getAnalog(0) * 255);
fill(adc.getAnalog(1) * 255);
ellipse(width/2, height/2, width * 0.75, width * 0.75);
}