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
我正在为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);
}
}
相关文章:
- C++ gmock - 我们如何在单元测试 cpp 文件中读取/获取 cpp 文件函数的参数值
- 使用其他头文件函数的头文件
- 创建文件函数是否可以打开仅在WinObj实用程序中的全局目录下列出的设备的句柄?
- 如何指定创建文件函数获取未缓存的结果?
- 标准库头文件函数原型的实现是如何用 c++ 编写的?
- 如何将类对象作为对另一个头文件函数的引用传递
- 读取文件函数lpbuffer和字节以读取澄清
- C++ - 未定义的对多个文件函数的引用
- 使用C++的可视 Unicode 文件函数
- C 创建文件函数错误
- WinAPI 创建文件函数 2.
- 具有CREATE_ALWAYS处置的创建文件函数
- 重写c库文件函数
- 如何使用客户端调用堆栈中的地址从 PDB 检索文件/函数/行号?
- 通过头文件函数将遍历的数据从二进制搜索树加载到Vector中
- 需要帮助无法弄清楚为什么我的头文件函数声明不起作用
- 是否可以在不使用文件函数的情况下使用代码块从文件运行某些用例测试?
- 如何用c++文件函数读写8位整数单位形式的数据
- 在c++中读文件函数如何识别文本文件的结束
- 使用Windows API的c++文件函数