AVR筆記6:C語(yǔ)言?xún)?yōu)秀編程風(fēng)格
AVR c語(yǔ)言?xún)?yōu)秀編程風(fēng)格
文件結構
這個(gè)工程中有8個(gè)文件,一個(gè)說(shuō)明文件,如下圖:下載程序例子avrvi.com/down.php?file=examples/motor_control.rar">電機控制案例。
- 所有.c文件都包含了config.h文件。如: #include "config.h"
- 在config.h 中有如下代碼:
#include "delay.h" #include "device_init.h" #include "motor.h"
- 這樣做就不容易出現錯誤的包含關(guān)系,為了預防萬(wàn)一,我們還引入了宏定義與預編譯。如下:
#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 第一次包含本文件的時(shí)候正確編譯,并且#define _UNIT_H__ 1,第二次包含本文件#ifndef _UNIT_H__就不再成立,跳過(guò)文件。 預編譯還有更多的用途,比如可以根據不同的值編譯不同的語(yǔ)句,如下: //#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 - #include
與 #include "filename" 的區別 :前者是包含系統目錄include下 的文件,后者是包含程序目錄下的文件。
- 好的:
Delay100us();
不好的:Yanshi(); - 好的:
init_devices();
不好的:Chengxuchushihua(); - 好的:
int temp;
不好的:int dd;
- 首先在模塊化程序的.h文件中定義extern
//端口初始化 extern void port_init(void); //T2初始化 void timer2_init(void); //各種參數初始化 extern void init_devices(void);
- 模塊化程序的.c文件中定義函數,不要在模塊化的程序中調用程序,及不要出現向timer2_init();這樣函數的使用,因為你以后不知道你到底什么地方調用了函數,導致程序調試難度增加??梢栽诙x函數的過(guò)程中調用其他函數作為函數體。
// PWM頻率 = 系統時(shí)鐘頻率/(分頻系數*2*計數器上限值)) void timer2_init(void) { TCCR2 = 0x00; //stop TCNT2= 0x01; //set count OCR2 = 0x66; //set compare TCCR2 = (1<
- 在少數幾個(gè)文件中調用函數,在main.c中調用大部分函數,在interupts.c中根據不同的中斷調用服務(wù)函數。
void main(void) { //初始工作 init_devices(); while(1) { for_ward(0); //默認速度運轉 正 Delay1s(5); //延時(shí)5s motor_stop(); //停止 Delay1s(5); //延時(shí)5s back_ward(0); //默認速度運轉 反 Delay1s(5); //延時(shí)5s speed_add(20); //加速 Delay1s(5); //延時(shí)5s speed_subtract(20); //減速 Delay1s(5); //延時(shí)5s } }
- 一是用得非常多的命令或語(yǔ)句,利用宏將其簡(jiǎn)化。
#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;
- 二是利用宏定義方便的進(jìn)行硬件接口操作,再程序需要修改時(shí),只需要修改宏定義即可,而不需要滿(mǎn)篇去找命令行,進(jìn)行修改。
//PD4,PD5 電機方向控制如果更改管腳控制電機方向,更改PORTD |= 0x10即可。#define moto_en1 PORTD |= 0x10 #define moto_en2 PORTD |= 0x20 #define moto_uen1 PORTD &=~ 0x10 #define moto_uen2 PORTD &=~ 0x20 //啟動(dòng)TC2定時(shí)比較和溢出 #define TC2_EN TIMSK |= (<<1OCIE2)|(1<
- 在比較特殊的函數使用或者命令調用的地方加單行注釋。使用方法為:
Tbuf_putchar(c,RTbuf); // 將數據加入到發(fā)送緩沖區并開(kāi)中斷 extern void Delay1s(uint16 n); // n <= 6 ,when n==7, it is 1.
- 在模塊化的函數中使用詳細段落注釋?zhuān)?/li>
- 在文件頭上加文件名,文件用途,作者,日期等信息。
評論