2

I made a counter to count pulses:

int count  = 0 ;
.
.
.
setup()
{    
}    

while (count <= 35000)
{    
  digitalWrite(9, HIGH);
  delayMicroseconds(500);
  digitalWrite(9, LOW);

  count = count + 1;
}

But when I try while(count <= 40000), it does not stop counting.

7

int in AVR GCC is 16 bits. All possible int values are less than 32767.

  • 3
    To be precise, the maximum value of int on this platform is 32767. If you add 1 to 32767 you get -32768 which then counts back up to 0, then up to 32767 and so on. – Nick Gammon Dec 4 '17 at 5:22
  • 4
    If you made it unsigned int then the maximum value is 65535 which would work for counting up to 40000. – Nick Gammon Dec 4 '17 at 5:23
2

You have reached the maximum number that an int can represent. That is 32767.

int is a variable type that is made up of 16 bits. It is signed, meaning that it can represent positive and negative numbers.

Out of the 65536 (ie. 2^16) possible numbers from the 16 bits, half of them represent negative numbers and the remaining half represents positive numbers (including zero). Or in other words, -32768 to 32767.

If you don't need negative numbers, then you can change your variable type to unsigned int which will use numbers up to a maximum of 65535. So it becomes:

unsigned int count = 0;
0

But when I try while(count <= 40000), it does not stop counting.

"int" has a range from -32k to +32k-1. so "count <= 40000" will always be true as count is "int".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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