Page 1 of 1

SetPin macros..explained

Posted: Sun Jun 06, 2021 2:22 pm
by AnalysIR
we got a query from a user, which may be helpful to other...
....
I do have a question: In the KontroLIR demo firmware (KontroLIR.ino) in the file KIR_header.h you define some macros like this:
#define LEDON SetPinHIGH(E, PE3)
#define LEDOFF SetPinLOW(E, PE3)
...

I haven't been able to find where E and PE3 are defined. They work but they seem to come out of nowhere. Which header file are those from please?

thanks
Response is below:

E is port E on the AVR MCU

PE3 is a pin number on the ATmega328PB - it has a few xtra pins over the normal arduino ATmega328P (in PORTE)

SetPinHigh is a macro which allows fast setting of pins directly instead of using the slower Arduino digitalWrite().


The macros are defined in KIR_header.h

// PORT Level Pin manipulation - much faster access than Arduino defaults
#define SetPinINPUT(port, pin) DDR##port &= ~(1 << pin)
#define SetPinOUTPUT(port, pin) DDR##port |= (1 << pin)
#define SetPinHIGH(port, pin) PORT##port |= (1 << pin)
#define SetPinLOW(port, pin) PORT##port &= ~(1 << pin)
#define TogglePin(port, pin) PORT##port ^= (1 << pin)


The ## is a concatenation syntax. So in your example

SetPinHIGH(E, PE3)

is converted to PORTE |=(1<<PE3), by the pre-compiler on the PC IDE only...so there is no actual runtime overhead on the MCU.

.....which is the fastest way of setting a pin, using direct register access.

PORTE & PE3 would be defined in the AVR includes which happen as part of the Arduino subsystem/core definition, which may not be visible in the IDE.



....hope this helps