首页 > 解决方案 > 如何将注定要控制台的数据传递到Arduino中的char数组

问题描述

在 Arduino 上使用 RTC 的草图中,我有以下代码:

// print time to Serial
void printTime(time_t t){
  printI00(hour(t), ':');
  printI00(minute(t), ':');
  printI00(second(t), ' ');
}

// print date to Serial
void printDate(time_t t){
  printI00(day(t), 0);
  Serial << monthShortStr(month(t)) << _DEC(year(t));
}

并通过此打印控制台上的 RTC 读数:

void printDateTime(time_t t) {
  printDate(t);
  Serial << ' ';
  printTime(t);
}

我该怎么做才能让我发送到控制台的内容也存储在一个 char 数组中?

char bufferMSGtoClient[100];

标签: arduino

解决方案


这个例子应该做你需要的基本事情,如果你理解它从 sprintf 更改为方法 strcpy 和 strcat 和 iota 以提高内存效率:

// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;
unsigned long currentTime = 0;
unsigned long intervalTime = 1000;   // one print every second

char timeStamp[12] = {'\0'};
char dateStamp[11] = {'\0'};

char meridian [3] = {'\0'};

void setup () {
  Serial.begin(115200);
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}

void loop () {
  if (millis() - currentTime > intervalTime) {
    DateTime now = rtc.now();
    byte twelveHour = now.hour() - 12; // Variable used to display 13+ hours in 12 hour format
    byte zeroHour = 12;                // Variable use to convert "0" zero hour to display it as 12:00 +
    byte displayHour;
    byte MIN = now.minute();
    byte SEC = now.second();

    if (now.hour() == 0)   { // First we test if the hour reads "0"
      displayHour = zeroHour;
      strcpy (meridian, "AM");
    }
    else if (now.hour() >= 13)    {    // if no, Second we test if the hour reads "13 or more"
      displayHour = twelveHour;
      strcpy (meridian, "PM");
    }
    else {
      displayHour = now.hour();
      strcpy (meridian, "AM");
    }
    sprintf(timeStamp, "%02d:%02d:%02d-%s", displayHour, MIN, SEC, meridian);
    sprintf(dateStamp, "%02d/%02d/%04d", now.month(), now.day(), now.year());

    Serial.println(timeStamp);
    Serial.println(dateStamp);
  }
}

推荐阅读