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.
3 Answers 3
int
in AVR GCC is 16 bits. All possible int
values are less than 32767.
-
3To 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.2017年12月04日 05:22:21 +00:00Commented Dec 4, 2017 at 5:22 -
4If you made it
unsigned int
then the maximum value is 65535 which would work for counting up to 40000.2017年12月04日 05:23:09 +00:00Commented Dec 4, 2017 at 5:23
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;
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".