Real noob - F_CPU

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

Whilst (self-declared) being reasonable at ASM, I'm forcing myself to learn C and have much (all) to learn.

So in this code (based on a smiley workshop), I can change F_CPU to anything from 80000000l to 1l and my LEDs change state at exactly the same rate.

Why's that then?

#include 

// The last character is a lower case "˜L' not a 1 (one)
#define F_CPU 20000000l
#include 

int main (void)
{
	int i = 0;
	int j = 0;

	// set PORTB for output
	DDRD = 0xFF;

	while(1) {
		for(i = 1; i < 128; i = i*2)
		{
			PORTD = i;
			for(j = 1; j < 30; j++) {
				_delay_loop_2(65535);
			}
		}
		for(i = 128; i > 1; i -= i/2)
		{
			PORTD = i;
			for(j = 1; j < 30; j++) {
				_delay_loop_2(65535);
			}
		}
	}

	return 1;
}
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Think for a moment about the routines being called.
They are "loops", and are not based on any time unit.
So altering the F_CPU value will not change anything. The code will still be performing the same numbers of loops and the CPU is still running at the same clock rate.

Now if you call the other functions that are time based
like _delay_ms() or _delay_us() then those have to convert wall clock time to a number of loops and to do that they have to know the amount of time each loop will take and to know that they have to know the speed of the CPU.

So only the wall clock time based functions will change in duration when you alter F_CPU.

If you don't want or need to time based functions simply include instead and then you won't have to define F_CPU.

see these two links in the user manual:
http://www.nongnu.org/avr-libc/user-manual/group__util__delay.html

http://www.nongnu.org/avr-libc/user-manual/group__util__delay__basic.html

--- bill

Last Edited: Fri. Feb 26, 2010 - 10:10 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Ok - got it now. Ta :D