我正在构建一个程序,它在pin0
上对模拟电压进行10次测量并将其打印到日志文件中。当我尝试确保文件为空时,我遇到的问题就出现了。我正在使用SD.remove()
来删除以前的日志文件。当我这样做时,新的日志文件永远不会被写入。当我删除对SD.remove()
的调用时,程序正常工作。这是SD库中的一些已知错误,还是有一些偷偷摸摸的方法呢?
代码如下。
#include <SD.h>
#define OUTPUT_PIN 9 //Using SparkFun MP3 shield
#define DEFAULT_OUTPUT 10
#define VOLTAGE_REF (5)
//Reads a voltage on pin0. by default, the reference voltage is set to 5 V, but
//it can be changed by changing VOLTAGE_REF.
void setup() {
Serial.begin(9600);
Serial.println("Program Initialized");
pinMode(DEFAULT_OUTPUT ,OUTPUT); //Needs to be on to use the library
pinMode(0, INPUT);
if (!SD.begin(OUTPUT_PIN)) {
//init error
Serial.println("Error initializing SD card. Reset the Arduino and try again");
return;
}
Serial.println("Card sucessfully initialized");
if (SD.exists("LOGFILE.LOG") {
SD.remove("LOGFILE.LOG"); //We don't want to use the same file <<THIS IS THE BUG?
}
delay(10); //Make sure changes are applied
File logFile = SD.open("ANALOG.LOG", FILE_WRITE); //Create a new one every time
if (!SD.exists("LOGFILE.LOG")) {
Serial.println("There was some error making a new instance of the logfile?");
delay(1000);
SD.open("ANALOG.LOG", FILE_WRITE);
}
int i;
if (logFile) {
for(i=0;i<10;i++) {
int j = 0;
char str[64];
Serial.print("Reading analog sensor value");
for(j=0;j<=i;j++) {
Serial.print(".");
}
Serial.println();
logFile.print("Read #");
logFile.print(i+1);
logFile.print(" : ");
logFile.print(doVoltageRead(0));
unsigned char l = logFile.println(" V");
if (!l)
Serial.println("No data written");
delay(500);
}
Serial.println("Done.");
logFile.close(); //Close the logfile
Serial.println("Data sucessfully written");
}
else {
//Couldn't create file
Serial.println("There was an error creating the logfile");
}
}
void loop() {
//We don't really need to do anything here
}
float doVoltageRead(int pin) {
int voltageRead = analogRead(pin);
double divisor = (voltageRead * 0.00097752);
float finalVoltage =(VOLTAGE_REF * divisor);
Serial.println(finalVoltage);
return finalVoltage;
}
答案 0 :(得分:0)
所以..首先你看看LOGFILE.LOG是否存在,如果你删除了ANALOG.LOG。然后你创建ANALOG.LOG。之后,检查LOGFILE.LOG是否存在。如果没有,则打印错误并打开ANALOG.LOG。
LOGFILE.LOG的目的究竟是什么?你不应该只将LOGFILE改为ANALOG吗?
答案 1 :(得分:0)
我找到了错误的来源。在打开新日志文件后调用if(SD.exists())
时,库不喜欢这样。我假设SD.exists()
只是检查open返回的地址或对象是否为NULL。但是,在文件已经打开时调用它会导致一些奇怪的行为。在打开内部删除该调用后,一切都很顺利。感谢所有的建议!