Here, this is my previous coding for performing ADC operation of MCP3008 (SPI communication protocol) by using Arduino Mega 2560 Board.
#define SELPIN 53 //Selection Pin
#define DATAOUT 51//MOSI
#define DATAIN 50//MISO
#define SPICLOCK 52//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) //functiion prototype for Read ADC
{
int adcvalue = 0;
byte commandbits = B11000000; //command bits - start (B7) , mode (B6), channel (B3 to B5), dont care (B0 to B2) Note: B1 (1st bit // LSB) ; B7 (8th bit //MSB) (Channel refer to datasheet)
//allow channel selection
commandbits|=((channel-1)<<3); // must put "|" (not one "1" symbol)
digitalWrite(SELPIN,LOW); //Select adc
// setup bits to be written
for (int i=7; i>=3; i--){
digitalWrite(DATAOUT,commandbits&1<<i); // correct instruction Note: it means commandbits & (1<<i), do "1<<i" first.
//digitalWrite(DATAOUT,HIGH); //cannot use this instruction
//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 since it is ADC is 10 bits, then int i=9; i>=0; i-- ; if ADC is 12 bits, then nt i=11; i>=0; i--
for (int i=9; i>=0; i--){
adcvalue+=digitalRead(DATAIN)<<i;
//cycle clock
digitalWrite(SPICLOCK,HIGH);
digitalWrite(SPICLOCK,LOW);
}
digitalWrite(SELPIN, HIGH); //turn off device
return adcvalue;
}
void loop()
{
readvalue = read_adc(1); // read_adc(8) is to read the CH7 of MCP3008 // MCP3208 ; read_adc(1) is to read the CH1 of MCP3008 // MCP3208
Serial.println(readvalue,DEC);
readvalue = read_adc(2);
Serial.println(readvalue,DEC);
readvalue = read_adc(3); // read_adc(8) is to read the CH7 of MCP3008 // MCP3208 ; read_adc(1) is to read the CH1 of MCP3008 // MCP3208
Serial.println(readvalue,DEC);
readvalue = read_adc(4);
Serial.println(readvalue,DEC);
readvalue = read_adc(5); // read_adc(8) is to read the CH7 of MCP3008 // MCP3208 ; read_adc(1) is to read the CH1 of MCP3008 // MCP3208
Serial.println(readvalue,DEC);
readvalue = read_adc(6);
Serial.println(readvalue,DEC);
readvalue = read_adc(7); // read_adc(8) is to read the CH7 of MCP3008 // MCP3208 ; read_adc(1) is to read the CH1 of MCP3008 // MCP3208
Serial.println(readvalue,DEC);
readvalue = read_adc(8);
Serial.println(readvalue,DEC);
Serial.println(" ");
delay(250);
}
My problem is how to control sampling rate of MCP3008 such as 100 samples per second or 1000 samples per second by modifying Arduino coding?
Besides, how to write these data (ADC value) with timestamp and elapsed time into a excel file (not SD card) by modifying the Arduino coding?
Thanks you very much and very appreciate for helping.