新闻中心

EEPW首页>嵌入式系统>设计应用> 联合体union在单片机位定义时的妙用

联合体union在单片机位定义时的妙用

作者: 时间:2016-11-28 来源:网络 收藏
在51系列单片机开发中,我们经常喜欢用位定义,对端口某位进行操作,也可以用来做为标志。在开发msp430avrarm等单片机时,就不能再使用位定义了。因此给我们带来很多不变,这里介绍一种使用union联合同样也能实现位操作。

这里以MSP430为例,其他单片机类似。

本文引用地址://m.amcfsurvey.com/article/201611/322589.htm

1.用联合体做位标志

__no_initvolatile union {
uint8 temp;
struct
{
uint8bit0:1;
uint8bit1:1;
uint8bit2:1;
uint8bit3:1;
uint8bit4:1;
uint8bit5:1;
uint8bit6:1;
uint8bit7:1;
}temp_bit;
}var;

#definea_flagvar.temp_bit.bit0;

定义了上面的联合体,我们就可以对a_flag进行位操作,进行读写,置位。

2.用联合体定义端口或者寄存器

__no_init volatile
union
{
unsigned char IOPORT;
struct
{
unsigned char Way: 1;
unsigned char Out: 1;
};
} @ 8;

void Test(void)
{
IOPORT = 0;
Way = 1;
Out = 1;
}



评论


技术专区

关闭