Reduce C language coding errors with X macros: Part 3

Andrew Lucas

March 02, 2013

Andrew LucasMarch 02, 2013

Timeout Tables
Another common table that can be similarly initialized is a timeout table. In the case of a master processor instead of a slave processor, you need to allow a set period of time for the slave to respond before determining that a communications fault has occurred. Usually different commands will have differing requirements for this time, so implementing a look-up table for each command is necessary. Modifying the x macro table, we can add this functionality easily:

/* ------ NAME ------- FUNCTION --- CODE --- TIMEOUT(ms) ---*/
  #define COMMAND_TABLE \
  ENTRY(RESERVED,    reserved,     0x00,      0) \
  ENTRY(COMMANDA,    commandA,     0x02,    100) \
  ENTRY(COMMANDB,    commandB,     0x09,    500) \
  ENTRY(COMMANDZ,    commandZ,     0xef,     20)

uint16_t timeout_table[N_COMMANDS] = {

Here is how I would use this table:

int get_command_timeout(uint8_t command) {
  return timeout_table[command_offset_table[command]];

GPIO Configuration
One final area is the use of x macros to allow for code reuse by making it simple to change what gpio pins are used by a module. As an example consider the following table:

  ENTRY(SWITCHA,      GPIOE,         GPIO_Pin_0) \
  ENTRY(SWITCHB,      GPIOA,         GPIO_Pin_0)
  ENTRY(SWITCHC,      GPIOC,         GPIO_Pin_5)
  ENTRY(SWITCHD,      GPIOE,         GPIO_Pin_1)

I will leave it to the reader as an exercise, but from this table, as long as the supporting code follows a few conventions, all you have to do is change the port and pin name in the table and all of the initialization code adjusts accordingly, making it easy to port over to a new design.

Final Thoughts
I hope you have enjoyed this overview of x macros and that you have learned something new in the process. Though an advanced technique, once in place the use of x macros can reduce errors and make the embedded programmer's life easier. I would love to read in the comments how readers are using x macros in their designs.

Read Part 1
Read Part 2

Andrew Lucas leads a team of firmware developers at NCR Canada, where he is responsible for the firmware architecture of intelligent deposit modules for NCR's line of ATMs.

< Previous
Page 2 of 2
Next >

Loading comments...

Parts Search

Sponsored Blogs