1

I used to capture 5 seconds of data from an ADC which was sending samples at 125 SPS, this translated to having an array of size 5 * 125. In my code this looked like:

#define SPS 125
#define TIME 5

char Samples[SPS * TIME];

Now, I would like to capture 2.5 seconds of data and increase the ADC sampling rate to 250 SPS. In the code it looks like:

#define SPS 250
#define TIME 2.5

char Samples[SPS * TIME];

But if I do this the compiler throws up an error as:

#901 expression must have integral or enum type main.cpp line 59 C/C++ Problem

I'm able to understand what it is saying.

But what is the best way to overcome this situation keeping the SPS and TIME definition's usability in mind. I mean I've used them in several other places across the project and I wish to keep using them as they are.

Kindly help!

4
  • 3
    Maybe a cast would work. Try casting the result into int Commented Apr 28, 2015 at 6:15
  • 2
    Define time in milliseconds. Commented Apr 28, 2015 at 6:19
  • 1
    another way is defined separate numerator and denominator for TIME, and declare char Samples[SPS * TIME_NUM / TIME_DENOM]; Commented Apr 28, 2015 at 6:19
  • The problem is that you've got a "mixed expression": integer * floating point; the final expression resulting in floating point. One solution, as both Cool Guy and Arun A.S correctly suggested, is to "cast" the expression to "int". Commented Apr 28, 2015 at 6:23

3 Answers 3

6

The problem is that the result is converted to a float ( or double ), but the size of an array must be an integral type. The easiest solution would be as suggested by @CoolGuy, you can cast it to an int. Here is an example

#define SPS 125
#define TIME 2.5

char Samples[ (int)(SPS * TIME) ];
Sign up to request clarification or add additional context in comments.

Comments

5

I'm assuming this is an embedded system, so you probably don't want to use float numbers for this, as doing so typically forces you to link a floating point library to the project.

Float free version:

#define SPS       250ul
#define TIME_MS   2500ul
#define SAMPLES_N ( (SPS * TIME_MS) / 1000ul )

char Samples[SAMPLES_N];

If you insist on using float:

#define SPS        250
#define TIME       2.5
#define SAMPLES_N  ((unsigned long)(SPS * TIME))

char Samples[SAMPLES_N];

(These two snippets will work on all platforms, including small 8/16 bit MCU applications. Unlike all the posted answers using int, which are non-portable.)

Comments

2

Have you tried casting to unsigned int?

char Samples[(unsigned int)(SPS * TIME)];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.