Model Railroad crossing signal lights project.

Hi, I'm new to Arduino, I thought it was going to be easier but I'm running into a problem, basically I'm using an infrared sensor to detect the train, 2 LED's that will alternate as my train passes by and a servo that will drive the crossing arms, well it was all going OK but when I put the program to the test one of my LED's blinks all the time (ledPin2), even when nothing in front of the IR sensor, other than that when the train passes in front of the IR sensor my LED's alternate and the servo works fine, the value on the IR sensor at AI 0 is 410 when a train is present and 10 when is not, Thanks in advance.

#include <Servo.h>

Servo myservo1;

int IRsensor = 0;
int val;
int ledPin1 =1;
int ledPin2 =2;
void setup()
{
myservo1.attach(9);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);

}

void loop()
{
val = analogRead(IRsensor);

val = map(val, 8, 400, 0, 180);
myservo1.write(val);

val = analogRead(IRsensor);
if(val > 300)
digitalWrite(ledPin1,HIGH);
digitalWrite(ledPin2,LOW);
delay(350);
digitalWrite(ledPin1,LOW);
digitalWrite(ledPin2,HIGH);
delay(350);

if (val < 300)
digitalWrite(ledPin2,LOW);
digitalWrite(ledPin1,LOW);

}

Traindetector.ino (659 Bytes)

Try this, untested. You need to learn about using blocks when using if and if..else with using/needing compound statements:

http://arduino.cc/en/Reference/If
http://arduino.cc/en/Reference/Else

val = analogRead(IRsensor);            
  if(val > 300)
   { 
    digitalWrite(ledPin1,HIGH);
    digitalWrite(ledPin2,LOW);
    delay(350);
    digitalWrite(ledPin1,LOW);
    digitalWrite(ledPin2,HIGH);
    delay(350);
   }
  else
   {
    digitalWrite(ledPin2,LOW);
    digitalWrite(ledPin1,LOW);
   }

I am working on the same project in N scale. I am going to use 2 photo/motion sensors on a double main line (one for each line). I am not sure if I need two servos or one. One member of my train club made a controller for to control a pair of semaphores.