Wednesday, January 24, 2024

Defining F_CPU in Microchip Studio

The macro F_CPU specifies the CPU frequency and is used by libraries such as <delay.h> to calculate the delay based on the frequency of the processor or by UART libraries to calculate baud rate.

Up until now I used to define F_CPU like this:

#define F_CPU    16000000UL

Defining this way will work but it could lead to issues and confusion when you have multiple files that define this macro. The ideal way is to define it in a single place. This could be a Makefile if you are using custom Makefiles or in the IDE project configuration.

Defining F_CPU in Microchip Studio

Open the project properties window in Project -> Properties (Alt+F7) then in the left panel select the Toolchain menu. Next in AVR/GNU C Compiler -> Symbols use the green + button to define a new symbol F_CPU=16000000UL. Of course the F_CPU value depends on your CPU frequency that in this example is 16000000 Hertz or 16MHz. The UL at the end stands for unsigned integer.

Defining F_CPU symbol in Microchip Studio
click to enlarge

That's it. Now all included files in your project will use a single F_CPU value without giving errors such as "F_CPU is not defined", "F_CPU redefined", etc.

Since this method of defining is not as obvious as the first one, it is easy to forged to do it when starting a new project but there is a simple solution for that - using preprocessor conditionals.

#ifndef F_CPU
	#warning	"F_CPU not defined. Define it in project properties."
#elif F_CPU != 16000000
	#warning	"Wrong F_CPU frequency!"

This macro can be placed at the beginning of the main.c file before any type of code. If the F_CPU is not defined it will output a warning. If the F_CPU is defined but is not the value specified in the macro, it will also output a warning. This is also helpful to see what the CPU frequency is and to ensure that the defined value in project properties is correct.

No comments:

Post a Comment