Arduino esp8266中的c++函数修改了c文件中生成的float,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

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

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

ino 文件中的循环():
运行在 c 文件 RunTest.c

中定义的 runInLoop()

RunTest.c 中的 runInLoop():
创建一个浮动
将地址传递给 FloatTest.cpp
中定义的 modifyFloat(float *address) 在 modifyFloat() returns.

之后打印浮点数的值

modifyFloat(float *address) 在 FloatTest.cpp:
为 *address
分配一个值 打印值
return

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

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);
}

RunTest.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);
    }

}

RunTest.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

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: %s\r\n", str_tmp);
        delay(1000);
    }

}