]> git.piffa.net Git - arduino/blob - books/ArduinoNextSteps-master/ArduinoNextSteps/sketch_09_01_SPI_ADC/sketch_09_01_SPI_ADC.ino
first commit
[arduino] / books / ArduinoNextSteps-master / ArduinoNextSteps / sketch_09_01_SPI_ADC / sketch_09_01_SPI_ADC.ino
1 // sketch_09_01_SPI_ADC
2
3 #include <SPI.h>
4
5 const int chipSelectPin = 10;
6
7 void setup() 
8 {
9   Serial.begin(9600);
10   SPI.begin();
11   pinMode(chipSelectPin, OUTPUT);
12   digitalWrite(chipSelectPin, HIGH);
13 }
14
15 void loop()
16 {
17   int reading = readADC(0);
18   Serial.println(reading);
19   delay(1000);
20 }
21
22 int readADC(byte channel)
23 {
24   unsigned int configWord = 0b11000 | channel;
25   byte configByteA = (configWord >> 1);
26   byte configByteB = ((configWord & 1) << 7);
27   digitalWrite(chipSelectPin, LOW);
28   SPI.transfer(configByteA);
29   byte readingH = SPI.transfer(configByteB);
30   byte readingL = SPI.transfer(0);
31   digitalWrite(chipSelectPin, HIGH);
32
33   printByte(readingH);
34   printByte(readingL);
35
36   int reading = ((readingH & 0b00011111) << 5) + ((readingL & 0b11111000) >> 3);
37   
38   return reading;
39 }
40
41 void printByte(byte b)
42 {
43   for (int i = 7; i >= 0; i--)
44   {
45      Serial.print(bitRead(b, i));
46   }
47   Serial.print(" ");
48 }
49