0
\$\begingroup\$

Need help a simple a 32-Bit counter with reset.

Pseudo code:

int x, value;
int count = 0;

while(count == 0)
{
    x = x + ?;
    osDelay(1000);
    if(x == 2^31 This Also? )
    {
        x = 0;
        break;
    }
}

I want x to count up to 32 bits and then reset with 1 s intervals.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ If you want an exact time you should use a timer not a delay loop. \$\endgroup\$
    – Mike
    Commented Apr 28, 2021 at 6:04
  • \$\begingroup\$ Did you mean you need a timer counting from 0 to 2^31 with 1s period? You'll need 2.147 GHz clock to feed it which I don't think any STM32H7s can generate. \$\endgroup\$
    – Long Pham
    Commented Apr 28, 2021 at 6:07
  • 1
    \$\begingroup\$ Is this a question related to your coursework (homework, exam, lab)? It looks like it would be, and we don't give out solutions to such questions here. You need to show us that you have done a substantial amount of work yourself, then as a specific question. \$\endgroup\$ Commented Apr 28, 2021 at 11:29

1 Answer 1

0
\$\begingroup\$

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 */
}
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.