2017-03-04 76 views
1

當寫入功能只接受整數時,如何讓Arduino將測量數據寫入micro SD卡?如何將整數寫入Arduino上的micro SD卡

#include <SD.h> 
#include <SPI.h> 

int CS_PIN = 10; 
int ledPin = 13; 
int EP =9; 



File file; 

void setup() 
{ 

    Serial.begin(9600); 
    pinMode(ledPin, OUTPUT); 
    pinMode(EP, INPUT); 

    initializeSD(); 



} 


void loop(){ 
    long measurement =TP_init(); 
    delay(50); 
// Serial.print("measurment = "); 
    Serial.println(measurement); 

    createFile("test.txt"); 
    writeToFile(measurement); 
    closeFile(); 
} 



long TP_init(){ 
    delay(10); 
    long measurement=pulseIn (EP, HIGH); //wait for the pin to get HIGH and returns measurement 
    return String(measurement); 

} 





void initializeSD() 
{ 
    Serial.println("Initializing SD card..."); 
    pinMode(CS_PIN, OUTPUT); 

    if (SD.begin()) 
    { 
    Serial.println("SD card is ready to use."); 
    } else 
    { 
    Serial.println("SD card initialization failed"); 
    return; 
    } 
} 

int createFile(char filename[]) 
{ 
    file = SD.open(filename, FILE_WRITE); 

    if (file) 
    { 
    Serial.println("File created successfully."); 
    return 1; 
    } else 
    { 
    Serial.println("Error while creating file."); 
    return 0; 
    } 
} 

int writeToFile(char text[]) 
{ 
    if (file) 
    { 
    file.println(text); 
    Serial.println("Writing to file: "); 
    Serial.println(text); 
    return 1; 
    } else 
    { 
    Serial.println("Couldn't write to file"); 
    return 0; 
    } 
} 

void closeFile() 
{ 
    if (file) 
    { 
    file.close(); 
    Serial.println("File closed"); 
    } 
} 

int openFile(char filename[]) 
{ 
    file = SD.open(filename); 
    if (file) 
    { 
    Serial.println("File opened with success!"); 
    return 1; 
    } else 
    { 
    Serial.println("Error opening file..."); 
    return 0; 
    } 
} 

String readLine() 
{ 
    String received = ""; 
    char ch; 
    while (file.available()) 
    { 
    ch = file.read(); 
    if (ch == '\n') 
    { 
     return String(received); 
    } 
    else 
    { 
     received += ch; 
    } 
    } 
    return ""; 
} 
+0

你爲什麼宣佈TP_init的'返回值( )'作爲'long'並在函數內返回'String'('返回String(測量);')? –

回答

0

可以編寫使用接受緩衝器和字節計數的write函數的該變體的4個字節的值long。只是通過你想要寫出來的變量的地址和類型的大小:

long measurement; 

file.write((byte*)&measurement, sizeof(long)); // write 4 bytes 

你可以這樣閱讀:

file.read((byte*)&measurement, sizeof(long)); // read 4 bytes 
+0

你是什麼意思,我會把文件,寫入文件函數寫東西? –

+0

writeToFile函數寫入一串字符,所以你不能把它放在那裏。寫另一個函數writeLongToFile或類似 – samgak