Avoid FP math with the pre-processor.
// Avoid the following
#define FS 16000.0f
#define COUNTER1_LIMIT ( ( RANGE1_ms/1000.0f)* FS/BS )
Alternative 1: use integer math that rounds quotients to nearest. Adding half the divisor works when dividend/divisor are positive.
#define RANGE1_ms 64
#define FS 16000
#define BS 64
#define ms_PER_s 1000
#define COUNTER1_LIMIT_N (1ul * RANGE1_ms * FS)
#define COUNTER1_LIMIT_D (1ul * ms_PER_s * BS )
#define COUNTER1_LIMIT_I ((COUNTER1_LIMIT_N + COUNTER1_LIMIT_D/2)/COUNTER1_LIMIT_D)
#define COUNTER1_LIMIT_F (1.0*COUNTER1_LIMIT_N/COUNTER1_LIMIT_D)
if (counter1 == COUNTER1_LIMIT_I)
Alternative 2:
When constants like FS
truly need to be FP like 16123.4f
, use a rounding function rather than truncation with an integer cast like (uint16_t)
#include <math.h>
if (counter1 == lround(COUNTER1_LIMIT))
Alternative 3:
When constants like FS
truly need to be FP like 16123.4f
, add 0.5 then truncate with an integer cast like (uint16_t)
. The add 0.5 trick works when the value is positive. It fails with a number of values when adding 0.5 is not exact. Yet has the advantage: it can be computed, as in OP's case, at compile time.
if (counter1 == (uint16_t)(COUNTER1_LIMIT + 0.5))