Hi, newbie alert :~
I'm trying to move a tray which has a limit switch at each end when an "O" is received over serial, my code is below - my problem is that the void trayout() section isn't working as I want it to - I want to run the motor till the switch readings show the tray is ejected - but this isn't happening at the moment, any advice on what I'm doing wrong? Thank you very much.
#include <AFMotor.h>
AF_DCMotor motor(3);
const int ledPin = 13; //LED used to indicate motor action, manually moving tray for testing to activate switches
const int trayoutPin = 4; //pin 4 is 0 when tray is out, 1 when tray is coming in/in
const int trayinPin = 8; //pin 8 is 0 when tray is in, 1 when tray is out/going out
int TRAYOUT = 'O'; //we are looking for a "O" to eject tray
int trayoutState = 0; //set initial switch values
int trayinState = 0; // " "
void setup() {
pinMode(trayoutPin, INPUT);
pinMode(trayinPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
if (Serial.available()) {
int command = Serial.read();
if (command == TRAYOUT)
trayout();
}
}
void trayout()
{
trayoutState = digitalRead(trayoutPin);
Serial.print("tray out state: "); //these serial printouts are just so I can see status of switches
Serial.println(trayoutState);
trayinState = digitalRead(trayinPin);
Serial.print("tray in state: ");
Serial.println(trayinState);
if (trayoutState == 0 && trayinState == 1)
{
Serial.println("Tray out");
}
else
{
digitalWrite(ledPin, HIGH);
Serial.println("tray ejecting");
motor.run(FORWARD);
motor.setSpeed(255);
}
}