FOR loop incorrect behavior ATmega4809 Curiosity Nano

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

AS - 1931,  ATmega_DFP = 1.3.300, default installed toolchain

 

This "for loop" prints the correct values on the 1st pass,(beginning at 112) but subsequent passes begin at 0.

 

	prstr3("M4809fortest\r\n");
	knt = F_CPU;
	ultoa (knt,String,10);
	strcat(String,"\r\n");
	prstr3(String);
	_delay_ms(200);
	while (1) 
    {
		for (uint8_t ii = 112; ii < 255 ; ii = ii + 16)
		{
			TCB0.CCMPH = ii;
			itoa(ii,String,10);
			strcat(String,"\r\n");
			prstr3(String);
			_delay_ms(1000);
		}
	}
}

 

This topic has a solution.
Last Edited: Mon. Dec 24, 2018 - 10:38 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Offhand I don't see anything incorrect.  I would try two things:

 

1) Don't modify ii in the loop (so it will always stay at 112).  Does it still print 0 after the first time through?

 

2) Remove the for loop and unroll three or four iterations.  Do inline code for ii = 112, then add 16 and repeat the same code again, and then again and again.

This reply has been marked as the solution. 
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Um...  The loop never finishes "the first time through."

ii becomes 240, which is less than 255.  Adding 16 to that gives you 0, which is still less than 255.  You never hit 255 itself, which is the only uint8_t value that will not match the "ii < 255" continuation condition.

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Because the index ii is unsigned, when jumping by 16 the index goes from 240 to 256 = 0.  Thus it is never < 255 and the for loop never terminates.

 

Works correctly when the ending value is set to 240.

 

	while (1) 
    {
		for (uint8_t ii = 112; ii < 240 ; ii = ii + 16)
		{
			TCB0.CCMPH = ii;
			utoa(ii,String,10);
			strcat(String,"\r\n");
			prstr3(String);
			_delay_ms(1000);
		}
	}

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Ah, I misunderstood.  I read it that it printed 112 but then started printing 0s, so I didn't even look at the loop ending condition.