I have two pieces of code one as a transmitter and another as receiver. I want to push both these codes to an arduino but want the arduino to switch between being a transmitter or a receiver using a physical switch button what should the code be like ?
The transmitter is only having a void setup(){} function but in the receiver it is having both setup and loop functions
Do you want to switch at any point in time or just when starting up?
Have you considered having both roles active at the same time and the switch is tested to decide what to do in the loop?
Here is an example that uses the state change detection method to toggle between running one function or the other.
// by C Goulding aka groundFungus
const byte buttonPin = 12; // the pin to which the pushbutton is attached
const byte ledPin = 13; // the pin to which the LED is attached
bool buttonState = 0; // current state of the button
bool lastButtonState = 0; // previous state of the button
bool mode = false;
void setup()
{
// initialize the button pin as a input with internal pullup enabled
pinMode(buttonPin, INPUT_PULLUP);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(115200);
Serial.println("Select mode with push button");
}
void loop()
{
static unsigned long timer = 0;
unsigned long interval = 50; // check switch 20 times per second
if (millis() - timer >= interval)
{
timer = millis();
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
// compare the new buttonState to its previous state
if (buttonState != lastButtonState)
{
if (buttonState == LOW)
{
// if the current state is LOW then the button
// went from off to on:
digitalWrite(ledPin, !digitalRead(ledPin)); // toggle the LED output
mode = !mode; // toggle the mode
}
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
}
if (mode == true)
{
function1();
}
else
{
function2();
}
}
void function1()
{
// run code for function 1
static unsigned long timer = 0;
unsigned long interval = 1000;
if (millis() - timer >= interval)
{
timer = millis();
Serial.println("Running function 1");
}
}
void function2()
{
// run code for function 2
static unsigned long timer = 0;
unsigned long interval = 1000;
if (millis() - timer >= interval)
{
timer = millis();
Serial.println("Running function 2");
}
}