MCP3004/3008, 2.7V 4-Channel/8-Channel 10-Bit A/D Converters with SPI Serial Interface (Arduino)

Used Products:

1. Arduino UNO
2. MCP3008

Content:

Çeşme: http://arduinolearning.com/code/arduino-and-mcp3008.php https://github.com/nodesign/MCP3008 https://www.youtube.com/watch?v=jrXVmMni64Y

Code:

#define _cspin 12 #define _clockpin 9 #define _mosipin 11 #define _misopin 10 int val; void setup() { Serial.begin(9600); pinMode(_cspin, OUTPUT); pinMode(_clockpin, OUTPUT); pinMode(_mosipin, OUTPUT); pinMode(_misopin, INPUT); } void loop() { val = readADC(0); Serial.print("pot: "); Serial.print(val); Serial.println(); delay(250); } void doClock() { digitalWrite(_clockpin, HIGH); digitalWrite(_clockpin, LOW); } int readADC(int channel) { digitalWrite(_cspin, HIGH); digitalWrite(_clockpin, LOW); // # start clock low digitalWrite(_cspin, LOW); // # bring CS low digitalWrite(_mosipin, HIGH); doClock(); digitalWrite(_mosipin, HIGH); doClock(); # select channel = 0..7 = 0000..0111 for (int i = 2; i > -1; i--) { digitalWrite(_mosipin, (bitRead(channel,i)==1)); doClock(); } // first bit is null and 10 ADC bits = X 11 1111 1111 = 0..1023 int result = 0; for (int i = 0; i < 11; i++) { doClock(); result <<= 1; if (digitalRead(_misopin)) { result |= 0x1; } } digitalWrite(_cspin, HIGH); return result; }