【发布时间】:2017-05-17 09:44:44
【问题描述】:
我正在尝试让我的 Arduino 类返回带有各种日志信息的字符串消息。经过大量试验和错误,我设法将日志记录函数的引用传递给类,但只能得到一个 char* 而不是一个字符串,我希望能够发送字符串,从而更容易发回所有各种数据。
我已经完成了第一部分。 草图:
#include <Test.h>
#include <string.h>
void setup() {
Serial.begin(115200);
Test t;
t.setLogging(writeLog);
writeLog("Test message!" + String(" .... "));
t.doSomething("This is useful.");
t.doSomething("This as well.\n");
t.doSomething("This is even more useful.\n");
bool b = true;
}
void loop() {
}
void writeLog (char* message) {
Serial.print("char function: ");
Serial.print(message);
}
void writeLog (String message) {
Serial.print("String function: ");
Serial.println(message);
}
头文件:
#ifndef TEST_h
#define TEST_h
class Test
{
public:
Test(); // The constructor.
void setLogging(void (*)(char*)); // Takes function setting where to log.
void doSomething(char*);
};
#endif
班级:
#include <Test.h>
typedef void (*LogFunction)(char*);
LogFunction writeLog;
Test::Test () {
}
void Test::doSomething (char* s) {
// Do something useful and log the result.
writeLog(s);
}
void Test::setLogging (void (*f)(char*) ) {
writeLog = f;
return;
}
现在我希望我的班级能够发送这样的信息,作为字符串,而不是 char*(我还没有找到一种简单的方法将“任何”转换为 char*,然后将两者连接起来或更多字符串):
writeLog ("HydroMonitorECSensor::setCalibration Receiving calibration - haveCalibration = " + String(haveCalibration));
writeLog ("HydroMonitorECSensor::setCalibration calibratedSlope = " + String(calibratedSlope));
writeLog ("HydroMonitorECSensor::setPins capPos set to " + String(capPos));
其中haveCalibration 是bool(字符串变为“真”或“假”),calibratedSlope 是double,capPos 是int。这样我可以轻松干净地将完整的行发送到记录器。在主脚本中效果很好 - 而不是在课堂上。
我尝试简单地将char* 更改为String 并将#include <string.h> 添加到库文件中,但它不起作用。
然后在 Test.cpp 中我得到 void Test::setLogging (void (*f)(String) ) { 和在 Test.h 中 void setLogging(void (*)(String)); 现在我得到错误消息:
In file included from /home/wouter/Arduino/libraries/Test/Test.cpp:1:0:
/home/wouter/Arduino/libraries/Test/Test.h:10:29: error: expected ',' or '...' before '(' token
void setLogging(void (*)(String)); // Takes function setting where to log.
^
/home/wouter/Arduino/libraries/Test/Test.cpp:16:40: error: variable or field 'setLogging' declared void
void Test::setLogging (void (*f)(String) ) {
^
/home/wouter/Arduino/libraries/Test/Test.cpp:16:31: error: 'f' was not declared in this scope
void Test::setLogging (void (*f)(String) ) {
^
/home/wouter/Arduino/libraries/Test/Test.cpp:16:34: error: 'String' was not declared in this scope
void Test::setLogging (void (*f)(String) ) {
^
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).
建议?
附加信息,也许很重要:我正在使用 Arduino IDE 并为 ESP8266 进行编译。
【问题讨论】: