summaryrefslogtreecommitdiff
path: root/Resources/OpenPLCv2/firmware/ADC.test.arduino/trial.c
blob: fae88f68b117a79de96f537a285d1989dc3b7206 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

#define SELPIN 10 //Selection Pin
#define DATAOUT 11//MOSI
#define DATAIN  12//MISO
#define SPICLOCK  13//Clock
int readvalue;

void setup(){
//set pin modes
pinMode(SELPIN, OUTPUT);
pinMode(DATAOUT, OUTPUT);
pinMode(DATAIN, INPUT);
pinMode(SPICLOCK, OUTPUT);
//disable device to start with
digitalWrite(SELPIN,HIGH);
digitalWrite(DATAOUT,LOW);
digitalWrite(SPICLOCK,LOW);

Serial.begin(9600);
}

int read_adc(int channel){
 int adcvalue = 0;
 byte commandbits = B11000000; //command bits - start, mode, chn (3), dont care (3)
 
 //allow channel selection
 commandbits|=((channel-1)<<3);

 digitalWrite(ADCSEL,LOW); //Select adc
 // setup bits to be written
 for (int i=7; i>=3; i--){
   digitalWrite(DATAOUT,commandbits&1<<i);
   //cycle clock
   digitalWrite(SPICLOCK,HIGH);
   digitalWrite(SPICLOCK,LOW);    
 }

 digitalWrite(SPICLOCK,HIGH);    //ignores 2 null bits
 digitalWrite(SPICLOCK,LOW);
 digitalWrite(SPICLOCK,HIGH);  
 digitalWrite(SPICLOCK,LOW);

 //read bits from adc
 for (int i=11; i>=0; i--){
   adcvalue+=digitalRead(DATAIN)<<i;
   //cycle clock
   digitalWrite(SPICLOCK,HIGH);
   digitalWrite(SPICLOCK,LOW);
 }
 digitalWrite(ADCSEL, HIGH); //turn off device
 return adcvalue;
}

digitalWrite(SELPIN, HIGH); //turn off device
return adcvalue;
}

void loop() {
readvalue = read_adc(1);
Serial.println(readvalue,DEC);
readvalue = read_adc(2);
Serial.println(readvalue,DEC);
Serial.println(" ");
delay(250);
}