使用SD卡保存CSV数据文件-Arduino中文社区 - Powered by Discuz! Archiver

vany5921 发表于 2020-1-7 19:39

使用SD卡保存CSV数据文件

    CSV是一种常用的文本数据格式记录文件,使用逗号来分割字段,以下示例将演示如何通过CSV文件记录按下A,B,C按键的真实时间。你可以将按键替换为传感器,比如记录一天当中的温湿度数据。

#include <M5Stack.h>
#include <WiFi.h>
#include <time.h>

char ssid[] = "M5-5G";
char pass[] = "Office@888888";

char ntpServer[] = "cn.pool.ntp.org";//连接中国NTP服务器
const long gmtOffset_sec = 8 * 3600; //格林尼治时间GMT8
const intdaylightOffset_sec = 28800; //设置时差
struct tm timeinfo;
String dateStr;
String timeStr;

File file;

const char* fname = "/btnevent_log.csv"; //路径名称
char *eventName[] = { "按下按键A", "按下按键B", "按下按键C" }; //保存内容

void getTimeFromNTP(){   //获取NTP时间

configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
while (!getLocalTime(&timeinfo)) {
    delay(1000);
}
}

void getTime(){    //屏幕打印

getLocalTime(&timeinfo);
dateStr = (String)(timeinfo.tm_year + 1900)
          + "/" + (String)(timeinfo.tm_mon + 1)
          + "/" + (String)timeinfo.tm_mday;
timeStr = (String)timeinfo.tm_hour
          + ":" + (String)timeinfo.tm_min
          + ":" + (String)timeinfo.tm_sec;

M5.Lcd.setTextColor(WHITE,BLACK);
M5.Lcd.setCursor(0, 50, 1);
M5.Lcd.println(dateStr + "   ");
M5.Lcd.println(timeStr + "   ");
}


void writeData(char *paramStr) {   //向SD卡写入数据

file = SD.open(fname, FILE_APPEND);
file.println(dateStr + "," + timeStr + "," + paramStr);
file.close();
}

void setup()
{
M5.begin();
M5.Lcd.fillScreen(BLACK);
M5.Lcd.setTextSize(2);
M5.Lcd.setTextColor(WHITE,BLACK);
M5.Lcd.println("CSV Writer");

WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    M5.Lcd.print(".");
}
M5.Lcd.println("\nWiFi connected.");

getTimeFromNTP();

}

void loop()
{
M5.update();

getTime();

M5.Lcd.setCursor(0, 100, 1);


if (M5.BtnA.wasPressed()) {
    M5.Lcd.print("Button A Pressed");
    writeData(eventName);
}
if (M5.BtnB.wasPressed()) {
    M5.Lcd.print("Button B Pressed");
    writeData(eventName);
}
if (M5.BtnC.wasPressed()) {
    M5.Lcd.print("Button C Pressed");
    writeData(eventName);
}
}
页: [1]
查看完整版本: 使用SD卡保存CSV数据文件