I am using an Arduino for the first time to control the level crossing gates on my model railway using an LDR and two servos. I want to have a train run over a photo resistor (LDR). On this event, the gates should close. When the train has passed over, there should be a delay and then the gates should open. The code presented here is simplified to just open the gates and close them without the required delays. As the LDR sends constant readings, the servos should only respond on the initial change as I don't want to manage servos pulling or pushing on gates once they have moved.
I have tried using a global to hold the gate state. I have now changed the code to pass a variable around.
#include <Servo.h>
Servo myservo;
int sensorPin = A0; // select the input pin for LDR
int sensorValue = 0; // variable to store the value coming from the sensor
int pos = 1;
int barState;
void setup() {
Serial.begin(9600); //sets serial port for communication
myservo.attach(9);
barState = 0;
}
int upMove(int bs)
bs = 0;
for (pos = 0; pos <= 60; pos += 1) { // goes from 0 degrees to 60 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(30); // waits 30ms for the servo to reach the position
}
return bs;
}
int downMove(int bs)
{
bs = 1;
for (pos = 60; pos >= 0; pos -= 1) { // goes from 60 degrees to 0 degrees
// in steps of 1 degree
{ myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(30); // waits 30ms for the servo to reach the position
}
return bs;
}
int up(int bs)
{
if ( bs = 1) {
bs = upMove(bs);
}
return bs;
}
int down(int bs)
{
bs = downMove(bs);
}
return bs;
}
void loop() {
{ sensorValue = analogRead(sensorPin); //define photocellReading as pin 0 input from LDR
sensorValue = map(sensorValue, 0, 1023, 0, 179); //map the LDR input to a value between 1-180 so the servo can understand it
if (sensorValue > 90) //if the LDR is showing less than half light intensity
{
up(barState);
}
else if (sensorValue <= 90) //if the LDR is showing more than half light intensity
{
down(barState); //then tell the servo to rotate forwards at a steady rate
}
}
}
The code is working for Up but not for Down. Up works once but Down continually resets and operates the servo.