Create sets for 16-bit variable composed of two 8-bit

Asked

Viewed 102 times

1

I wonder if there is any way to create a define for a "variable" in C that has 16 bits called PORTAB, so that writing:

PORTAB = 0xAAFF;

is equivalent to:

PORTA = 0xAA;
PORTB = 0xFF;

Thank you.

2 answers

0

#define PORTA (0xAA)
#define PORTB (0xFF)
#define PORTAB (((PORTA) << 8) | (PORTB))

Or else:

#define JUNTAR_16_BITS(a, b) (((a) << 8) | (b))

#define PORTA (0xAA)
#define PORTB (0xFF)
#define PORTAB JUNTAR_16_BITS(PORTA, PORTB)

0

I suggest you use two macros different, one for reading and one for recording.

Reading:

#define PORTAB ((unsigned short)(((PORTA) << 8) | (PORTB)))

Recording:

#define PORTAB( value ) do{ unsigned short v = value; PORTA = ((unsigned char*)&v)[1]; PORTB = ((unsigned char*)&v)[0]; }while(0)

Example of Use:

#include <stdio.h>

#define PORTAB ((unsigned short)(((PORTA) << 8) | (PORTB)))

#define SET_PORTAB( value ) do{ unsigned short v = value; PORTA = ((unsigned char*)&v)[1]; PORTB = ((unsigned char*)&v)[0]; }while(0)

int main( void )
{
    /* Gravação */

    PORTA = 0xAA;
    PORTB = 0xFF;

    SET_PORTAB( 0xAAFF );

    /* Leitura */

    printf( "PORTA  = 0x%X\n", PORTA );
    printf( "PORTB  = 0x%X\n", PORTB );
    printf( "PORTAB = 0x%X\n", PORTAB );

    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.