File Structure
Modular programs should have a good program structure. AVR C language programs have two types of user files, .c program files and .h header files. During the program writing process, the .c file needs to include the .h header file. Beginners often have problems with repeated inclusion or header file inclusion errors. I was often worried about this error at the time. Below I will use the motor drive routine I wrote to illustrate to you the excellent programming file structure.
There are 8 files and one description file in this project, as shown below: Download program example motor control case .
The number of files in the programs I wrote is basically an even number, because each structured function definition .c file will correspond to a .h file. main.c corresponds to config.h. Let's take a look at the inclusion relationship of each file. Let's take a look at the inclusion relationship and content of these files: [Recommended file inclusion order and relationship]
All .c files include the config.h file. For example: #include "config.h"
In config.h there is the following code:
#include "delay.h" #include "device_init.h" #include "motor.h"
This makes it less likely that incorrect inclusion relationships will occur. To prevent this, we also introduce macro definitions and precompilation. As follows:
#ifndef _UNIT_H__ #define _UNIT_H__ 1 //100us extern void Delay100us(uint8 n); //1s extern void Delay1s(uint16 n); // n <= 6 ,when n==7, it is 1. //1ms extern void Delay1ms(uint16 n); #endif The first time this file is included, it compiles correctly and #define _UNIT_H__ 1 is set. The second time this file is included, #ifndef _UNIT_H__ is no longer valid and the file is skipped. Precompilation has more uses, such as compiling different statements according to different values, as follows: //#pragma REGPARMS #if CPU_TYPE == M128 #include #endif #if CPU_TYPE == M64 #include #endif #if CPU_TYPE == M32 #include #endif #if CPU_TYPE == M16 #include #endif #if CPU_TYPE == M8 #include #endif
The difference between #include and #include "filename": the former includes files under the system directory include, while the latter includes files under the program directory.
Variable names and function names
Variable and function names should be as short as possible, as long as needed, and meaningful. You can use underscores or a combination of uppercase and lowercase to form variable and function names. The following compares good and bad naming methods:
Good: Delay100us();
Bad: Yanshi();Good: init_devices();
Bad: Chengxuchushihua();Good: int temp;
Bad: int dd;
External calls
First define extern in the .h file of the modular program
//Port initialization extern void port_init(void); //T2 initialization void timer2_init(void); //Various parameter initialization extern void init_devices(void);
Define functions in the .c file of a modular program. Do not call programs in modular programs, and do not use functions like timer2_init(); because you will not know where you called the function later, which will increase the difficulty of program debugging. You can call other functions as the function body during the process of defining a function.
// PWM frequency = system clock frequency / (division coefficient * 2 * counter upper limit)) void timer2_init(void) { TCCR2 = 0x00; //stop TCNT2= 0x01; //set count OCR2 = 0x66; //set compare TCCR2 = (1<
Call functions in a few files, most of the functions are called in main.c, and service functions are called according to different interrupts in interupts.c.
void main(void) { //initial work init_devices(); while(1) { for_ward(0); //default speed forward Delay1s(5); //delay 5s motor_stop(); //stop Delay1s(5); //delay 5s back_ward(0); //default speed reverse Delay1s(5); //delay 5s speed_add(20); //accelerate Delay1s(5); //delay 5s speed_subtract(20); //decelerate Delay1s(5); //delay 5s } }
Macro Definition
Macro definitions are mainly used in two places:
One is to use macros to simplify frequently used commands or statements.
#ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #ifndef NULL #define NULL 0 #endif #define MIN(a,b) ((ab)?(a):(b)) #define ABS(x) ((x>)?(x):(-x)) typedef unsigned char uint8; typedef signed char int8; typedef unsigned int uint16; typedef signed int int16; typedef unsigned long uint32; typedef signed long int32;
The second is to use macro definitions to facilitate hardware interface operations. When the program needs to be modified, you only need to modify the macro definitions, without having to look for command lines throughout the program to make modifications.
//PD4,PD5 motor direction control If you change the pin to control the motor direction, just change PORTD |= 0x10. #define moto_en1 PORTD |= 0x10 #define moto_en2 PORTD |= 0x20 #define moto_uen1 PORTD &=~ 0x10 #define moto_uen2 PORTD &=~ 0x20 //Enable TC2 timing comparison and overflow #define TC2_EN TIMSK |= (<<1OCIE2)|(1<
About Annotations
In order to increase the readability of the program, make it easier for collaborators to read the program, or enable the program author to understand the program after a period of time, we need to write comments in the program.
Add a single-line comment where a special function is used or a command is called. The usage is:
Tbuf_putchar(c,RTbuf); // Add data to the transmit buffer and enable interrupt extern void Delay1s(uint16 n); // n <= 6 ,when n==7, it is 1.
Use detailed paragraph comments in modular functions:
Add file name, file purpose, author, date and other information to the file header.
Be clear that comments are for easy reading and to enhance the readability of the program. Don't put the cart before the horse and add comments to a very simple program that everyone can understand. Don't let comments overwhelm your program structure. For functions, variables, etc., try to use the method of self-commenting the file name, and the meaning can be understood through the file name.
This article is over, and the beginner tutorial is also over. I hope our tutorial can help you easily enter the world of AVR.
Previous article:Detailed explanation of atmega16L serial port
Next article:AVR software operation library functions
Recommended ReadingLatest update time:2024-11-16 23:48
- Popular Resources
- Popular amplifiers
- Principles and Applications of Single Chip Microcomputers 3rd Edition (Zhang Yigang)
- Metronom Real-Time Operating System RTOS for AVR microcontrollers
- Learn C language for AVR microcontrollers easily (with video tutorial) (Yan Yu, Li Jia, Qin Wenhai)
- ATmega16 MCU C language programming classic example (Chen Zhongping)
Professor at Beihang University, dedicated to promoting microcontrollers and embedded systems for over 20 years.
- Innolux's intelligent steer-by-wire solution makes cars smarter and safer
- 8051 MCU - Parity Check
- How to efficiently balance the sensitivity of tactile sensing interfaces
- What should I do if the servo motor shakes? What causes the servo motor to shake quickly?
- 【Brushless Motor】Analysis of three-phase BLDC motor and sharing of two popular development boards
- Midea Industrial Technology's subsidiaries Clou Electronics and Hekang New Energy jointly appeared at the Munich Battery Energy Storage Exhibition and Solar Energy Exhibition
- Guoxin Sichen | Application of ferroelectric memory PB85RS2MC in power battery management, with a capacity of 2M
- Analysis of common faults of frequency converter
- In a head-on competition with Qualcomm, what kind of cockpit products has Intel come up with?
- Dalian Rongke's all-vanadium liquid flow battery energy storage equipment industrialization project has entered the sprint stage before production
- Allegro MicroSystems Introduces Advanced Magnetic and Inductive Position Sensing Solutions at Electronica 2024
- Car key in the left hand, liveness detection radar in the right hand, UWB is imperative for cars!
- After a decade of rapid development, domestic CIS has entered the market
- Aegis Dagger Battery + Thor EM-i Super Hybrid, Geely New Energy has thrown out two "king bombs"
- A brief discussion on functional safety - fault, error, and failure
- In the smart car 2.0 cycle, these core industry chains are facing major opportunities!
- The United States and Japan are developing new batteries. CATL faces challenges? How should China's new energy battery industry respond?
- Murata launches high-precision 6-axis inertial sensor for automobiles
- Ford patents pre-charge alarm to help save costs and respond to emergencies
- New real-time microcontroller system from Texas Instruments enables smarter processing in automotive and industrial applications
- 【AT-START-F425 Review】Bootloader -USART&USB Operation Process
- Timer
- How to understand switching AC-DC conversion in power supplies in a simple and easy way
- TDS water quality testing
- Download any of them to get a gift | ADI [Lithium battery solutions, reference circuit collection]
- One week evaluation information delivered~
- msp430g2331 ds1302 clock module
- [RVB2601 Creative Application Development] Dynamically load the wiring method of MBRE LED color screen ILI9341 TFT
- MSP430F5438A serial port
- Making a CPU out of a bunch of switches?