Bit access

Technical Note 25083






11/2/2015 1:46 PM


This Technial Note covers different aspects of accessing bits, when using IAR Embedded Workbench for AVR.


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 (for example P3.2) which is an extension to the ISO/ANSI C langauge. That syntax is not supported by IAR C/C++ Compiler for AVR.

Various suggestions

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 enough 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:

#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 IAR C/C++ Compiler for AVR 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.

All product names are trademarks or registered trademarks of their respective owners

We do no longer support Internet Explorer. To get the best experience of, we recommend upgrading to a modern browser such as Chrome or Edge.