2016-07-09 114 views
0

我正試圖使用​​卡模塊從串行端口寫入Arduino Mega 2560中的SD卡。從串行端口寫入SD卡

我希望能夠在txt文件中寫入我在串行com中輸入的內容。

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

const int chipSelect = 4; 
void setup() { 
    // put your setup code here, to run once: 
    Serial.begin(9600); 
    Serial.print("This is a test and should be ignored"); 
    if (!SD.begin(chipSelect)) { 
    Serial.println("\nCard failed, or not present"); 
    // don't do anything more: 
    return; 
    } 
    else{ 
    Serial.println("\ncard initialized."); 
} 
} 


void loop() { 
    // put your main code here, to run repeatedly 
File OpenFile = SD.open("test.txt", FILE_WRITE); 
    if(OpenFile and Serial.available()); 
    { 
    OpenFile.println(Serial1.read()); 
    OpenFile.close(); 
    } 
} 

不過的連續行「-1」和「1」,沒有了」,被寫入SD。

是的,我可以通過其他方法來寫入SD卡。 ..

歡呼聲,流行

回答

0

我注意到你正在檢查Serial.available()但使用串行從:)

一讀你有一個兆豐,你不會得到一個錯誤,因爲有SerialSerial1。我會說這是你的罪魁禍首!

當沒有數據時,Stream讀取函數將返回-1。你也可以減輕你的Arduino負載,並且一次完成所有操作(每個字節不打開/關閉)並清除所有可用數據(如果你不知道,Serial.read()只讀取一個字節)。

void loop() { 

    File OpenFile = SD.open("test.txt", FILE_WRITE); 

    if(OpenFile){ 
    while(Serial.available()){ 
     OpenFile.println(Serial.read()); 
    } 
    OpenFile.close(); 
    } 
} 

您可能要檢查SD LIB默認支持或類似FILE_APPEND標誌追加,你將覆蓋下一個循環的文件,如果數據越來越多(串行數據不是即時,你的代碼可能在接收其餘數據時循環)。

+0

它的工作!但它是ASCII碼(代碼在另一個comp ...)。如果將來有人需要幫助,你必須用char來解析Serial.read :) – PoP

+0

@PoP如果答案幫助解決了你的問題,你可以考慮增加一個投票,還是選擇它作爲答案。乾杯 –