Hag*_*ble 1 c arrays c-preprocessor
我曾经从一个ADC发送了5秒的数据,这个数据是在125 SPS发送样本,这转换为大小为5*125的数组.在我的代码中,这看起来像:
#define SPS 125
#define TIME 5
char Samples[SPS * TIME];
Run Code Online (Sandbox Code Playgroud)
现在,我想捕获2.5秒的数据并将ADC采样率提高到250 SPS.在代码中它看起来像:
#define SPS 250
#define TIME 2.5
char Samples[SPS * TIME];
Run Code Online (Sandbox Code Playgroud)
但是,如果我这样做,编译器会抛出一个错误:
#901 expression must have integral or enum type main.cpp line 59 C/C++ Problem
Run Code Online (Sandbox Code Playgroud)
我能够理解它的含义.
但是,克服这种情况的最佳方法是保持SPS和TIME定义的可用性.我的意思是我已经在整个项目的其他几个地方使用它们,我希望继续使用它们.
请帮忙!
问题是结果转换为float(或double),但数组的大小必须是整数类型.最简单的解决方案是@CoolGuy建议的,你可以将它转换为int.这是一个例子
#define SPS 125
#define TIME 2.5
char Samples[ (int)(SPS * TIME) ];
Run Code Online (Sandbox Code Playgroud)
我假设这是一个嵌入式系统,所以你可能不想为此使用浮点数,因为这样做通常会强制你将浮点库链接到项目.
浮点免费版:
#define SPS 250ul
#define TIME_MS 2500ul
#define SAMPLES_N ( (SPS * TIME_MS) / 1000ul )
char Samples[SAMPLES_N];
Run Code Online (Sandbox Code Playgroud)
如果你坚持使用float:
#define SPS 250
#define TIME 2.5
#define SAMPLES_N ((unsigned long)(SPS * TIME))
char Samples[SAMPLES_N];
Run Code Online (Sandbox Code Playgroud)
(这两个片段适用于所有平台,包括小型8/16位MCU应用程序.与使用int的所有发布的答案不同,它们是非便携式的.)