arduino - 如何将注定要控制台的数据传递到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];
解决方案
这个例子应该做你需要的基本事情,如果你理解它从 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);
}
}
推荐阅读
- c# - 控制器的非异步方法是否会阻止其他用户在使用或锁定时进入?
- f# - 如何在 F# 中使用 C# 可为空的日期时间
- c++ - CMake 找不到 boost_test
- python - 如何将函数中的值设置为 CSV?
- php - Wordpress 添加重写规则重定向而不是“隐藏”
- youtube - Youtube 评论 API 抛出“权限不足:请求的身份验证范围不足”错误
- ios - 当我的应用程序在后台运行时,是否可以获取用户正在使用的当前应用程序?
- python - Pandas 中的索引与 dplyr 相比
- scala - 我无法从 Jupyter 运行 scala
- java - 调用 setText() 时 JavaFX 文本不会改变