Technically, you can't have two sketches on one board. It's not really a different program.
The switch automatically:
You don't even need any extra hardware for this approach. Just turn on the pullup resistors in your board with this code:
pinMode(pin, INPUT); // set pin to input
digitalWrite(pin, HIGH); // turn on pullup resistors
Note: you will need a switch that conducts electricity when it's not pushed. I can't remember the abbreviation off the top of my head.
With that code, all you have to do is connect one end of the switch to the Arduino pin of your choice and the other end to GND
. Don't add a resistor to this button, as the Arduino does this automatically with the above code. Then, to check for if it's pushed or not, just do the standard digitalRead(pin);
and it will return:
HIGH
if the button's being pushed or the button isn't connectedLOW
if the button isn't being pushed but it's connected
Since two states share the same return value, I'd recommend switching when both buttons return HIGH
. If you want to be sure they're disconnected, you might want to make sure they stay pushed for two seconds, and then switch after that, but that would add latency to your code.
Switching from one state to another:
You'll have to use the code above that I mentioned and check for it getting plugged in. Then, it will execute the code depending on the buttons. I wrote some no-frills code below with only a delay();
for debouncing to add simplicity. If you want to make it more advanced, feel free to do so, but I don't have the time now. Also, there is a little delay switching between modes.
#define button1 2
#define button2 3
boolean isManual = false;
void setup() {
pinMode(button1, INPUT);
digitalWrite(button1, HIGH);
pinMode(button2, INPUT);
digitalWrite(button2, HIGH);
//Other setup code here!
}
void loop() {
checkForChanges();
if (isManual == false) {
//Do code here for manual buttons. If there's a loop or a decently sized delay inside, call `checkForChanges` and see if it's still manual. If not, use `break;` to escape loop/if statement
} else {
//Do code here for auto. If there's a loop or a decently sized delay inside, call `checkForChanges` and see if it's still auto. If not, use `break;` to escape loop/if statement
}
//Add any code you want executed regardless of if it's manual or auto
}
void checkForChanges() {
if (isManual == false) {
if (digitalRead(button1) == LOW && digitalRead(button2) == LOW) {
isManual = true;
delay(200); //Crude debouncing; feel free to edit
}
} else {
if (digitalRead(button1) == LOW && digitalRead(button2) == LOW) {
isManual = true;
delay(1000); //Crude debouncing; feel free to edit; you need some delay here even if there's debouncing to make sure someone isn't pushing both
if (digitalRead(!(button1) == LOW && digitalRead(button2) == LOW)) {
isManual = false;
}
}
//Do one read of inputs. If
}
}