主要内容:
模块化编程
enum(枚举)
模块化编程
模块化编程简单来说就是将一段代码封装成一个易于调用的函数
注意点:通用性可读性
例如:以下为一个“封装”好的函数,写在主函数后
//函数功能:任意的一个引脚输出"高/低"电平 (通用性,可读性)
//port:(0~3)表示的是P0~P3的端口
//pin:(0~7)表示的是0~7的引脚
//volt:(0~1)表示的是"高/低"电平
void IO_Out(Port_x port,Pin_x pin,unsigned char volt)
{
switch(port)
{
case 0: if(volt==0) //输出低电平
{
P0 &= ~(0x01<<pin);
}
else if(volt==1) //输出高电平
{
P0 |= 0x01<<pin;
}
break;
case 1: if(volt==0) //输出低电平
{
P1 &= ~(0x01<<pin);
}
else if(volt==1) //输出高电平
{
P1 |= 0x01<<pin;
}
break;
case 2: if(volt==0) //输出低电平
{
P2 &= ~(0x01<<pin);
}
else if(volt==1) //输出高电平
{
P2 |= 0x01<<pin;
}
break;
case 3: if(volt==0) //输出低电平
{
P3 &= ~(0x01<<pin);
}
else if(volt==1) //输出高电平
{
P3 |= 0x01<<pin;
}
break;
}
}
用法举例(部分):
void IO_Out(Port_x port,Pin_x pin,Volt_x volt);//声明
void main()
{
while(1) //后台服务程序(操作系统)
{
IO_Out(Port3,Pin0,Volt0);//将P30口赋予低电平
}
}
enum(枚举)
以上函数中的Port_x,Pin_x,Volt_x,均需在声明之前进行定义,【此时的Port_x,Pin_x,Volt_x,为枚举类型而非枚举变量】
//枚举型
typedef enum
{
Port0,Port1,Port2,Port3
}Port_x;
typedef enum
{
Pin0,Pin1,Pin2,Pin3,Pin4,Pin5,Pin6,Pin7
}Pin_x;
typedef enum
{
Volt0,Volt1
}Volt_x;
枚举的作用:约束用户输入的参数
枚举语法定义格式:
enum 枚举名 {枚举元素1,枚举元素2,……};
如果不用枚举,定义 Port0,Port1,Port2,Port3则需要
#define Port0 0
#define Port1 1
#define Port2 2
#define Port3 3
而使用枚举则可以写成
enum PORT
{
Port0,Port1,Port2,Port3
};
第一个枚举成员的默认值为整型的 0,后续枚举成员的值在前一个成员上加 1。
枚举变量的定义
1.先定义枚举类型再定义枚举变量
enum PORT
{
Port0,Port1,Port2,Port3
};
enum PORT Port_x;
2.定义枚举类型的同时定义枚举变量
enum PORT
{
Port0,Port1,Port2,Port3
}Port_x;
3.省略枚举名称,直接定义变量
enum
{
Port0,Port1,Port2,Port3
}Port_x;
而在此处中
因为有typedef,所以将Port_x定义成了枚举类型而非枚举变量
全部代码:
#include "regx52.h"
//枚举型
typedef enum
{
Port0,Port1,Port2,Port3
}Port_x;
typedef enum
{
Pin0,Pin1,Pin2,Pin3,Pin4,Pin5,Pin6,Pin7
}Pin_x;
typedef enum
{
Volt0,Volt1
}Volt_x;
void IO_Out(Port_x port,Pin_x pin,Volt_x volt);
void main()
{
while(1) //后台服务程序(操作系统)
{
IO_Out(Port3,Pin0,Volt0);
}
}
//函数功能:任意的一个引脚输出"高/低"电平 (通用性,可读性)
//port:(0~3)表示的是P0~P3的端口
//pin:(0~7)表示的是0~7的引脚
//volt:(0~1)表示的是"高/低"电平
void IO_Out(Port_x port,Pin_x pin,Volt_x volt)
{
switch(port)
{
case 0: if(volt==0) //输出低电平
{
P0 &= ~(0x01<<pin);
}
else if(volt==1) //输出高电平
{
P0 |= 0x01<<pin;
}
break;
case 1: if(volt==0) //输出低电平
{
P1 &= ~(0x01<<pin);
}
else if(volt==1) //输出高电平
{
P1 |= 0x01<<pin;
}
break;
case 2: if(volt==0) //输出低电平
{
P2 &= ~(0x01<<pin);
}
else if(volt==1) //输出高电平
{
P2 |= 0x01<<pin;
}
break;
case 3: if(volt==0) //输出低电平
{
P3 &= ~(0x01<<pin);
}
else if(volt==1) //输出高电平
{
P3 |= 0x01<<pin;
}
break;
}
}
仿真结果