【51单片机零根本-chapter5:模块化编程】

  金牌会员 | 2025-1-9 00:27:08 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 991|帖子 991|积分 2973

模块化编程



将以往main中泛型的代码,放在与main平级的c文件中,在h中引用.
简化main函数


将原来main中的delay抽出
然后将delay放入单独c文件,并单独开一个delay头文件,内里放置函数的声明,相当于收纳delay的c文件内里写的函数的接口.

注意,单个c文件所有用到的变量需要在该文件内里声明或引用,函数也是.
存放头文件的地点修改处,但是一样寻常用不着

预编译


  1. #define AAA
  2. #ifdef AAA
  3. fx//会执行
  4. #endif
  5. #ifndef AAA
  6. gx//不会执行,因为AAA已经定义
  7. #endif
复制代码
以是无论头文件界说什么,一样寻常都会包围语句
fx.h:
  1. #ifndef __FX_H__                //加
  2. #define  __FX_H__
  3. void fx(...)
  4. #endif                //加
复制代码
#include <.h>是安装目录内里找
#include “.h” 是程序目录内里找
可以软件里add new新建文件
也可也外部已有文件add existing



同时在主文件里右键open头文件可以打开则乐成


  1. 模块化编程
  2. main.c``````````````````````````````````
  3. #include <REGX52.H>
  4. #include "Delay.h"
  5. #include "light.h"
  6. void main(){
  7.         while(1){
  8.                 light(1,9);Delay(1);
  9.                 light(2,8);Delay(1);
  10.                 light(3,5);Delay(1);
  11.                 light(6,2);Delay(1);
  12.                 light(7,1);Delay(1);
  13.                 light(8,1);Delay(1);
  14.         }
  15. }
  16. Dalay.c`````````````````````````````````
  17. #include <REGX52.H>
  18. void Delay(unsigned char x)                //@12.000MHz
  19. {
  20.         while(x--){
  21.                 unsigned char i, j;
  22.                 i = 2;
  23.                 j = 239;
  24.                 do
  25.                 {
  26.                         while (--j);
  27.                 } while (--i);
  28.         }
  29. }
  30. Delay.h`````````````````````````````````````````
  31. #ifndef __DELAY_H__
  32. #define __DELAY_H__
  33. void Delay(unsigned char x);
  34. #endif
  35. light.h
  36. #ifndef __LIGHT_H__
  37. #define __LIGHT_H__
  38. void light(unsigned char location,num);
  39. #endif
  40. light.c
  41. #include <REGX52.H>
  42. #include "Delay.h"
  43. unsigned char lednum[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
  44. void light(unsigned char location,num){
  45.         switch(location){
  46.                 case 1:P2_4=1;P2_3=1;P2_2=1; break;
  47.           case 2:P2_4=1;P2_3=1;P2_2=0; break;
  48.                 case 3:P2_4=1;P2_3=0;P2_2=1; break;
  49.                 case 4:P2_4=1;P2_3=0;P2_2=0; break;
  50.                 case 5:P2_4=0;P2_3=1;P2_2=1; break;
  51.                 case 6:P2_4=0;P2_3=1;P2_2=0; break;
  52.                 case 7:P2_4=0;P2_3=0;P2_2=1; break;
  53.                 case 8:P2_4=0;P2_3=0;P2_2=0; break;
  54.         }
  55.         P0=lednum[num];
  56.         Delay(1);
  57.         P0=0x00;
  58. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表