3

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.

per1234
4,2782 gold badges23 silver badges43 bronze badges
asked Dec 3, 2017 at 23:42

3 Answers 3

7

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

Juraj
18.3k4 gold badges31 silver badges49 bronze badges
answered Dec 3, 2017 at 23:44
2
  • 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. Commented Dec 4, 2017 at 5:22
  • 4
    If you made it unsigned int then the maximum value is 65535 which would work for counting up to 40000. Commented Dec 4, 2017 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;
answered Dec 5, 2017 at 1:08
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".

answered Dec 5, 2017 at 0:51
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.