arduino 使用日志系统
https://github.com/thijse/Arduino-Log
#include <ArduinoLog.h> // 日志, https://github.com/thijse/Arduino-Log
// #define DISABLE_LOGGING // 关闭日志功能
void setup()
{
Serial.begin(9600);
initLog();
}
void loop()
{
Log.infoln("初始化 lcd"); // 使用日志系统
delay(300);
}
// 初始化日志系统
void initLog()
{
Log.setPrefix(printPrefix); // 日志前加入日期及类型
// Log.setSuffix(printSuffix); // set suffix 日志后加一些东西
Log.begin(LOG_LEVEL_VERBOSE, &Serial); // 绑定日志至串口
Log.setShowLevel(false); // 不显示默认的日志类型, printPrefix 已定制相关信息
}
// 日志前加内容
void printPrefix(Print *_logOutput, int logLevel)
{
printTimestamp(_logOutput);
printLogLevel(_logOutput, logLevel);
}
void printTimestamp(Print *_logOutput)
{
char timestamp[20]; // Time as string
getCurrentTime(timestamp);
_logOutput->print(timestamp);
}
// 返回当前的时间
void getCurrentTime(char* timestamp){
// Division constants
const unsigned long MSECS_PER_SEC = 1000;
const unsigned long SECS_PER_MIN = 60;
const unsigned long SECS_PER_HOUR = 3600;
const unsigned long SECS_PER_DAY = 86400;
// Total time
const unsigned long msecs = millis();
const unsigned long secs = msecs / MSECS_PER_SEC;
// Time in components
const unsigned long MilliSeconds = msecs % MSECS_PER_SEC;
const unsigned long Seconds = secs % SECS_PER_MIN;
const unsigned long Minutes = (secs / SECS_PER_MIN) % SECS_PER_MIN;
const unsigned long Hours = (secs % SECS_PER_DAY) / SECS_PER_HOUR;
// 注意使用 %ld 显示 long 类型, 不然会只显示 0
sprintf(timestamp, "%02ld:%02ld:%02ld.%03ld ", Hours, Minutes, Seconds, MilliSeconds);
}
void printLogLevel(Print *_logOutput, int logLevel)
{
/// Show log description based on log level
switch (logLevel)
{
default:
case 0:
_logOutput->print("SILENT ");
break;
case 1:
_logOutput->print("FATAL ");
break;
case 2:
_logOutput->print("ERROR ");
break;
case 3:
_logOutput->print("WARNING ");
break;
case 4:
_logOutput->print("INFO ");
break;
case 5:
_logOutput->print("TRACE ");
break;
case 6:
_logOutput->print("VERBOSE ");
break;
}
}
void printSuffix(Print *_logOutput, int logLevel)
{
_logOutput->print("");
}