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

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

Arduino:

#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; }

C:

#include <avr/io.h> #include <util/delay.h> #include <Arduino.h> #define _cspin PB4 #define _mosipin PB3 #define _misopin PB2 #define _clockpin PB1 int val; int main(void) { Serial.begin(9600); DDRB |= (1<<_cspin); DDRB |= (1<<_clockpin); DDRB |= (1<<_mosipin); DDRB &= ~(1<<_misopin); while (1) { val = readADC(0); Serial.print("pot: "); Serial.print(val); Serial.println(); _delay_ms(50); } return 0; } void doClock() { PORTB |= (1<<_clockpin); PORTB &= ~(1<<_clockpin); } int readADC(int channel) { PORTB |= (1<<_cspin); PORTB &= ~(1<<_clockpin); PORTB &= ~(1<<_cspin); PORTB |= (1<<_mosipin); doClock(); PORTB |= (1<<_mosipin); doClock(); //# select channel = 0..7 = 0000..0111 for (int i = 2; i > -1; i--) { byte state= ((channel >> i) & 0x01); if (state) { PORTB |= (1<<_mosipin); } else { PORTB &= ~(1<<_mosipin); } 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 (PINB & (1 << _misopin)) { result |= 0x1; } } PORTB |= (1<<_cspin); return result; }