在连接到 Arduino 的 SD 卡中存储新文件
在本教程中,我们将创建一个新的文件,该文件存储在连接到 Arduino Uno 的 SD 卡中。
电路图
电路图如下所示:

如您所见,您需要进行以下连接:
| SD 卡座 | Arduino Uno |
|---|---|
| Vcc | 5V |
| GND | GND |
| MISO | 12 |
| MOSI | 11 |
| SCK | 13 |
| CS | 10 |
仅对于 Vcc,请确保您的 SD 卡座以 5V 作为输入。如果它接收 3.3V,则将其连接到 Arduino Uno 上的 3.3V 引脚。
代码演练
我们将逐步介绍内置 SD 库附带的示例代码。您可以从 文件 → 示例 → SD → Datalogger 中访问它。

或者,您可以在 GitHub 上访问代码:https://github.com/adafruit/SD/blob/master/examples/Datalogger/Datalogger.ino 我们首先包含 SPI 和 SD 库,并设置 chipSelect 引脚(我们将将其设置为 10)。
#include <SPI.h> #include <SD.h> const int chipSelect = 10;
在 Setup 中,我们初始化 Serial 和 SD 卡。
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
while (1);
}
Serial.println("card initialized.");
}在循环中,我们从 3 个模拟引脚读取数据,并将其存储在名为 dataString 的字符串中。然后,我们使用 SD.open() 函数以 FILE_WRITE 模式打开文件 datalog.txt。**此函数会在文件不存在时创建文件**。然后我们将新的 dataString 附加到文件中并关闭文件。标准命令 dataFile.println() 用于将数据附加到文件。
void loop() {
// make a string for assembling the data to log:
String dataString = "";
// read three sensors and append to the string:
for (int analogPin = 0; analogPin < 3; analogPin++) {
int sensor = analogRead(analogPin);
dataString += String(sensor);
if (analogPin < 2) {
dataString += ",";
}
}
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile = SD.open("datalog.txt", FILE_WRITE);
// if the file is available, write to it:
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
// print to the serial port too:
Serial.println(dataString);
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP