AVR Notes 6: Excellent C programming style

Publisher:MagicalSerenadeLatest update time:2015-09-16 Source: eefocus Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere
    How can a beginner have a good programming style? I would like to quote a story about a beginner asking a programming master for advice and let the readers understand it for themselves.

    There was a programming master who wrote unstructured programs. A beginner deliberately imitated him and also wrote unstructured programs. When he showed his progress to the master, the master criticized his unstructured program: "What is suitable for a programming master may not be suitable for a beginner. Before going beyond structured, you must understand the way of programming." I personally think that as a beginner, you should lay a solid foundation in programming and not rush for quick success and lose sight of the main goal. I have taken many detours, and I hope that everyone can remember the advice of the programming master like me: "What is suitable for a programming master may not be suitable for a beginner."

    The excellent programming style described in this article is suitable for most languages. The article may mention concepts that you don’t understand very well. It doesn’t matter. Just read on. After using AVR for a month, you will understand everything.

AVR C language excellent programming style

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  .

AVR Notes 6: Excellent C programming style

 

    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 debugging the program. You can call other functions as the function body during the definition of 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 operation Delay1s(5); //delay 5s motor_stop(); //stop Delay1s(5); //delay 5s back_ward(0); //default speed reverse operation 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.

Reference address:AVR Notes 6: Excellent C programming style

Previous article:AVR Notes 7: ATmega16 locked
Next article:AVR Notes 5: .c and .h Nature

Latest Microcontroller Articles
  • 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)
    Since development under LINUX is still quite troublesome, is there a more convenient and simple development method under WINDOWS? The answer is yes. Of course, it is not a development tool like ADS, because it ...
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
  • Learn ARM development(18)
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号