AVR C language excellent programming style

Publisher:tnzph488Latest update time:2017-11-20 Source: eefocusKeywords:AVR Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

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  .

File Structure

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:

  1. Good: Delay100us();
    Bad: Yanshi();

  2. Good: init_devices();
    Bad: Chengxuchushihua();

  3. Good: int temp;
    Bad: int dd;

External calls

  1. 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);
  2. 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<
  3. 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:

  1. 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;
  2. 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.

  1. 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.
  2. Use detailed paragraph comments in modular functions:

  3. 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.


Keywords:AVR Reference address:AVR C language excellent programming style

Previous article:Detailed explanation of atmega16L serial port
Next article:AVR software operation library functions

Recommended ReadingLatest update time:2024-11-16 23:48

Circuit diagram and programming example of the interface between AVR microcontroller and CF card
1. The content described in this article is to read and write CF cards through 8051 microcontrollers. 2. The operation mode of CF cards is similar to the operation mode of computer hard disks. There are also two ways to address sectors: physical addressing (CHS) and logical addressing (LBA). Physical addressing uses c
[Microcontroller]
Circuit diagram and programming example of the interface between AVR microcontroller and CF card
Generation and burning of AVR ELF files
Usually AVR chips include flash, eeprom, fuse, lockbits, user signature and other non-volatile contents that need to be burned into the chip during programming. Among them, the fuse part can only be rewritten by an external programmer, and the application itself cannot be changed. During ISP burning, users want to c
[Microcontroller]
Generation and burning of AVR ELF files
Design of SD card reading platform based on AVR microcontroller and serial port
O Introduction SD card (secure digital memory card) is a new generation memory device based on semiconductor flash memory. It is widely used in portable devices such as digital cameras, personal digital assistants (PDAs) and multimedia players. SD card was jointly developed by Panasonic, Toshiba and SanDisk
[Microcontroller]
Design of SD card reading platform based on AVR microcontroller and serial port
Embedded Learning Notes 18 - Fuse Bit Setting of AVR MCU
1. Introduction to fuse bits:     A fuse bit state of "1" indicates unprogrammed, and a fuse bit state of "0" indicates programmed, because the fuse bits are defined in the AVR device manual using programmed and unprogrammed. The fuse bits of the AVR microcontroller can be programmed multiple times. After the
[Microcontroller]
Embedded Learning Notes 18 - Fuse Bit Setting of AVR MCU
Drug (capsule) packaging detection and control system
0 Introduction The pharmaceutical capsules produced by Shanghai Huada Group Huaai Food Co., Ltd. are exported to Japan. The packaging specifications of the exported medicines are 10 small bags in a box, and each small bag contains three capsules. However, during the production process, due to the packaging
[Industrial Control]
AVR Notes 5: .c and .h Nature
       .c and .h are both text files, and I also use .r to indicate a private .h. If you like, you can use any text format. I agree with your point of view. As for the difference, I think there is still a little difference. For example, for ICC, under project compilation, the compiler can only see the .c file, while th
[Microcontroller]
AVR series PWM test
The class has already started, but I haven't finished the summary yet. I'm not in a hurry. They say that slow work makes fine work, but I don't know if mine can be considered fine work. I'll just comfort myself and treat it as such. Today I've sorted out the PWM function test of the timer. I won't say much, let's cont
[Microcontroller]
SPWM Program for AVR Microcontroller
#include  //There are only SPWM-related programs in the program now, and other programs have been deleted #include #pragma interrupt_handler T0:17 //Timer 0 overflow interrupt vector unsigned int SPWM_OCR1A ={493,492,491,490,489,488,487,486,485,484,                               483,482,481,479,478,477,476,475
[Microcontroller]
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号