1

我正在构建一个程序,它对模拟电压进行 10 次测量pin0并将其打印到日志文件中。当我尝试确保文件为空白时,我遇到了问题。我正在使用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;
}
4

2 回答 2

0

所以.. 首先你看看 LOGFILE.LOG 是否存在,如果存在则删除 ANALOG.LOG。然后创建 ANALOG.LOG。之后,您检查 LOGFILE.LOG 是否存在。如果没有,则打印错误并打开 ANALOG.LOG。

LOGFILE.LOG 的目的究竟是什么?您不应该将LOGFILE更改为ANALOG吗?

于 2012-11-01T08:52:28.850 回答
0

我找到了错误的根源。当我if(SD.exists())打开一个新的日志文件后打电话时,图书馆不喜欢那样。我假设SD.exists()只是检查 open 返回的地址或对象是否为 NULL。但是,在文件已经打开时调用它会导致一些奇怪的行为。在打开内部删除该调用后,一切都很好。感谢所有的建议!

于 2012-11-04T20:12:31.017 回答