Arduino uses SD card module to write sensor data
foreword
For the specific SD card wiring, please refer to the Arduino read and write SD card module (to obtain SD card information).
This blog uses the temperature and humidity sensor DHT22 as an example. As for other sensors, you can draw inferences from one another.
hardware preparation
SD card module
temperature and humidity sensor DHT22
DHT22 | Arduino |
---|---|
+ | 5V |
S | 7 |
GND | GND |
code section
Temperature and humidity detection
#include <dht.h>
#define DHTPin 7
dht DHT;
void loop() {
int readData = DHT.read22(DHTPin);
float t = DHT.temperature;
float h = DHT.humidity;
Serial.print("Temperature = ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(" Humidity = ");
Serial.print(h);
Serial.println(" % ");
Create .txt file
myFile = SD.open("可以自主命名.txt", FILE_WRITE);
Function to write to SD card: "myFile"
if (myFile) {
myFile.print("Temperature = ");
myFile.print(t);
myFile.print(",");
myFile.print(" Humidity = ");
myFile.println(h);
myFile.close(); //结束文件记录
}
Determine if the file can be opened
else {
Serial.println("error opening data.txt");
}
full code
#include <SD.h>
#include <SPI.h>
#include <dht.h>
#define DHTPin 7
dht DHT;
File myFile;
int pinCS = 4;
void setup() {
Serial.begin(9600);
pinMode(pinCS, OUTPUT);
// SD Card Initialization
if (SD.begin())
{
Serial.println("SD card is ready to use.");
} else
{
Serial.println("SD card initialization failed");
return;
}
}
void loop() {
int readData = DHT.read22(DHTPin);
float t = DHT.temperature;
float h = DHT.humidity;
Serial.print("Temperature = ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(" Humidity = ");
Serial.print(h);
Serial.println(" % ");
myFile = SD.open("data.txt", FILE_WRITE);
if (myFile) {
myFile.print("Temperature = ");
myFile.print(t);
myFile.print(",");
myFile.print(" Humidity = ");
myFile.println(h);
myFile.close(); // close the file
}
else {
Serial.println("error opening data.txt");
}
delay(500);
}
renderings
Check that the DATA.txt
data in the SD card has been successfully written! ! !
Postscript supplement
We can use the data recorded in the SD card to draw tables and line graphs, etc. Good luck
in drawing it into a line graph !
! !