分文件实现代码优化:
1、把几个模块的代码分别建立成分文件 (.c文件)
2、再把函数进行封装声明。(.h文件)
3、主函数调用时(.h文件)在主文件中用头文件形式展现
要实现两个文件中同时使用,也可以封装为.h形式,在两个文件中头文件形式使用
例如config.h头文件的建立。
注意: 封装的.h文件中函数头要与.c文件头一致,否则会警告。
extern char datas[5];//声明为外部变量,把别的文件中的全局变量拿走使用,
#include "reg52.h"
#include <intrins.h>
#include "delay.h"
#include "uart.h"
#include "LCD1602.h"
#include "DHT11.h"
#include "config.h"
char wendu[13]; //temperature
char shidu[13]; //humidity
extern char datas[5]; //声明为外部变量
void build_datas()
{
shidu[0] = 's';
shidu[1] = 'h';
shidu[2] = 'i';
shidu[3] = 'd';
shidu[4] = 'u';
shidu[5] = ':';
shidu[6] = datas[0]/10 + 0x30; //湿度整数位
shidu[7] = datas[0]%10 + 0x30;
shidu[8] = '.';
shidu[9] = datas[1]/10 + 0x30; //湿度小数位
shidu[10] = datas[1]%10 + 0x30;
shidu[11] = '%';
shidu[12] = '\0';
wendu[0] = 'w';
wendu[1] = 'e';
wendu[2] = 'n';
wendu[3] = 'd';
wendu[4] = 'u';
wendu[5] = ':';
wendu[6] = datas[2]/10 + 0x30; //温度整数位
wendu[7] = datas[2]%10 + 0x30;
wendu[8] = '.';
wendu[9] = datas[3]/10 + 0x30; //温度小数位
wendu[10] = datas[3]%10 + 0x30;
wendu[11] = 'C';
wendu[12] = '\0';
}
void main()
{
Delay1000ms();
UartInit(); //初始化串口
LCD1602_INIT(); //初始化LCD
Delay1000ms();
Delay1000ms();
ledOne = 0; //亮灯
while(1){
Delay1000ms();
Read_Data_From_DHT();
if(datas[2] > 24){ //温度大于24时,风扇启动
fengshan = 0;
}else{
fengshan = 1; //风扇关闭
}
build_datas();
sendString(shidu);
sendString("\r\n");
sendString(wendu);
sendString("\r\n");
LCD1602_showLine(1,2,shidu);
LCD1602_showLine(2,2,wendu);
}
}
extern
可以在一个文件中引用另一个文件中定义的变量或者函数(全局)
表明变量或者函数是定义在其他其他文件中的
例如:extern int a;
显式的说明了a的存储空间是在程序的其他地方分配的,在文件中其他位置或者其他文件中寻找a这个变量。
如果不想让其他.c文件引用本文件中的变量,加上 static 即可
static修饰:局部变量,全局变量,函数