Nice to see you’re using these macros I wrote months ago. At the time, David seemed interested to include them in Arduino. At least that’s what he said on the developer mail list. I would not have done all that work had I known it would only sit in the issue tracker, rather than be included in 0018. (likewise, many other optimizations I’ve explored won’t been ported to Arduino and written up nicely, because if issue #140 can’t be included, certainly other more difficult optimizations for non-const cases won’t be).
Still, a library implementation is better than nothing.
Could I convince you to surround each definition with a check to avoid redefining if it already exists? For example:
(((P) >= 0 && (P) <= 7) ? &PORTD : (((P) >= 8 && (P) <= 13) ? &PORTB : &PORTC))
I realize this adds a lot of extra #if and #endif lines. However, if these definitions ever become included in the Arduino core (where they rightly belong), your code will continue to work.
On 3rd party boards, this will allow those boards to define these macros for their different pin assignments, and your code will automatically use them.
Also, on Arduino Mega, issue #146 will apply to the pins which use registers beyond the range usable with the CBI and SBI instructions. Then again, issue #146 applies to ALL usage of the normal digitalWrite() and pinMode() functions, regardless of register addresses.
If you care about issue #146, you could add a check if the pointer (cast to an integer) is greater than 32, and if so, surround the bitWrite with code to save interrupt context, disable interrupts, and then restore. Because this is within the check for __builtin_constant_p(P), the compiler will only include that code for the appropriate pins.
So far, nobody seems to care much about issue #146. Someday I’ll get around to writing some test cases to demonstrate the problem. Trust me, it is real. The “nobody has ever complained in 5 years” is only because recently have widely used libraries and functions called digitalWrite() from interrupts, and because the problems are so very mysterious and difficult to debug. Such is the way of race conditions.
Still, nice work on library-izing this. Hope it gets some use.