单片机IO位域定义及操作详解及代码编写

1、位域操作单片机IO口,结构清晰,且减少代码运算量(虽然不多哈)。

2、如果8个IO口不是P0/P1/P2/P3等,而是不同的GPIO口组合的8个,那建议使用位域操作。

范例:优先考虑,赋值一次后分别对8个IO单独赋值。

#define LED_ROW1 P2_1
#define LED_ROW1 P2_0
#define LED_ROW3 P0_1
#define LED_ROW4 P0_5
#define LED_ROW5 P2_5
#define LED_ROW6 P3_1
#define LED_ROW7 P3_2
#define LED_ROW8 P1_1
typedef union
{
unsigned char byte;
struct
{
unsigned char bit_8:1;//高8位
unsigned char bit_7:1;
unsigned char bit_6:1;
unsigned char bit_5:1;
unsigned char bit_4:1;
unsigned char bit_3:1;
unsigned char bit_2:1;
unsigned char bit_1:1;//低0位
}bits;
}LED_union_typedef;

LED_union_typedef LED_ROW={0XFF};

void LED_SW(unsigned char value)
{
LED_ROW.byte=value;//赋值

LED_ROW1=LED_ROW.bits.bit_8;
LED_ROW2=LED_ROW.bits.bit_7;
LED_ROW3=LED_ROW.bits.bit_6;
LED_ROW4=LED_ROW.bits.bit_5;
LED_ROW5=LED_ROW.bits.bit_4;
LED_ROW6=LED_ROW.bits.bit_3;
LED_ROW7=LED_ROW.bits.bit_2;
LED_ROW8=LED_ROW.bits.bit_1;
}

范例:不建议,每次运行一下把结果赋给IO

#define LED_ROW1 P2_1
#define LED_ROW1 P2_0
#define LED_ROW3 P0_1
#define LED_ROW4 P0_5
#define LED_ROW5 P2_5
#define LED_ROW6 P3_1
#define LED_ROW7 P3_2
#define LED_ROW8 P1_1

void LED_SW(unsigned char value)
{
LED_ROW1=value&0x01;
LED_ROW2=value&0x02;
LED_ROW3=value&0x04;
LED_ROW4=value&0x08;
LED_ROW5=value&0x10;
LED_ROW6=value&0x20;
LED_ROW7=value&0x40;
LED_ROW8=value&0x80;
}

原创文章,作者:周边游,如若转载,请注明出处:http://www.daxiangjuan.cn/219/.html