我正在为 Azure IoT 中心编写代码,这需要在 Arduino 循环 () 中使用 c 函数。我遇到的问题是,如果我将 c 文件中创建的 float 的指针传递给 c++ 文件并修改该值,则 c++ 函数返回后在 c 文件中看到的内容是乱码。
这是一个伪代码示例,下面包含一个工作示例:
ino 文件中的loop():
运行 runInLoop(),在 c 文件 RunTest.c 中定义
RunTest.c 中的 runInLoop():
创建一个 float
将地址传递给FloatTest.cpp中定义的modifyFloat(float *address)
在modifyFloat()返回后打印 float 的值。
FloatTest.cpp中的modifyFloat(float *address):
为 *address
分配一个值
打印值
返回
我在下面的工作示例中执行了这个伪代码,串行监视器中的结果是:
Value assigned in modifyFloat: 22.55
The value that was returned is: 1077316812
我正在使用 Adafruit Huzzah Feather,其配置完全按照文档中的指示进行。
这是一个工作示例:
azure_troubleshoot.ino
#include "RunTest.h"
void setup()
{
initSerial();
}
void loop()
{
Serial.println("Starting main loop!\r\n");
runInLoop();
}
void initSerial()
{
Serial.begin(9600);
}
运行测试.c
#include "FloatTest.h"
void runInLoop(void)
{
while(1)
{
float testValue;
modifyFloat(&testValue);
(void)printf("The value that was returned is: %d\r\n", testValue);
delay(1000);
}
}
运行测试.h
#ifndef RUNTEST_H
#define RUNTEST_H
#ifdef __cplusplus
extern "C" {
#endif
void runInLoop(void);
#ifdef __cplusplus
}
#endif
#endif // RUNTEST_H
FloatTest.cpp
#include <Arduino.h>
#include "FloatTest.h"
void modifyFloat(float *address)
{
*address = 22.55;
Serial.print("Value assigned in modifyFloat: ");
Serial.println(*address);
}
FloatTest.h
#ifndef FLOATTEST_H
#define FLOATTEST_H
#ifdef __cplusplus
extern "C" {
#endif
void modifyFloat(float* address);
#ifdef __cplusplus
}
#endif
#endif // FLOATTEST_H
最佳答案
问题是在 RunTest.c 的 printf 字符串中使用了 %d。将代码更新为如下所示可以修复问题并生成输出:
Value seen in modifyFloat: 22.55
The value that was returned is: 22.55
运行测试.c
#include "FloatTest.h"
void runInLoop(void)
{
while(1)
{
float testValue;
modifyFloat(&testValue);
char str_tmp[6];
dtostrf(testValue, 4, 2, str_tmp);
(void)printf("The value that was returned is: %s\r\n", str_tmp);
delay(1000);
}
}
关于Arduino esp8266中的c++函数修改了c文件中生成的 float ,c++函数退出后在c文件中看到乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41726934/