Arduino esp8266中的c++函数修改了c文件中生成的浮点值,在c++函数退出后,c文件中会出现胡言乱语

c++ function in Arduino esp8266 modifies a float generated in a c file, gibberish seen in the c file after the c++ function exits

本文关键字:文件 函数 c++ 退出 胡言乱语 修改 中的 esp8266 Arduino      更新时间:2023-10-16

我正在为Azure IoT Hub编写代码,它需要在Arduino loop()中使用c函数。我遇到的问题是,如果我将一个指向c文件中创建的浮点值的指针传递给一个c++文件并修改该值,那么在c++函数返回后,在c文件中看到的是胡言乱语。

下面是一个伪代码示例,下面包括一个工作示例:

loop()在ino文件中:
运行runInLoop(),在c文件RunTest.c 中定义

RunTest.cp:
中的runInLoop()创建一个float
将地址传递给在FloatTest.cpp中定义的modifyFloat(float*地址)
在modifyFloot()返回后打印float的值。

FloatTest.cpp中的modifyFloat(float*地址):
将值分配给*地址
打印值
返回

我在下面的工作示例中执行了这个伪代码,串行监视器中的结果是:

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!rn");
runInLoop();
}
void initSerial()
{
Serial.begin(9600);
}

RunTest.c

#include "FloatTest.h"
void runInLoop(void)
{
while(1)
{
float testValue;
modifyFloat(&testValue);
(void)printf("The value that was returned is: %drn", 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);
}

浮动测试.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

RunTest.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: %srn", str_tmp);
delay(1000);
}
}