Ok, first of all you have to answer this question:
How can I tell the compiler what program it should compile?
The first (and easiest) solution is to have the preprocessor to this job. It's just a matter of writing two /
...
Personally, instead of wrapping everything in an ifdef
, I would have done something like
#include "share.h"
#define TX
#ifdef TX
#define setup_tx() setup()
#define loop_tx() loop()
#else
#define setup_rx() setup()
#define loop_rx() loop()
#endif
void setup_tx(){...}
void loop_tx(){...}
void setup_rx(){...}
void loop_rx(){...}
This way I could put the two different setup/loop pairs in two different files (e.g. tx.ino and rx.ino). Moreover the ifdef
block can be moved in an h file.
NOTE: I'm not sure wheter the function redefinition works well, because I never tried it. If it doesn't work you can try doing the opposite (i.e. #define setup() setup_tx()
and so on) or, in the end, make single-line functions (i.e. void setup(){setup_tx();}
and so on).
Another solution can be applied if the processors are different. For instance if you have an Arduino UNO as transmitter and an Arduino Mega 2560 as a receiver, you could write:
#ifdef __AVR_ATmega2560__
- receiver functions
#else
- transmitter functions
#endif
But this would require you to switch processor along with the port.
The third solution is to place the shared h file in an include directory. You can do this by using a common include dir:
The include path includes the sketch's directory, the target directory (/hardware/core//) and the avr include directory (/hardware/tools/avr/avr/include/), as well as any library directories (in /hardware/libraries/) which contain a header file which is included by the main sketch file.
(See here)
You can also pass the -Idir
option to avr-gcc to include also dir
in the include dirs list, but this requires you to change the boards.txt file.
The last solution I can think at is to compile both programs, load the same files on both arduinos and then choose at runtime what is the correct program to use by assinging a pin to the "choice of program" function.
For instance you assing pin 8 to this function. On the TX board you connect pin 8 to VCC, while on the RX board you connect it to GND. Then the program is:
#include "share.h"
// Loop function callback (to speed things up)
typedef void (*loopfunction)();
loopfunction currentloop;
const int RXTX_PIN = 8;
void setup()
{
pinMode(RXTX_PIN,INPUT);
if (digitalRead(RXTX_PIN))
{
setup_tx();
currentloop = loop_tx;
}
else
{
setup_rx();
currentloop = loop_rx;
}
}
void loop()
{
currentloop();
}
void setup_tx(){...}
void loop_tx(){...}
void setup_rx(){...}
void loop_rx(){...}
IMHO the best solution is the first one, i.e. the define one. But... You should choose the best for your particular problem.
Bye