avr-gcc-list
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [avr-gcc-list] efficiency of assigning bits


From: Dave Hansen
Subject: Re: [avr-gcc-list] efficiency of assigning bits
Date: Fri, 18 Mar 2005 16:23:58 -0500

From: Ned Konz <address@hidden>
[...]
Even better, use higher-level constructs like inline functions (better than
macros, because they're type-safe and can do more). In this case, of course,
it would be easy to do with a macro.

/* in a header file */

const uint8_t STATUS_LED = 3;

static inline
void turnLedOn(void)
{
 PORTA |= _BV(STATUS_LED);
}

/* in your main C source */

#include "myIODefinitions.h"

...
 turnLedOn();
...

I know the preprocessor is somewhat out of style these days, but consider the scheme I use:

// Helper macros common to all projects
//
#define BIT(p,b)                (b)

#define PORT(p,b)               (PORT ## p)
#define PIN(p,b)                (PIN ## p)
#define DDR(p,b)                (DDR ## p)

#define MASK(b)                 (1 << (b))

#define Set_Port_Bit(p,b)       ((p) |= MASK(b))
#define Clr_Port_Bit(p,b)       ((p) &= ~MASK(b))
#define Tgl_Port_Bit(p,b)       ((p) ^= MASK(b))

#define Get_Port_Bit(p,b)       (((p) & MASK(b)) != 0)

#define Set_Output(io)          Set_Port_Bit(PORT(io),BIT(io))
#define Reset_Output(io)        Clr_Port_Bit(PORT(io),BIT(io))
#define Toggle_Output(io)       Tgl_Port_Bit(PORT(io),BIT(io))
#define Get_Output(io)          Get_Port_Bit(PORT(io),BIT(io))

#define Get_Input(io)           Get_Port_Bit(PIN(io),BIT(io))

#define Tristate(io)            Clr_Port_Bit(DDR(io),BIT(io))
#define Drive(io)               Set_Port_Bit(DDR(io),BIT(io))

// LED example
// These macros (except IO_LED) are the ones to appear in in functions
//
#define IO_LED        A,3                 // Port letter and bit number
#define Led_On()   Reset_Output(IO_LED)   // inverted logic, just for fun
#define Led_Off()   Set_Output(IO_LED)
#define Is_Led_On() (!Get_Output(IO_LED))
#define Enable_Led() Drive(IO_LED)
#define Disable_Led() Tristate(IO_LED)  // I don't know why, just examples

Note that the seperate Get_Input and Get_Output macros prevent one from inadvertently trying to read the output latch instead of the pin state.

Note also the *_Port_Bit macros can be used for other kinds of ports, e.g.,

  Set_Port_Bit(ADCSRA, ADEN);  // Enable ADC converter


Regards,
  -=Dave






reply via email to

[Prev in Thread] Current Thread [Next in Thread]