【问题标题】:Arduino printing of two-digit month format两位数月份格式的Arduino打印
【发布时间】:2017-10-12 03:51:33
【问题描述】:

我的 Arduino 设置中有此代码,用于使用日期创建文件名。它可以工作,但是有一个问题。

#include <DS3231.h>
#include <SD.h>
#include <SPI.h>
#include <dht.h>

dht DHT;

Time now;

int dt;
int t;
unsigned int interation = 1;
char filename[12];  

DS3231  rtc(SDA, SCL);  

void setup() {
  Serial.begin(9600);
  rtc.begin(); // Initialize the rtc object
  rtc.setDOW(THURSDAY); // Set Day-of-Week to SUNDAY
  rtc.setTime(21, 48, 0); // Set the time to 12:00:00 (24hr format)
  rtc.setDate(10, 11, 2017); // Set the date to January 1st, 2014
  now = rtc.getTime();
  String(String(now.year) + String(now.mon) + String(now.dow) + ".csv").toCharArray(filename, 12);
  Serial.println(filename);

打印一个日期字符串,但是当它是单个数字时,月份数字中没有前导零。

代码打印此2017111.csv 而不是20170111.csv。我该如何解决这个问题?

【问题讨论】:

  • 注释和代码看起来不一致。 rtc.setDate(10, 11, 2017); // Set the date to January 1st, 2014 与输出不一致 2017111.csv
  • Arduino 代码具体不是 C 而是 C++
  • 只是为了完成:当日期是个位数时,这是否也会出现?一个简单的解决方案是if(now.mon &lt; 10){Stringwithadded0}else{Stringnormal}
  • chux,是的,代码有点不对劲。字符串需要这样设置String(String(now.year) + String(now.mon) + String(now.date) + ".csv").toCharArray(filename, 13);现在注释和代码一致了。
  • H. Puc,是的,如果它是个位数,它也会在当天发生。我不确定如何实施您提供的解决方案。

标签: c++ date time arduino format


【解决方案1】:

你需要一个 if 语句来测试这个数字是否小于 10,如果是则添加你自己的 0。

String myMonthString = "";
int mon = now.mon;
if(mon < 10){
   myMonthString += '0';
}
myMonthString += mon;

更优雅的解决方案是使用 sprintf。这也没有使用 String 类,它可以在小型微控制器上做一些坏事,通常在 Arduino 上要避免。

char fileName[12];
sprintf(fileName, "%d%02d%02d.csv", now.year, now.mon, now.dow);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多