I have made a prototype track switching device (Turnout) that uses a servo to move the switch from straight to turn and vise versa. I modified code that I found on the web and it works fine with one switch ( code included below ). I use two momentary buttons as activators, one for straight and one for turn.
The problem...
I have 6 switches to install so I want to expand the code. A Nano should be able to handle 3 servos ( rather than one Nano/servo per turnout ). First step was to add a second switch(turnout) to my prototype. Can't figure out how to structure the state setup for a second set of buttons and turnout/servo.
I am using a Nano with SG90 servos.
I started by trying to create a second "switchState" ( using switchStateA and switchStateB)
eg. switch (switchStateA , switchStateB)
But that does not work..
Here is the code that works;
#include <Servo.h>
Servo switch1; //declares my servo switch
const int straight1 = 11; // Black Button to go straight
const int turn1 = 12; // Red Button to turn
int pos = 0;
int posstraight=40; // servo angle for straight
int posturn=135; // servo angle for turn
int straightstate = 0;
int turnstate = 0;
void setup()
{
Serial.begin(9600); //starts the serial monitor
switch1.attach(6); // attaches the servo on pin 6
pinMode(straight1, INPUT);
pinMode(turn1, INPUT);
switch1.write(90); // servo Start at point middle
}
enum SWITCHSTATES // Setting up the different Switch states
{
ST_OFF1,
ST_OFF2,
ST_STRAIGHT,
ST_TURN,
};
SWITCHSTATES switchState = ST_OFF1; //Sets default state to off1
void loop() {
straightstate = digitalRead(straight1); // read pin 11
turnstate = digitalRead (turn1); // read pin 12
delay (200);
switch (switchState)
{
case ST_OFF1:
switchoff1(straightstate); //sets up change to ST_OFF1
break;
case ST_OFF2:
switchoff2(turnstate); //sets up change to ST_OFF2
break;
case ST_STRAIGHT:
switchstraight(straightstate); //sets up change to ST_STRAIGHT
break;
case ST_TURN:
switchturn(turnstate); //sets up change to ST_TURN
break;
}
}
void switchoff1(int straight){
switch1.write(posstraight);
if (straightstate == HIGH){
switchState = ST_TURN;
}
}
void switchturn(int straight1){
for (pos = posstraight; pos <= posturn; pos += 1){ // goes from 40 degrees to 135 degrees
switch1.write(pos);
delay(15);
}
switchState = ST_OFF2;
}
void switchoff2(int turn1){
switch1.write(posturn);
if (turnstate == HIGH){
switchState = ST_STRAIGHT;
}
}
void switchstraight(int turn){
for (pos=posturn; pos >= posstraight; pos -= 1){ // goes from 135 degrees to 40 degrees
switch1.write(pos);
delay(15);
}
switchState = ST_OFF1;
}
Thanks