Here's where I jump in and preach against the use of naked constants. Use #define <name> <constant> instead.
So instead of
use
Code:
#define STOPPED (127) // pwm value for zero speed
...
motorSpeed = STOPPED;
There are three good reasons for this:
1. It's self-documenting. The macro STOPPED tells the reader what the constant
means.
2. If you use a constant more than once and need to change all instances, you only need to change it in one place, instead of searching around for all the '127's in your code that should be changed. And you know you're gonna miss one!
3. The compiler will catch the error in
Code:
motorSpeed = STOPED;
but will not catch
because both 127 and 122 are valid. But "STOPED" is a symbol presumably unknown to the compiler, and it will halt the build and tell you exactly what is wrong: it doesn't understand "STOPED".
Here's my real-life story on this issue. I worked on a project that processed streaming MPEG video in real time. If the code crashed it meant the TV station would go off the air and lose a lot of money.
A line of code checked for a special value indicating a special mode:
Code:
if ( vbv_delay == 0xFFFF )
{
...
}
This test was performed in several places in my code. The code worked fine for months. One day someone on the project came to me to ask about a crash that looked like it originated in my code. I tracked it down to a typo. One of the tests was
Code:
if ( vbv_delay == 0xFFF )
{
...
}
Oops. The compiler couldn't help me: 0xFFF and 0xFFFF are both valid constant values.
If I had used
Code:
#define VBR_MODE (0xFFFF)
if ( vbv_delay == VBR_MODE )
{
...
}
not only would it have been easier to understand by someone else (and the code is now being maintained by someone else) the compiler would have immediately flagged something like
Code:
#define VBR_MODE (0xFFFF)
if ( vbv_delay == VBR_MOD )
{
...
}
Fortunately we caught this error before we shipped any units, but we were lucky.
The moral: AVOID NAKED CONSTANTS!