The proper way to do this is to use the on-chip hardware peripheral timers of your MCU. That being said, if you for some reason needs a counter like this you should not use signed types. In fact the default primitive data types of C (int
, long
etc) should never be used in embedded systems - you should be using uintn_t
types from stdint.h
.
Unsigned types in C have a well-defined wrap-around, they cannot overflow. When they reach maximum and you keep adding, they wrap around to zero. This is guaranteed by the language. So the solution you are looking for is simply this:
for(uint32_t i=0; ; i++) // 2nd clause intentionally empty, loop forever
{
/* do stuff */
}