您的位置:首页 > 产品设计 > UI/UE

Arduino 串口读写 SD 卡模块

2017-07-06 22:13 701 查看
/*
Arduino 的 Nano 的引脚
MOSI----------11
MISO----------12
CLK-----------13
CS------------10
*/

#include <SD.h>

File myFile; // 文件的句柄
String filename = "mogu.txt"; // 文件名
const int chipSelect = 10;  // SD 卡使能引脚

#define BUFF_SIZE 128  // 缓冲区大小
char buff[BUFF_SIZE];  // 缓冲区数组
int readsize = 0;   // 实际读取的长度

// 单片机初始化函数
void setup() {
// 设置串口
// 波特率为 38400, 8位数据位, 2位停止位, 偶校验
Serial.begin(38400, SERIAL_8E2);

// 判断串口是否可用
// 如果不可用等在这里
while (!Serial) {
delay(1000);
}

Serial.println("Initializing SD card...");
// 初始化化 sd 卡
// 如果初始化失败, 打印log, 程序返回
if (!SD.begin(chipSelect)) {
Serial.println("initialization failed!");
return;
}

// 程序执行到这里,说明 sd 卡初始化完成
Serial.println("initialization done.");

// 判断文件是否存在
if (SD.exists(filename)) {
Serial.println("file exists, delete file");
// 如果文件存在, 删除文件
SD.remove(filename);
}

Serial.println("creat file");
// 旧文件删除, 新建文件
myFile = SD.open(filename, FILE_WRITE);
// 判断文建是否创建成功
// 如果文件创建失败, 打印log, 程序返回
if (!myFile) {
Serial.println("error opening file");
return;
}

//  myFile = SD.open(filename);
//  if (myFile) {
//    Serial.println("test.txt:");
//
//    // read from the file until there's nothing else in it:
//    while (myFile.available()) {
//      Serial.write(myFile.read());
//    }
//    // close the file:
//    myFile.close();
//  } else {
//    // if the file didn't open, print an error:
//    Serial.println("error opening test.txt");
//  }
}

void loop() {

}

// 串口中断入口函数
// 单片机接收到数据后自动调用此函数
void serialEvent() {
// 读取接收到的数据长度
while ((readsize = Serial.available()) > 0 ) {
// 判断文件操作是否可用
// 可用才能往文件里写数据
if (myFile) {
// 清空旧的缓存
memset(buff, 0, sizeof(buff));
// 将数据保存到缓冲区中
Serial.readBytes(buff, readsize);
// 再将缓冲区中的数据写入sd卡中
myFile.write(buff);
// 刷新 sd 卡
myFile.flush();
Serial.print(buff);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  arduino c sd卡 串口