2016-05-04 117 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