01-04-2019 03:33 PM
I made a simple counter that should increment by 1 when when the digital signal is received. However, when I get to 30,000 counts, it starts running backward in the negatives. Any ideas on why it doesn't continue to run indefinitely? Thank you!
Solved! Go to Solution.
01-04-2019 03:52 PM - edited 01-04-2019 04:02 PM
Your datatype is an I16. It has a range of -32,768 to 32,767.
When you start at 0, it will increment by one. When you reach 32,767 and add 1, it effectively rolls over. That bit 15 becomes 1 instead of 0. For a signed integer, the highest order bit is the sign bit, and 2's complement comes into play.
So it will jump from 32,767 to -32,768 and count UP from there which is towards 0/
How high to you want that number to go? Try a 32 bit or 64 bit integer. Do you ever expect to have a negative number? If not, make it an unsigned integer. An unsigned 64 bit integer will allow you to go from 0 to about 1.84e19 on a counter. You don't have any timing functions in your loop so we don't know how fast that loop is running. But if this was on an FPGA running against a 40 MHz clock, it would take about 14,623 years to roll over.
01-04-2019 03:52 PM
It's stored in a I16 which can only hold numbers in the range of -32768 to 32767. When it tries to increment from 32767 to 32768 it can't store that high a number so it wraps around to -32768 instead.
It's not really possible to have a integer that continues "indefinitely" since whatever representation you choose will have a max range.
01-04-2019 03:53 PM - edited 01-04-2019 03:57 PM
I16 has a range of +- 32768. Once you go over 32,768 it should start counting back up from -32,767. Use an unsigned 32 for a much larger range of positive numbers. (Right click the number and select "representation")
01-04-2019 03:54 PM
Lol, I guess we all posted at the same time 😛
01-04-2019 03:59 PM
Yes, this was the issue...thank you all very much for the help!