The
result was allocated on stack, and because it wasn't initialized, it is "set" to whatever value was in the stack at that position. When you call a function in a loop, it is common for such uninitialized values to get the same value on each call.
In C, the
bool type is actually an integer type, with zero being false, and all nonzero values true. It can hold more than two values. If you use logical expressions (like
result = (a < b)) the compiler will only store a 0 or a 1, and you can always ensure the value is 0 or 1 by using
!!result (which means not-not-result, or
(result != 0)). Here, the value is uninitialized, and therefore can be anything. (And since in C it really is some integer type, you happen to get 9.)
In that case, here's what I'd use:
Code:
#define SENSORS 12
int limit[SENSORS] = { 0 };
unsigned char deadband[SENSORS] = { 0 };
bool state[SENSORS] = { 0 };
unsigned int i;
for (i = 0; i < SENSORS; i++) {
state[i] = check(state[i], limit[i] - deadband[i]/2, measurement(i), limit[i] + (deadband[i] + 1)/2);
/* Do something with state[i] */
}
In C, when initializing an array, you do not need to specify a value for each member. The compiler will initialize the rest to zeros.
Above,
limit[] is the centerpoint of the deadband. If the deadband is odd, the upper half of the dead range is one larger. If we used
deadband[i]/2 for both, incrementing the deadband by 1 would not do anything; the deadband would always be effectively even (a multiple of 2).
The mathematically correct way would be to use
(deadband[i] - deadband[i]/2) for the upper range, as it evaluates to
deadband[i]/2 if it is even, but to
deadband[i]/2 + 1 if it is odd. However, because it cannot be negative, we can achieve the exact same result with
(deadband[i] + 1)/2, which is much easier for the compilers to optimize (if you are using an 8-bit microcontroller, this might matter a lot).
If you have some sort of user interface to allow the user to control the limit and the deadband separately, this is much more intuitive arrangement, as changing
limit[] moves the range -- and usually changing that is sufficient --, and changing
deadband[] only changes the sensitivity (the total range of the temperature changes allowed).