Help with preprocessor macro/xmacro

Anything not related to STM32
Post Reply
User avatar
Kenjutsu
Posts: 129
Joined: Fri May 29, 2015 8:26 am

Help with preprocessor macro/xmacro

Post by Kenjutsu » Mon Jul 03, 2017 12:08 pm

I find myself doing more stuff like the following.

Code: Select all

#define LED_DLY 200
int led1;
int led2;
int led3;
int led4;

void setup_a()
{
  led1 = 10;	            
  led2 = 11;
  led3 = 12;
  led4 = 13;
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
}

void loop() {
  digitalWrite(led1, HIGH);
  digitalWrite(led2, HIGH);
  digitalWrite(led3, HIGH);
  digitalWrite(led4, HIGH);
  delay(LED_DLY);
	
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW); 
  digitalWrite(led3, LOW); 
  digitalWrite(led4, LOW);    
  delay(LED_DLY);
}
It is a lot of copy 'n' paste work and I am trying to use macros to simplify the process. So far, I came up with the following:

Code: Select all

#define LED_VAR_LIST \
    X(led1) \
    X(led2) \
    X(led3) \
    X(led4)

#define X(name) int name;
	LED_VAR_LIST
#undef X
The above will declare the four variables. In setup() I have the following:

Code: Select all

  led1 = 2;	            
  led2 = 3;
  led3 = 4;
  led4 = 5;
  #define X(name) pinMode(name, OUTPUT);
    LED_VAR_LIST
  #undef X  
to set all the pins to OUTPUT. In loop() I have the following:

Code: Select all

#define X(name) digitalWrite(name, HIGH);
  LED_VAR_LIST
#undef X
	
delay(LED_DLY);
	
#define X(name) digitalWrite(name, LOW);
  LED_VAR_LIST
#undef X

delay(LED_DLY);
So far, so good. What I would like to do further, is create a parallel table/list that contains the corresponding pin numbers, and use a macro to assign the pin numbers to the correct variable in LED_VAR_LIST. This will then replace the following in setup():

Code: Select all

  led1 = 10;	            
  led2 = 11;
  led3 = 12;
  led4 = 13;
This is where I need some help ;)
OSX: 10.12.5
Arduino IDE: 1.6.12
Blue pill STM32F103C8T6 Dev Board
Maple Mini Clones

User avatar
RogerClark
Posts: 6726
Joined: Mon Apr 27, 2015 10:36 am
Location: Melbourne, Australia
Contact:

Re: Help with preprocessor macro/xmacro

Post by RogerClark » Mon Jul 03, 2017 9:43 pm

Why are you using macros?

I would do this with const arrays of pins and or loops to iterate the array

I think I posted a snippet that set up 8 pins as input in the thread about the OV7670 camera, as the original code I was using was not setting pinmode, which caused problems with one pin not working as input ( due to a separate bug in the code, which I have since fixed)

ag123
Posts: 719
Joined: Thu Jul 21, 2016 4:24 pm

Re: Help with preprocessor macro/xmacro

Post by ag123 » Thu Jul 06, 2017 4:47 pm

would an array work? e.g. instead of
led1 = 1;
led2 = 2;
led3 = 3;

use an array instead
int led[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 10 };
:)

Post Reply