[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[avr-gcc-list] Bit-wise structure and unions
From: |
Keith Gudger |
Subject: |
[avr-gcc-list] Bit-wise structure and unions |
Date: |
Tue, 21 Nov 2006 10:40:54 -0800 (PST) |
Below is a program which illustrates the following issue:
When using AVR ports, I would like to define them with bit-wise
structures. This way I can easily access individual bits (or groups of
bits). e.g.:
typedef struct port_reg {
unsigned bit0:1 ;
unsigned bit1:1 ;
unsigned unused:6 ;
} PORT_REG;
However, I cannot assign the 8 bit port value directly to a structure
defined this way. Here is the code and the gcc error:
PORT_REG *pLED_DIR = (PORT_REG *)0x37 ; ///< LED Port DIR REG PORT B
*pLED_DIR = (PORT_REG) 0x03 ;
main.c:27: error: conversion to non-scalar type requested
I can fix this problem by introducing a union:
typedef union {
PORT_REG port_bits ;
uint8_t byte ;
} PORT_UNION ;
PORT_UNION *pLED_DIR = (PORT_UNION *)0x37 ; ///< LED Port DIR REG PORT B
PORT_UNION *pLED_OUT = (PORT_UNION *)0x38 ; ///< LED Port Output PORT B
pLED_DIR->byte = 0x3 ;
But I would rather not have the union. Is there any other way around
this? Thanks.
Keith
(full code follows)
typedef struct port_reg {
unsigned bit0:1 ;
unsigned bit1:1 ;
unsigned unused:6 ;
} PORT_REG;
typedef union {
PORT_REG port_bits ;
uint8_t byte ;
} PORT_UNION ;
int main(void)
{
#ifdef UNION
PORT_UNION *pLED_DIR = (PORT_UNION *)0x37 ; ///< LED Port DIR REG PORTB
PORT_UNION *pLED_OUT = (PORT_UNION *)0x38 ; ///< LED Port Output PORTB
pLED_DIR->byte = 0x3 ;
#else
PORT_REG *pLED_DIR = (PORT_REG *)0x37 ; ///< LED Port DIR REG PORT B
PORT_REG *pLED_OUT = (PORT_REG *)0x38 ; ///< LED Port Output PORT B
*pLED_DIR = 0x03 ;
#endif
while (1)
{
#ifdef UNION
pLED_OUT->port_bits.bit1 ^= 1 ;
#else
pLED_OUT->bit1 ^= 1 ;
#endif
}
return 0;
}