Hi Community
This project uses :
- Uno
-2 Relays to Control 1 Motor with Forward, Reverse and Stop controls.
-LimitSwitch1 should stop the motor at the maximum forward position and wait for Reverse command.
-LimitSwitch2 should stop the motor at the maximum Reverse position and wait for Forward command.
i have both Limit switches wired with 10k resistors to Ground.
I cannot get this to work successfully.
Any input would be appreciated.
This project uses :
- Uno
-2 Relays to Control 1 Motor with Forward, Reverse and Stop controls.
-LimitSwitch1 should stop the motor at the maximum forward position and wait for Reverse command.
-LimitSwitch2 should stop the motor at the maximum Reverse position and wait for Forward command.
i have both Limit switches wired with 10k resistors to Ground.
I cannot get this to work successfully.
Any input would be appreciated.
Code:
const byte RELAY1 = 2;
const byte RELAY2 = 3;
const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte State_Idle = 0;
const byte State_Forward = 1;
const byte State_Reverse = 2;
byte currentState;
void setup(){
pinMode(RELAY1,OUTPUT);
pinMode(RELAY2,OUTPUT);
pinMode(LimitSwitch1, INPUT);
pinMode(LimitSwitch2, INPUT);
Serial.begin(9600);
currentState = 0xFF; // Force a change to enter the idle state
}
void loop(){
// Check if we need to change state
byte nextState = currentState;
switch (currentState)
{
case State_Idle:
{ // If we received a valid command, start the operation
if(Serial.available() > 0)
{
switch (Serial.read())
{
case 'A':
nextState = State_Forward;
break;
case 'B':
nextState = State_Reverse;
break;
default:
break;
}
}
}
break;
case State_Forward:
if(digitalRead(LimitSwitch2))
nextState = State_Idle;
break;
case State_Reverse:
if(digitalRead(LimitSwitch1))
nextState = State_Idle;
break;
default:
nextState = State_Idle;
break;
}
// If there was a change, switch state and trigger enter condition
if (nextState != currentState)
{
currentState = nextState; // Move in the new state
switch (currentState)
{ // Entering the new state
case State_Idle:
// Switch both Relays(Motor) OFF
digitalWrite(RELAY1, LOW);
digitalWrite(RELAY2, LOW);
break;
case State_Forward:
// Move Forward
digitalWrite(RELAY1, LOW);
digitalWrite(RELAY2, HIGH);
break;
case State_Reverse:
// Move Reverse
digitalWrite(RELAY1, HIGH);
digitalWrite(RELAY2, LOW);
break;
}
}
}