2016-05-04 123 views
1

我的最終目標是通過XBEE向另一個arduino發送30 KB文件。但現在我只是試圖複製SD上連接到第一個arduino的4KB文件。首先我試圖發送一個字節一個字節的數據。它工作併成功複製文件。但我必須有一個緩衝區,然後將64字節數據包的數據發送到XBEE,所以我應該能夠讀寫64字節數據包中的文件。這是我做了什麼:使用arduino進行文件傳輸

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

void setup() { 

Serial.begin(115200); 
while (!Serial) { 
; // wait for serial port to connect. Needed for native USB port only 
    } 
if (!SD.begin(4)) { 

Serial.println("begin failed"); 
return; 
    } 

File file = SD.open("student.jpg",FILE_READ); 
File endFile = SD.open("cop.jpg",FILE_WRITE); 
Serial.flush(); 

char buf[64]; 
if(file) { 

while (file.position() < file.size()) 
     { 
    while (file.read(buf, sizeof(buf)) == sizeof(buf)) // read chunk of 64bytes 
     { 
     Serial.println(((float)file.position()/(float)file.size())*100);//progress % 
     endFile.write(buf); // Send to xbee via serial 
     delay(50); 
     } 


     } 
     file.close(); 
} 

} 
    void loop() { 

} 

它成功地完成它的進度,直至100%,但是當我打開SD筆記本電腦上創建文件卻顯示爲0 KB文件。

最新問題?

+0

添加評論: 我剛剛添加的行: endFile.close(); 現在輸出文件是2 KB和損壞。但源文件是3 KB。 – alireza

回答

2

你不告訴.write你的緩衝區的長度是多少,所以它會認爲它是一個以空字符結尾的字符串(它不是)。

另外,內部循環似乎不僅是不必要的,而且甚至是有害的,因爲如果它小於64字節,它將跳過最後的塊。

檢查了這一點:

while(file.position() < file.size()) { 
    // The docs tell me this should be file.readBytes... but then I wonder why file.read even compiled for you? 
    // So if readBytes doesn't work, go back to "read". 
    int bytesRead = file.readBytes(buf, sizeof(buf)); 
    Serial.println(((float)file.position()/(float)file.size())*100);//progress % 

    // We have to specify the length! Otherwise it will stop when encountering a null byte... 
    endFile.write(buf, bytesRead); // Send to xbee via serial 

    delay(50); 
} 
+0

感謝男人...ü救了我:)現在它的作品現在該文件成功複製 – alireza