I'm working with embedded C for a microcontroller right now and I find that sometimes there are several peripherals that differ only by a single letter (for example UARTA, UARTB, etc). The code for each peripheral is often times identical except for lettering of otherwise identical registers. For example to setup peripheral A I would do something like:
UCA2CTL1 |= UCSWRST; // Put state machine in reset
UCA2CTL0 |= UCSYNC+UCCKPL+UCMSB; // 3-pin, 8-bit SPI slave
// Continue initializing peripheral registers with "A" in name
And to setup peripheral B I have exactly the same code, except that the register names are transposed by 1 letter:
UCB2CTL1 |= UCSWRST; // Put state machine in reset
UCB2CTL0 |= UCSYNC+UCCKPL+UCMSB; // 3-pin, 8-bit SPI slave
// Continue initializing peripheral registers with "B" in name
I would like to have the ability to change which peripheral I target without having to #ifdef/copy/paste code or find/replace. Is there some compiler directive or clever trick that can implement this behavior so that I only have to write the code once? I would love to just #define the last letter in the peripheral, but something like that seems to wander dangerously close to code stink to me.
Will this work for you?
#define INITUC(device) \
UC ## device ## 2CTL1 |= UCSWRST; \
UC ## device ## 2CTL0 |= UCSYNC+UCCKPL+UCMSB
...
INITUC(A);
INITUC(B);