I wrote a small sketch to see how quickly I could poll a 3208 ADC and record it to SD. It works fine without the LCD but my final project will need both shields. Can anyone tell me why I can write to the SD in the setup function but not in the loop function?
// testing how quickly can poll the 3208 ADC
#include<SPI.h>
#include<LiquidCrystal.h>
#include <SdFat.h>
SdFat sd;
SdFile myFile;
const int chipSelect = 10;
int lcdpin = 9;
int adcpin = 2;
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
void setup() {
lcd.begin(16, 2);
Serial.begin(9600);
SPI.begin();
pinMode(10, OUTPUT);
// Set the cable select for the ADC.
pinMode(adcpin, OUTPUT);
digitalWrite(adcpin, HIGH);
// Initialize SdFat or print a detailed error message and halt
// Use half speed like the native library.
// change to SPI_FULL_SPEED for more performance.
if (!sd.begin(chipSelect, SPI_HALF_SPEED)) sd.initErrorHalt();
// open the file for write at end like the Native SD library
if (!myFile.open("speed.csv", O_RDWR | O_CREAT | O_AT_END)) {
sd.errorHalt("opening speed.txt for write failed");
}
myFile.println("ADC,Time");
myFile.close();
}
void loop() {
int count;
unsigned long timelog[10];
int datalog[10];
// lcd.clear();
// lcd.setCursor(0,0);
// lcd.print(" Ready");
delay(2000);
//for(int i = 0;1 < 3;i ++) {
for (int i = 0; i < 10; i ++) {
datalog[i] = adcpinread(7);
timelog[i] = micros();
delayMicroseconds(100);
}
// lcd.clear();
// lcd.setCursor(0,0);
// lcd.print("counting done");
// delay (3000);
if (!myFile.open("speed.csv", O_RDWR | O_CREAT | O_AT_END)) {
sd.errorHalt("opening test.txt for write failed");
//lcd.setCursor(0,1);
//lcd.print("Disk error:");
}
// else {
// lcd.setCursor(0,1);
// lcd.print("test opened");
// }
delay(3000);
for (int i = 0;i < 10; i ++) {
myFile.print(datalog[i]);
myFile.print(",");
myFile.println(timelog[i]);
Serial.print("ADC: ");
Serial.print(datalog[i]);
Serial.print(" Time: ");
Serial.println(timelog[i]);
}
//}
myFile.close();
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" Done");
delay(50000);
}
int adcpinread(int channel)
{
int adcvalue = 0;
byte transbyte = 6;
byte returnbyte;
digitalWrite(adcpin, LOW); // Turn on device "adcpin"
// Set the first byte to transfer,
// with with a start bit and a 1 for single ended
// (not differentail) and the MSB of the channel number
if (channel >3) {
transbyte = 7;
}
SPI.transfer(transbyte);
// Set the next transfer byte with the channel number
// minus the MSB and catch the first 4 bits of the
// return value
transbyte |= (channel << 6);
returnbyte = SPI.transfer(transbyte);
// add the first four bits of the valuse to adcvalue
// then shift them to the first four (of 12) bits
adcvalue = returnbyte & 15;
adcvalue = adcvalue << 8;
// recieve the last 8 bits and add them to adc value
returnbyte = SPI.transfer(0x0);
adcvalue += returnbyte;
//end communication with device adcpin
digitalWrite(adcpin, HIGH);
return adcvalue;
}