Arduino Uno cannot count higher than 32767?

I have a sketch that count the number of times a reed switch closes. After sometime it began to count backward when it reaches 32767. Is there a way to make it count higher?

Thank you.

Please post your code.
It sounds like you are using a signed integer 16 bit number and it's rolling over.
You can increase it by selecting a different data type for the variable. A uin32_t variable will allow you to count to 4,294,967,295.

see the section Data Types in the Arduino Reference - Arduino Reference

Data Types

byte
char
double
float
int
long
short
unsigned char
unsigned int
unsigned long
word

pick the type that suits your needs

Thank you, I changed my variable from "int" to "unsigned long" and I will wait to see if it goes higher. But that was probably the problem. When I saw 32767 it should have ring a bell in my head.

I don’t trust the ringing in my head as it is just Tinnitus.
:frowning:

1 Like

the doc does not tell the whole story, you can get even larger with unsigned long long (but print does not know how to print them)

void setup() {
  Serial.begin(115200); Serial.println();
  Serial.print("Number of bytes for unsigned int : "); Serial.println(sizeof(unsigned int));
  Serial.print("Number of bytes for unsigned long : "); Serial.println(sizeof(unsigned long ));
  Serial.print("Number of bytes for unsigned long long : "); Serial.println(sizeof(unsigned long long));
}

void loop() {}
Number of bytes for unsigned int : 2
Number of bytes for unsigned long : 4
Number of bytes for unsigned long long : 8

➜ 8 bytes

void setup()
{
  Serial.begin(9600);
  unsigned long long int  x = 0xFFFFFFFFFFFFFFFF;//18,446,744,073,709,551,615
  byte myArray[20];
  for (int i = 0; i < 20; i++)
  {
    myArray[i] = x % 10;
    x = x / 10;
  }
  for(int i = 19; i>=0; i--)
  {
    Serial.print(myArray[i], DEC);//shows: 18446744073709551615
  }

}

void loop() 
{
  
}

Data types supported my Standard Arduino (UNO/NANO/MEGA)