原文地址:http://supp.iar.com/Support/?note=25083
EW targets: | AVR |
EW component: | C/C++ compiler |
Keywords: | bit, bit access, bitfield, bitfield struct |
Last update: | November 14, 2002 |
Many Special Function Registers (SFRs) contain single bits that one want to set, clear or test. This technical note gives some examples how it can be done.
If you are used to compilers for the 8051 for example, you may be familiar with the dot-bit-number syntax (i.e. P3.2) which is an extension to the ISO/ANSI C langauge that is not supported by ICCAVR.
Instead, in ISO/ANSI C you can access a bit using ordinary C expressions:
P3 &= ~(1 << 2); /* clear a bit */P3 |= (1 << 2); /* set a bit */
The compiler is smart enought to understand what you are doing and will use bit instructions when possible.
If you need to access bits that have symbolic names, you can use the bit names that can be found in the io<chip>.h header file. As an example, the 8535 has a GIMSK register that has a bit called INT1 which can set in the following way:
GIMSK |= (1 << INT1);
You need to define the symbol ENABLE_BIT_DEFINITIONS to enable the bit name definitions at the end of the io8535.h header file. This can be done in the following way:
#define ENABLE_BIT_DEFINITIONS#include <io8535.h>
You can also avoid the define in the code and do it from the build environment instead.
The SFR_?() macro used for defining the SFR symbols in the I/O header file also defines bit symbols, which allow you to write:
GIMSK_Bit2 = 0;
The following comment has been added in the header files starting with the 2.28A release of ICCAVR to clearify this:
/***************************************************** * An example how the macro's below expand to. * SFR_B(AVR, 0x1F) Expands to: * __io union { * unsigned char AVR;//The sfrb as 1 byte * struct { //The sfrb as 8 bits * unsigned char AVR_Bit0:1, * AVR_Bit1:1, * AVR_Bit2:1, * AVR_Bit3:1, * AVR_Bit4:1, * AVR_Bit5:1, * AVR_Bit6:1, * AVR_Bit7:1; * }; * } @ 0x1F; * To set bit 5 of AVR you can do like this: * AVR |= (1<<5); * or like this: * AVR_Bit5 = 1; ****************************************************/
The symbol GIMSK_Bit2 is really a anonymous one bit bitfield. The anonymous part is a language extension, bitfields are part of the ISO/ANSI C language.
简单说下以上内容要点
如果要使用bit位定义功能,那么只需要宏定义#define ENABLE_BIT_DEFINITIONS,比如AVR的端口D即PORTD想进行位定义,那么可以这么写#define ENABLE_BIT_DEFINITIONS PORTD_Bit3=0;//千万注意bit上面的B要大写,当然除了这个方
法以外,还有一种更好的办法,如下图所示
联系客服