| 给你一个最强的宏定义,不仅可以定义变量(包括I/O)中的单独某一位,而且可以定义多位作为一个整体访问。 先把下面的代码保存为一个头文件:bitwise.h,以后都可以用的。
 
#ifndef __BITWISE_H
#define __BITWISE_H
#ifdef __cplusplus
extern "C" {
#endif
#define _BITFIELD_(_W)        \
    typedef union {           \
        struct {              \
            uint8_t used :_W; \
        };                    \
        uint8_t dummy;        \
    } _bit_0_ ## _W ## _t
#define _BITFIELD1_(_S, _W)   \
    typedef union {           \
        struct {              \
            uint8_t :_S;      \
            uint8_t used :_W; \
        };                    \
        uint8_t dummy;        \
    } _bit_ ## _S ## _ ## _W ## _t
_BITFIELD_(1);
_BITFIELD_(2);
_BITFIELD_(3);
_BITFIELD_(4);
_BITFIELD_(5);
_BITFIELD_(6);
_BITFIELD_(7);
_BITFIELD_(8);
_BITFIELD1_(1, 1);
_BITFIELD1_(1, 2);
_BITFIELD1_(1, 3);
_BITFIELD1_(1, 4);
_BITFIELD1_(1, 5);
_BITFIELD1_(1, 6);
_BITFIELD1_(1, 7);
_BITFIELD1_(2, 1);
_BITFIELD1_(2, 2);
_BITFIELD1_(2, 3);
_BITFIELD1_(2, 4);
_BITFIELD1_(2, 5);
_BITFIELD1_(2, 6);
_BITFIELD1_(3, 1);
_BITFIELD1_(3, 2);
_BITFIELD1_(3, 3);
_BITFIELD1_(3, 4);
_BITFIELD1_(3, 5);
_BITFIELD1_(4, 1);
_BITFIELD1_(4, 2);
_BITFIELD1_(4, 3);
_BITFIELD1_(4, 4);
_BITFIELD1_(5, 1);
_BITFIELD1_(5, 2);
_BITFIELD1_(5, 3);
_BITFIELD1_(6, 1);
_BITFIELD1_(6, 2);
_BITFIELD1_(7, 1);
#define SFR(_P, _S, _W) (*(_bit_ ## _S ## _ ## _W ## _t volatile*)(_SFR_ADDR(_P))).used
#ifdef __cplusplus
}
#endif
#endif
使用方法:
 
 1、在你的程序中包含bitwise.h。
 
 2、定义位变量
 
 在你的程序中需要使用SFR宏定义一个位变量(如同keil c51中位变量首先需要使用sbit定义之后才能访问一样),语法如下:
 #define BITFIELD_VARIABLE SFR(ADDRESS, START_BIT, FIELD_WIDTH)
BITFIELD_VARIABLE: 位变量名称。
 ADDRESS: 包含该位变量的字节所在的地址。
 START_BIT: 位变量开始的位置(LSB)。
 FIELD_WIDTH: 位变量的宽度。
 
 例如:你需要将PORTB0作为位变量访问,变量名为RELAY,由器件的头文件中可知PORTB0位于PORTB的第0位,那么就可得出ADDRESS为PORTB, START_BIT为0,你只使用这一位,那么FIELD_WIDTH就为1,最后定义如下:
 
 #define RELAY SFR(PORTB, 0, 1)
3、访问位变量
 
 如同访问普通变量一样的语法。例如:
 |