Friday, March 15, 2024

Defining SYSCLK or F_CPU in Simplicity Studio

The macro SYSCLK or 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    24500000UL

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 SYSCLK / F_CPU in Simplicity Studio

Open the project properties window in Project -> Properties (Alt+Enter) then in the left panel select the C/C++ Build -> Settings menu. Then in Tool Settings - > Keil 8051 Compiler -> Symbols use the green + button to define a new symbol SYSCLK=2450000UL. Of course the SYSCLK value depends on your CPU frequency that in this example is 24500000 Hertz or 24.5MHz. The UL at the end stands for unsigned integer.

Defining SYSCLK symbol in Simplicity Studio 01

Defining SYSCLK symbol in Simplicity Studio 02

That's it. Now all included files in your project will use a single SYSCLK value without giving errors such as "SYSCLK is not defined", "SYSCLK 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 SYSCLK
	#warning	"SYSCLK not defined. Define it in project properties."
#elif SYSCLK != 24500000
	#warning	"Wrong SYSCLK frequency!"
#endif

This macro can be placed at the beginning of the main.c file before any type of code. If the SYSCLK is not defined it will output a warning. If SYSCLK 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