A total noob question

Status
Not open for further replies.
Hi everybody,

I've just starting learning to use my Teensy 2.0++, and I've stumbled in something that appears to be very strange for a total noob like me.

I've written and run the following simple code that counts from 0x0000 to 0xFFFF, and sends the value in hex notation to the serial port.

------------

word i;

void setup(){

Serial.begin(9600);

Serial.println("Start counting !");

for (i = 0; i <= 0xFFFF; i++) {
Serial.println(i,HEX);
if (i == 0xFFFF) {
Serial.println("FFFF reached !");
}
}

Serial.println("Count finished!");

}

void loop()
{
}

------------

Looking at the serial monitor in the Arduino IDE, when I run this code, the setup() routine, that I thought would be run only once, is instead executed repeatedly, and the line that prints "Count finished!" is never executed, and appears to be always skipped.

Why is that ?

It looks like the Teensy is being reset at the end of the for loop.

How can I make the program do something after the first for loop ?

Thanks in advance for any help.
 
Last edited:
The issue is that you will never exit your for loop:
That is
Code:
word i;
for (i = 0; i <= 0xFFFF; i++) {
...
A word on an Arduino (Teensy 2) is 16 bits long, so it can hold values from 0-65535 (0-0xffff).
Now suppose in your loop i is equal to 0xffff, the loop continues. Now you increment i and as
the variable is only 16 bits long i is now 0, which is less than 65536, so you will never exit.

Hope that helps
Kurt
 
is a type "word" signed or unsigned?
Many prefer to use the standardized type names:
int // machine dependent size
int16_t // always 16 bit signed
uint16_t // always 16 bit unsigned
int32_t
uint32_t // often used where signed arithmetic isn't applicable

and so on

I recall that 'word' is an old Intel CPU notion
 
word/byte types have been around for a long time, but are different on different platforms.
Both of these are unsigned.

If you look at Arduino reference help files, word is shown to be 16 bit unsigned integer. However warning on Teensy 3.1 it is 32 bit unsigned. I had to fix my code in a few places for this when converting to run on Teensy 3.1.

Kurt
 
Status
Not open for further replies.
Back
Top