51 Replies Latest reply on Apr 18, 2018 4:28 PM by balearicdynamics

    Please I need help Writing code

    theshay

      I am trying to write code for an automatic railroad crossing gates for my grandsons train table i built. I have no clue what i am doing. What i can say is im using 2 servos with external power 4 red leds that need to flash and a speaker for bell ding which i was hoping to use a sound file to play back my wire config is 2,3 for leds  2 servos 5,6 I also have a 10 second record-able device for train horn which uses push button for playback. i wanted to cut off the push button and use the arduino r3 to act as the push button pin 8. Also i will have 2 reed switches one to activate gates and lights and one to deactivate pins 4,7 this is what i have so far I get the lights to flash but im lost from there can some one help me write this code?

       

      @@@@

      int rd1LEDPin=2; //Declares rd1LED as int and set to 2

      int rd2LEDPin=3; //declairs rd2LED as int and set to 3

       

      int rd1onTime=250; //light 1 on time

      int rd1offTime=250;  // light 1 off time

      int rd2onTime=250; //light 2 on time

      int rd2offTime=250;  // light 2 off time

       

      const int REED_PIN = 4; // Pin connected to reed switch

      const int REED_PIN = 7; // Pin connected to reed switch

      const int LED_PIN = 13; // LED pin - active-high

       

       

      void setup() {

        pinMode(rd1LEDPin, OUTPUT);// sets the second pin for output

         pinMode(rd2LEDPin, OUTPUT);// sets the third pin for output

       

        Serial.begin(9600);

        // Since the other end of the reed switch is connected to ground, we need

        // to pull-up the reed switch pin internally.

        pinMode(REED_PIN, INPUT_PULLUP);

        pinMode(LED_PIN, OUTPUT);

      }

       

      void loop() {

        digitalWrite(rd1LEDPin,HIGH); //turns led 1 on

        digitalWrite(rd2LEDPin,LOW); // turns led 2 off

        delay (rd1onTime); //wait

        delay(rd2offTime); //wait

       

        digitalWrite(rd1LEDPin,LOW); //turns led 1 off

        digitalWrite(rd2LEDPin,HIGH);//turns led 2 on

        delay (rd1offTime);//  wait

        delay(rd2onTime);  //wait

       

        int proximity = digitalRead(REED_PIN); // Read the state of the switch

        if (proximity == LOW) // If the pin reads low, the switch is closed.

        {

          Serial.println("Switch closed");

          digitalWrite(LED_PIN, HIGH); // Turn the LED on

        }

        else

        {

          digitalWrite(LED_PIN, LOW); // Turn the LED off

       

      }

        • Re: Please I need help any body
          andywest

          You may want to change the title of your discussion to something more specific than "Please I need help any body". People are more likely to read and answer you that way. Adding relevant tags can also help.

           

          Also, do you have a specific question? What does your code do, and how is that different than what you expected?

          5 of 5 people found this helpful
            • Re: Please I need help Writing code
              theshay

              ok i changed it. please for give me im an old man trying to do something for my autistic grandson he loves trains. so i build him a table for his birthday. only thing left to do is make the crossing gates lights and sound to work. I have no clue how to write code. everyone says it is so easy but not for me apparently.

              2 of 2 people found this helpful
                • Re: Please I need help Writing code
                  andywest

                  That sounds like a nice gift.

                   

                  You included some code in your post. Did you write that? If so then I would say you have some clue. But we need more details about what's working and what isn't before we can help you.

                   

                  I get the lights to flash but im lost from there

                   

                  Does that mean that the above code is working fine, but you're not sure how to code for the audio?

                  1 of 1 people found this helpful
                    • Re: Please I need help Writing code
                      theshay

                      int rd1LEDPin=2; //Declares rd1LED as int and set to 2

                      int rd2LEDPin=3; //declairs rd2LED as int and set to 3

                       

                      int rd1onTime=250; //light 1 on time

                      int rd1offTime=250;  // light 1 off time

                      int rd2onTime=250; //light 2 on time

                      int rd2offTime=250;  // light 2 off time

                       

                       

                       

                      void setup() {

                        pinMode(rd1LEDPin, OUTPUT);// sets the second pin for output

                         pinMode(rd2LEDPin, OUTPUT);// sets the third pin for output

                       

                       

                      }

                       

                      void loop() {

                        digitalWrite(rd1LEDPin,HIGH); //turns led 1 on

                        digitalWrite(rd2LEDPin,LOW); // turns led 2 off

                        delay (rd1onTime); //wait

                        delay(rd2offTime); //wait

                       

                        digitalWrite(rd1LEDPin,LOW); //turns led 1 off

                        digitalWrite(rd2LEDPin,HIGH);//turns led 2 on

                        delay (rd1offTime);//  wait

                        delay(rd2onTime);  //wait

                        

                       

                      this is the part that works the lights flash I copied most of the code from a tutorial and im trying to put it together it took me 2 days to get the lights to flash properly by playing with the numbers i basically want two reed switches one to activate and one to deactivate I am a retired electrician so i know the basics what resistors to use with what led an so forth. I can wire it up but programming it is a whole different ball game and im clueless. I have less than a month to finish and im starting to panic. He will be 13 I really wanted to go above and beyond and do something special but im beginning to think i may have bitten off more than i can chew :-(

                      1 of 1 people found this helpful
                        • Re: Please I need help Writing code
                          andywest

                          I'm not sure I have the complete picture, but it sounds like you have two switches. One switch causes the lights to flash, the gate to come down, and the sound to play. The other switch stops the flashing, moves the gate back, and stops the sound. Correct?

                           

                          Coding for the switches should be fairly easy. You'll want to connect to an available GPIO pin and use digitalRead() instead of digitalWrite(). Then you need to store the results in a variable so when you're going through the loop you can evaluate and determine whether to flash, ring the bell, etc. There is a lot of example code out there; here's a link that might help:

                           

                          https://www.arduino.cc/en/Tutorial/Button

                           

                          Several years ago I used an Arduino to simulate button presses on an RF remote for room lighting, so I know it's possible. I'll see if I can dig up the code.

                           

                          I have no experience controlling servos, but there are many people in this community who are knowledgeable about that aspect.

                          1 of 1 people found this helpful
                        • Re: Please I need help Writing code
                          theshay

                          I found some code that works and is very similar to what i want but im not sure how to edit the code to do what i want, for instance the code has infrared sensors but in using reed switches and it has a timer that i don't need.  This is the code but i dont know how to change it to what i have wired and get rid of the timer and lcd ect..

                           

                          Railroad crossing controller

                           

                          */

                           

                          #include <Servo.h>

                           

                           

                          // Constants

                           

                          const int CYCLE_PERIOD_MS = 10;

                           

                           

                          const int SENSOR_DELTA_THRESHOLD = 20;

                           

                           

                          const int BELL_RING_PERIOD = 400;

                           

                          const int BELL_RING_CYCLES = BELL_RING_PERIOD / CYCLE_PERIOD_MS;

                           

                          const int BELL_TONE_FREQUENCY = 300;

                           

                          const int BELL_DURATION = 180;

                           

                           

                          const int LIGHT_BLINK_PERIOD = 1000;

                           

                          const int LIGHT_BLINK_CYCLES = LIGHT_BLINK_PERIOD / CYCLE_PERIOD_MS;

                           

                          const int LIGHT_BLINK_HALF_CYCLES = LIGHT_BLINK_CYCLES / 2;

                           

                           

                          const float CROSSING_POSITION_RAISED = 110.0;

                           

                          const float CROSSING_POSITION_LOWERED = 15.0;

                           

                          const float CROSSING_DEGREES_PER_CYCLE = 0.1;

                           

                           

                          const int TRAIN_SPEED_MS_PER_SECTION = 1000;

                           

                          const int TRAIN_SECTIONS_TO_CROSSING = 13;

                           

                           

                          const int TIME_GATE_WARNING_BEFORE_TRAIN_MS = 7000;

                           

                          const int TIME_GATE_DOWN_BEFORE_TRAIN_MS = 5000;

                           

                          const int TIME_GATE_DOWN_AFTER_TRAIN_MS = 2000;

                           

                          const int TIME_GATE_DOWN_BEFORE_TRAIN_CYCLES = TIME_GATE_DOWN_BEFORE_TRAIN_MS / CYCLE_PERIOD_MS;

                           

                          const int TIME_GATE_DOWN_AFTER_TRAIN_CYCLES = TIME_GATE_DOWN_AFTER_TRAIN_MS / CYCLE_PERIOD_MS;

                           

                           

                          const int PIN_SENSOR = 0;

                           

                          const int PIN_LEFT_LIGHT = 2;

                           

                          const int PIN_RIGHT_LIGHT = 3;

                           

                          const int PIN_STATUS_LIGHT_ARRIVAL = 4;

                           

                          const int PIN_STATUS_LIGHT_DEPARTURE = 5;

                           

                          const int PIN_BUZZER = 6;

                           

                          const int PIN_SERVO = 7;

                           

                           

                          // Enums and globals

                           

                          enum sensorState {

                           

                            out, entering, in, exiting

                           

                          }

                           

                          sensorState = out;

                           

                           

                          enum crossingState {

                           

                            up, warning, lowering, down, raising

                           

                          }

                           

                          crossingState = up;

                           

                           

                          Servo gateServo;

                           

                          int sensorThreshold = 0;

                           

                          long trainArrivalCountDownMS = 0;

                           

                          long trainDepartureCountDownMS = 0;

                           

                          int bellCycleCounter = 0;

                           

                          int leftLightCycleCounter = 0;

                           

                          int rightLightCycleCounter = LIGHT_BLINK_HALF_CYCLES;

                           

                          float crossingPosition = CROSSING_POSITION_RAISED;

                           

                           

                           

                          /*

                           

                          One time initializations

                           

                          */

                           

                          void setup()

                           

                          {

                           

                            pinMode(PIN_LEFT_LIGHT, OUTPUT);

                           

                            pinMode(PIN_RIGHT_LIGHT, OUTPUT);

                           

                            pinMode(PIN_STATUS_LIGHT_ARRIVAL, OUTPUT);

                           

                            pinMode(PIN_STATUS_LIGHT_DEPARTURE, OUTPUT);

                           

                            pinMode(PIN_BUZZER, OUTPUT);

                           

                           

                            // we assume that a train is not in the sensor at startup

                           

                            sensorThreshold = analogRead(PIN_SENSOR) + SENSOR_DELTA_THRESHOLD;

                           

                           

                            gateServo.attach(PIN_SERVO);

                           

                            gateServo.write(CROSSING_POSITION_RAISED);

                           

                           

                            Serial.begin(9600);

                           

                          }

                           

                           

                          /*

                           

                          Main control loop.

                           

                          Check the sensor, update outputs, and then wait the cycle period.

                           

                          */

                           

                          void loop()

                           

                          {

                           

                            checkSensor();

                           

                            updateTimers();

                           

                            updateStatusLights();

                           

                            updateCrossingState();

                           

                            updateBells();

                           

                            updateLights();

                           

                            updateGatePosition();

                           

                            delay(CYCLE_PERIOD_MS);

                           

                          }

                           

                           

                           

                          /*

                           

                          Check sensor and update transitions or states

                           

                          */

                           

                          void checkSensor()

                           

                          {

                           

                            if (isTrainPresentAtSensor()) {

                           

                             switch (sensorState) {

                           

                             case in:

                           

                             // still in...

                           

                             break;

                           

                             case entering:

                           

                            Serial.println("\nsensor -> in");

                           

                            sensorState = in;

                           

                             break;

                           

                             case out:

                           

                             case exiting:

                           

                            Serial.println("\nsensor -> entering");

                           

                            sensorState = entering;

                           

                             break;

                           

                            }

                           

                            } else {

                           

                             switch (sensorState) {

                           

                             case in:

                           

                             case entering:

                           

                            Serial.println("\nsensor -> exiting");

                           

                            sensorState = exiting;

                           

                             break;

                           

                             case out:

                           

                             break;

                           

                             case exiting:

                           

                            Serial.println("\nsensor -> out");

                           

                            sensorState = out;

                           

                             break;

                           

                            } 

                           

                            }

                           

                          }

                           

                           

                          /*

                           

                          Set the timers when a train arrives,

                           

                          increment the departure timer if a train is still in the sensor,

                           

                          decrement the timers if a train is on its way

                           

                          */

                           

                          void updateTimers() {

                           

                            switch (sensorState) {

                           

                             case in:

                           

                            trainDepartureCountDownMS += CYCLE_PERIOD_MS;

                           

                             break;

                           

                             case entering:

                           

                             // is this a new train or an additional train?

                           

                             if (trainDepartureCountDownMS > 0) {

                           

                             // it is an additional train...

                           

                             // leave the arrival time as-is, add the time it takes for the new train to arrive on the departure timer

                           

                            Serial.println("\nAdditional train detected...");

                           

                            trainDepartureCountDownMS = calculateTrainArrivalTimeMS() + CYCLE_PERIOD_MS + TIME_GATE_DOWN_AFTER_TRAIN_MS; 

                           

                             // Serial.print("Arrival: ");

                           

                             // Serial.print(trainArrivalCountDownMS);

                           

                             // Serial.print("Departure: ");

                           

                             // Serial.println(trainDepartureCountDownMS); 

                           

                            } else {

                           

                             // it is a new train...

                           

                            Serial.println("\nNew train detected...");

                           

                            trainArrivalCountDownMS = calculateTrainArrivalTimeMS();

                           

                            trainDepartureCountDownMS = trainArrivalCountDownMS + CYCLE_PERIOD_MS + TIME_GATE_DOWN_AFTER_TRAIN_MS;

                           

                             // Serial.print("Arrival: ");

                           

                             // Serial.print(trainArrivalCountDownMS);

                           

                             // Serial.print("Departure: ");

                           

                             // Serial.println(trainDepartureCountDownMS); 

                           

                            }

                           

                             break;

                           

                             case out: 

                           

                             case exiting:

                           

                             // do nothing additional

                           

                             break;

                           

                            }

                           

                           

                            if (trainArrivalCountDownMS > 0) {

                           

                            trainArrivalCountDownMS -= CYCLE_PERIOD_MS;

                           

                            }

                           

                           

                            if (trainDepartureCountDownMS > 0) {

                           

                            trainDepartureCountDownMS -= CYCLE_PERIOD_MS;

                           

                            }

                           

                          }

                           

                           

                           

                          /*

                           

                          Manage crossing state transitions

                           

                          */

                           

                          void updateCrossingState() {

                           

                            switch (crossingState) {

                           

                             case up:

                           

                             if ((trainDepartureCountDownMS > 0) && (trainArrivalCountDownMS < TIME_GATE_WARNING_BEFORE_TRAIN_MS)) {

                           

                            Serial.println("\ngate up -> warning");

                           

                            crossingState = warning;

                           

                            }

                           

                             break;

                           

                             case warning:

                           

                             if (trainArrivalCountDownMS < TIME_GATE_DOWN_BEFORE_TRAIN_MS) {

                           

                            Serial.println("\ngate warning -> lowering");

                           

                            crossingState = lowering;

                           

                            }

                           

                             break;

                           

                             case lowering:

                           

                             if (crossingPosition <= CROSSING_POSITION_LOWERED) {

                           

                            Serial.println("\ngate lowering -> down");

                           

                            crossingState = down; 

                           

                            } else {

                           

                            crossingPosition -= CROSSING_DEGREES_PER_CYCLE;

                           

                            }

                           

                             break;

                           

                             case down:

                           

                             if (trainDepartureCountDownMS <= 0) {

                           

                            Serial.println("\n(expected train departure from gate)");

                           

                            Serial.println("\ngate down -> raising");

                           

                            crossingState = raising;

                           

                            }

                           

                             break;

                           

                             case raising:

                           

                             if (crossingPosition >= CROSSING_POSITION_RAISED) {

                           

                            Serial.println("\ngate raising -> up");

                           

                            crossingState = up; 

                           

                            } else {

                           

                            crossingPosition += CROSSING_DEGREES_PER_CYCLE;

                           

                            }

                           

                             break;

                           

                            }

                           

                          }

                           

                           

                           

                           

                          /*

                           

                          We have one light to show the arrival countdown timer > 0 and

                           

                          another light to show the departure countdown timer > 0

                           

                          */

                           

                          void updateStatusLights() {

                           

                            if (trainArrivalCountDownMS > 0) {

                           

                             digitalWrite(PIN_STATUS_LIGHT_ARRIVAL, HIGH);

                           

                            } else {

                           

                             digitalWrite(PIN_STATUS_LIGHT_ARRIVAL, LOW);

                           

                            }

                           

                           

                           

                            if (trainDepartureCountDownMS > 0) {

                           

                             digitalWrite(PIN_STATUS_LIGHT_DEPARTURE, HIGH);

                           

                            } else {

                           

                             digitalWrite(PIN_STATUS_LIGHT_DEPARTURE, LOW);

                           

                            }

                           

                          }

                           

                           

                           

                          /*

                           

                          Helper to determine if the train is in the sensor

                           

                          */

                           

                          boolean isTrainPresentAtSensor() {

                           

                            int sensorValue = analogRead(PIN_SENSOR);

                           

                            // Serial.println(sensorValue);

                           

                            if (analogRead(PIN_SENSOR) > sensorThreshold) {

                           

                            Serial.print("S");

                           

                             return true;

                           

                            } else {

                           

                             return false;

                           

                            }

                           

                          }

                           

                           

                          /*

                           

                          We do a very simplistic calculation with the assumption that all

                           

                          trains move at the same speed. If we had a better sensor we could

                           

                          figure out how fast an individual train was going

                           

                          */

                           

                          int calculateTrainArrivalTimeMS() {

                           

                            return TRAIN_SPEED_MS_PER_SECTION * TRAIN_SECTIONS_TO_CROSSING;

                           

                          }

                           

                           

                           

                          /*

                           

                          Bells only ring during the initial warning and

                           

                          when the gate is lowering

                           

                          */

                           

                          void updateBells()

                           

                          {

                           

                            switch (crossingState) {

                           

                             case warning:

                           

                             case lowering:

                           

                             if (bellCycleCounter == 0) {

                           

                            Serial.print("(B!)");

                           

                             tone(PIN_BUZZER, BELL_TONE_FREQUENCY, BELL_DURATION);

                           

                            bellCycleCounter = BELL_RING_CYCLES;

                           

                            } else {

                           

                            bellCycleCounter--;

                           

                            }

                           

                             break;

                           

                            }

                           

                          }

                           

                           

                           

                          /*

                           

                          Lights flash continuously when the gate is not up

                           

                          */

                           

                          void updateLights()

                           

                          {

                           

                            switch (crossingState) {

                           

                             case up:

                           

                             digitalWrite(PIN_LEFT_LIGHT, LOW);

                           

                             digitalWrite(PIN_RIGHT_LIGHT, LOW);

                           

                             break;

                           

                             case warning:

                           

                             case lowering:

                           

                             case down:

                           

                             case raising:

                           

                             if (leftLightCycleCounter == 0) {

                           

                            Serial.print("(LL)");

                           

                             digitalWrite(PIN_LEFT_LIGHT, HIGH);

                           

                             digitalWrite(PIN_RIGHT_LIGHT, LOW);

                           

                            leftLightCycleCounter = LIGHT_BLINK_CYCLES;

                           

                            rightLightCycleCounter--;

                           

                            } else if (rightLightCycleCounter == 0) {

                           

                            Serial.print("(RL)");

                           

                             digitalWrite(PIN_LEFT_LIGHT, LOW);

                           

                             digitalWrite(PIN_RIGHT_LIGHT, HIGH);

                           

                            rightLightCycleCounter = LIGHT_BLINK_CYCLES;

                           

                            leftLightCycleCounter--;

                           

                            } else {

                           

                            leftLightCycleCounter--;

                           

                            rightLightCycleCounter--;

                           

                            }

                           

                             break;

                           

                            }

                           

                          }

                           

                           

                          /*

                           

                          Manage incremental changes to the servo position

                           

                          */

                           

                          void updateGatePosition()

                           

                          {

                           

                            switch (crossingState) {

                           

                             case lowering:

                           

                             if (crossingPosition > CROSSING_POSITION_LOWERED) {

                           

                            crossingPosition -= CROSSING_DEGREES_PER_CYCLE;

                           

                            gateServo.write(crossingPosition);  // Move to next position

                           

                            }

                           

                             break;

                           

                             case raising:

                           

                             if (crossingPosition < CROSSING_POSITION_RAISED) {

                           

                            crossingPosition += CROSSING_DEGREES_PER_CYCLE;

                           

                            gateServo.write(crossingPosition);  // Move to next position

                           

                            }

                           

                             break;

                           

                            }

                          }

                          /*
                            • Re: Please I need help Writing code
                              jomoenginer

                              Considering your lack of code development background, gabbing code examples might be causing more of an issue for you than it may solve.  My suggestion for you is to write out what you want the code to do.  You already have part of that in the initial description.  What I gather is that you want the railroad arms to drop, lights to flash and a bell to ring as the train passes a specific point where you have your reed switches placed.  The reed switches are what trigger the sequence and perhaps end the sequence on the other end. Is this what you are looking to do?

                               

                              Try writing out the sequence of events in plain English (or whatever your native language is) and step though the events as they should occur.

                               

                              Something like:

                              1. When the train passes point A, I want the reed switch to start the crossing arm down sequence.

                                   ( This gives you a clue that you need to enable a GPIO for the reed switch as well as either poll for the event or have it triggered by an interrupt)

                              2. I want the crossing arm down sequence to perform the following when reedSwitchA is activated.

                                 a. Enable LED flash behavior

                                 b. Start bell sound

                                 c. Enable servos and move crossing arms down.

                               

                              ... And so on.

                               

                              Then once you have an outline of what you want your code to perform, you can start dropping in the individual pieces.

                               

                              Start simple by just getting the reed switch to start the LED flash event.

                              Pseudo pseudo code.

                               

                                  if (reedSwitchA == 0)

                                     flash LEDs is true

                                 if (reedSwitchB == 0)

                                     flash LEDS is false

                               

                               

                              This is just an example but I think it may help you solve your coding project.

                               

                              From your first example, you want to take the flashing LED code that is listed prior to the reed switch reading and place it in a method(or rather function) and call this when the reed switch is activated.

                               

                              Or, the quick and dirty way, just move that code in the decision block for the reed switch:

                               

                              void loop() {
                              
                                int proximity = digitalRead(REED_PIN); // Read the state of the switch
                              
                                if (proximity == LOW) // If the pin reads low, the switch is closed.
                                {
                              
                                  Serial.println("Switch closed");
                              
                                  digitalWrite(LED_PIN, HIGH); // Turn the LED on
                                  digitalWrite(rd1LEDPin,HIGH); //turns led 1 on
                                  digitalWrite(rd2LEDPin,LOW); // turns led 2 off
                              
                                  delay (rd1onTime); //wait
                                  delay(rd2offTime); //wait
                              
                                  digitalWrite(rd1LEDPin,LOW); //turns led 1 off
                                  digitalWrite(rd2LEDPin,HIGH);//turns led 2 on
                              
                                  delay (rd1offTime);//  wait
                                  delay(rd2onTime);  //wait
                              
                                }
                              
                                else
                                {
                                  digitalWrite(LED_PIN, LOW); // Turn the LED off
                                }
                              

                               

                              Again, this is just an example and not how I would actually implement this.

                              3 of 3 people found this helpful
                              • Re: Please I need help Writing code
                                mcb1

                                When you paste code here, you paste it, then select all of it, and hit the >> symbol and choose Syntaxt Hightlighting, then C++.

                                During editing it may show everythign but as you'll see to others it's reduced.

                                It also allows line numbers in the post to be used.

                                 

                                */
                                 
                                #include 
                                
                                // Constants
                                const int CYCLE_PERIOD_MS = 10;
                                const int SENSOR_DELTA_THRESHOLD = 20;
                                const int BELL_RING_PERIOD = 400;
                                const int BELL_RING_CYCLES = BELL_RING_PERIOD / CYCLE_PERIOD_MS;
                                const int BELL_TONE_FREQUENCY = 300;
                                const int BELL_DURATION = 180;
                                const int LIGHT_BLINK_PERIOD = 1000;
                                const int LIGHT_BLINK_CYCLES = LIGHT_BLINK_PERIOD / CYCLE_PERIOD_MS;
                                const int LIGHT_BLINK_HALF_CYCLES = LIGHT_BLINK_CYCLES / 2;
                                const float CROSSING_POSITION_RAISED = 110.0;
                                const float CROSSING_POSITION_LOWERED = 15.0;
                                const float CROSSING_DEGREES_PER_CYCLE = 0.1;
                                const int TRAIN_SPEED_MS_PER_SECTION = 1000;
                                const int TRAIN_SECTIONS_TO_CROSSING = 13;
                                const int TIME_GATE_WARNING_BEFORE_TRAIN_MS = 7000;
                                const int TIME_GATE_DOWN_BEFORE_TRAIN_MS = 5000;
                                const int TIME_GATE_DOWN_AFTER_TRAIN_MS = 2000;
                                const int TIME_GATE_DOWN_BEFORE_TRAIN_CYCLES = TIME_GATE_DOWN_BEFORE_TRAIN_MS / CYCLE_PERIOD_MS;
                                const int TIME_GATE_DOWN_AFTER_TRAIN_CYCLES = TIME_GATE_DOWN_AFTER_TRAIN_MS / CYCLE_PERIOD_MS;
                                const int PIN_SENSOR = 0;
                                const int PIN_LEFT_LIGHT = 2;
                                const int PIN_RIGHT_LIGHT = 3;
                                const int PIN_STATUS_LIGHT_ARRIVAL = 4;
                                const int PIN_STATUS_LIGHT_DEPARTURE = 5;
                                const int PIN_BUZZER = 6;
                                const int PIN_SERVO = 7;
                                 
                                // Enums and globals
                                enum sensorState 
                                {
                                  out, entering, in, exiting
                                }
                                sensorState = out;
                                enum crossingState 
                                {
                                  up, warning, lowering, down, raising
                                }
                                
                                crossingState = up;
                                Servo gateServo;
                                nt sensorThreshold = 0;
                                long trainArrivalCountDownMS = 0;
                                long trainDepartureCountDownMS = 0;
                                int bellCycleCounter = 0;
                                int leftLightCycleCounter = 0;
                                int rightLightCycleCounter = LIGHT_BLINK_HALF_CYCLES;
                                float crossingPosition = CROSSING_POSITION_RAISED;
                                 
                                /*
                                One time initializations
                                */
                                
                                 
                                void setup()
                                {
                                  pinMode(PIN_LEFT_LIGHT, OUTPUT);
                                  pinMode(PIN_RIGHT_LIGHT, OUTPUT);
                                  pinMode(PIN_STATUS_LIGHT_ARRIVAL, OUTPUT);
                                  pinMode(PIN_STATUS_LIGHT_DEPARTURE, OUTPUT);
                                  pinMode(PIN_BUZZER, OUTPUT);
                                 
                                  // we assume that a train is not in the sensor at startup
                                
                                  sensorThreshold = analogRead(PIN_SENSOR) + SENSOR_DELTA_THRESHOLD;
                                  gateServo.attach(PIN_SERVO);
                                  gateServo.write(CROSSING_POSITION_RAISED);
                                  Serial.begin(9600);
                                
                                }
                                 
                                /*
                                 Main control loop.
                                 Check the sensor, update outputs, and then wait the cycle period.
                                */
                                 
                                void loop()
                                {
                                  checkSensor();
                                  updateTimers();
                                  updateStatusLights();
                                  updateCrossingState();
                                  updateBells();
                                  updateLights();
                                  updateGatePosition();
                                  delay(CYCLE_PERIOD_MS);
                                }
                                
                                 
                                /*
                                Check sensor and update transitions or states
                                */
                                
                                 
                                void checkSensor()
                                {
                                  if (isTrainPresentAtSensor()) 
                                  {
                                     switch (sensorState)
                                     {
                                     case in:
                                          // still in...
                                          break;
                                
                                     case entering:
                                          Serial.println("\nsensor -> in");
                                          sensorState = in;
                                          break;
                                     case out:
                                
                                     case exiting:
                                          Serial.println("\nsensor -> entering");
                                          sensorState = entering;
                                          break;
                                     }
                                
                                 
                                  } 
                                  else 
                                  {
                                    switch (sensorState)
                                    {
                                    case in:
                                    case entering:
                                         Serial.println("\nsensor -> exiting");
                                         sensorState = exiting;
                                         break;
                                
                                    case out:
                                         break;
                                
                                    case exiting:
                                         Serial.println("\nsensor -> out");
                                         sensorState = out;
                                         break;
                                    } 
                                 
                                  }
                                 
                                }
                                
                                 
                                /*
                                Set the timers when a train arrives,
                                increment the departure timer if a train is still in the sensor,
                                decrement the timers if a train is on its way
                                */
                                
                                 
                                void updateTimers() 
                                {
                                  switch (sensorState)
                                  {
                                  case in:
                                       trainDepartureCountDownMS += CYCLE_PERIOD_MS;
                                       break;
                                 
                                  case entering:
                                       // is this a new train or an additional train?
                                       if (trainDepartureCountDownMS > 0) 
                                       {
                                          // it is an additional train...
                                          // leave the arrival time as-is, add the time it takes for the new train to arrive on the departure timer
                                          Serial.println("\nAdditional train detected...");
                                          trainDepartureCountDownMS = calculateTrainArrivalTimeMS() + CYCLE_PERIOD_MS + TIME_GATE_DOWN_AFTER_TRAIN_MS; 
                                          // Serial.print("Arrival: ");
                                          // Serial.print(trainArrivalCountDownMS);
                                          // Serial.print("Departure: ");
                                          // Serial.println(trainDepartureCountDownMS); 
                                       }
                                       else 
                                       {
                                          // it is a new train...
                                          Serial.println("\nNew train detected...");
                                          trainArrivalCountDownMS = calculateTrainArrivalTimeMS();
                                          trainDepartureCountDownMS = trainArrivalCountDownMS + CYCLE_PERIOD_MS + TIME_GATE_DOWN_AFTER_TRAIN_MS;
                                          // Serial.print("Arrival: ");
                                          // Serial.print(trainArrivalCountDownMS);
                                          // Serial.print("Departure: ");
                                          // Serial.println(trainDepartureCountDownMS); 
                                        }
                                
                                 
                                  break;
                                
                                  case out: 
                                  case exiting:
                                       // do nothing additional
                                       break;
                                  }
                                
                                  if (trainArrivalCountDownMS > 0)
                                  {
                                     trainArrivalCountDownMS -= CYCLE_PERIOD_MS;
                                  }
                                
                                  if (trainDepartureCountDownMS > 0)
                                  {
                                     trainDepartureCountDownMS -= CYCLE_PERIOD_MS;
                                  }
                                
                                 
                                }
                                
                                /*
                                Manage crossing state transitions
                                */
                                 
                                void updateCrossingState()
                                {
                                  switch (crossingState)
                                  {
                                  case up:
                                       if ((trainDepartureCountDownMS > 0) && (trainArrivalCountDownMS < TIME_GATE_WARNING_BEFORE_TRAIN_MS))
                                       {
                                          Serial.println("\ngate up -> warning");
                                          crossingState = warning;
                                       }
                                  break;
                                
                                  case warning:
                                       if (trainArrivalCountDownMS < TIME_GATE_DOWN_BEFORE_TRAIN_MS)
                                       {
                                          Serial.println("\ngate warning -> lowering");
                                          crossingState = lowering;
                                       }
                                       break;
                                 
                                  case lowering:
                                       if (crossingPosition <= CROSSING_POSITION_LOWERED)
                                       {
                                          Serial.println("\ngate lowering -> down");
                                          crossingState = down; 
                                       }
                                       else
                                       {
                                          crossingPosition -= CROSSING_DEGREES_PER_CYCLE;
                                       }
                                       break;
                                 
                                   case down:
                                        if (trainDepartureCountDownMS <= 0)
                                        {
                                           Serial.println("\n(expected train departure from gate)");
                                           Serial.println("\ngate down -> raising");
                                           crossingState = raising;
                                        }
                                        break;
                                 
                                   case raising:
                                        if (crossingPosition >= CROSSING_POSITION_RAISED)
                                        {
                                           Serial.println("\ngate raising -> up");
                                           crossingState = up; 
                                        }
                                        else
                                        {
                                          crossingPosition += CROSSING_DEGREES_PER_CYCLE;
                                        }
                                        break;
                                
                                  }
                                
                                }
                                
                                 
                                /*
                                We have one light to show the arrival countdown timer > 0 and
                                another light to show the departure countdown timer > 0
                                */
                                
                                 
                                void updateStatusLights() 
                                {
                                  if (trainArrivalCountDownMS > 0)
                                  {
                                     digitalWrite(PIN_STATUS_LIGHT_ARRIVAL, HIGH);
                                  }
                                  else
                                  {
                                     digitalWrite(PIN_STATUS_LIGHT_ARRIVAL, LOW);
                                  }
                                
                                  if (trainDepartureCountDownMS > 0)
                                  {
                                     digitalWrite(PIN_STATUS_LIGHT_DEPARTURE, HIGH);
                                  }
                                  else
                                  {
                                     digitalWrite(PIN_STATUS_LIGHT_DEPARTURE, LOW);
                                  }
                                
                                }
                                
                                 
                                /*
                                Helper to determine if the train is in the sensor
                                */
                                 
                                boolean isTrainPresentAtSensor() 
                                {
                                   int sensorValue = analogRead(PIN_SENSOR);
                                   // Serial.println(sensorValue);
                                   if (analogRead(PIN_SENSOR) > sensorThreshold)
                                   {
                                     Serial.print("S");
                                     return true;
                                   }
                                   else
                                   {
                                      return false;
                                   }
                                  
                                }
                                
                                /*
                                We do a very simplistic calculation with the assumption that all
                                trains move at the same speed. If we had a better sensor we could
                                figure out how fast an individual train was going
                                */
                                
                                int calculateTrainArrivalTimeMS()
                                {
                                   return TRAIN_SPEED_MS_PER_SECTION * TRAIN_SECTIONS_TO_CROSSING;
                                }
                                
                                 
                                /*
                                Bells only ring during the initial warning and
                                when the gate is lowering
                                */
                                 
                                void updateBells()
                                {
                                  switch (crossingState)
                                  {
                                  case warning:
                                  case lowering:
                                       if (bellCycleCounter == 0)
                                       {
                                          Serial.print("(B!)");
                                          tone(PIN_BUZZER, BELL_TONE_FREQUENCY, BELL_DURATION);
                                          bellCycleCounter = BELL_RING_CYCLES;
                                       }
                                       else
                                       {
                                          bellCycleCounter--;
                                       }
                                       break;
                                  }
                                 
                                }
                                 
                                /*
                                Lights flash continuously when the gate is not up
                                */
                                
                                void updateLights()
                                {
                                  switch (crossingState)
                                  {
                                  case up:
                                       digitalWrite(PIN_LEFT_LIGHT, LOW);
                                       digitalWrite(PIN_RIGHT_LIGHT, LOW);
                                       break;
                                 
                                  case warning:
                                  case lowering: 
                                  case down:
                                  case raising:
                                       if (leftLightCycleCounter == 0)
                                       {
                                          Serial.print("(LL)");
                                          digitalWrite(PIN_LEFT_LIGHT, HIGH);
                                          digitalWrite(PIN_RIGHT_LIGHT, LOW);
                                          leftLightCycleCounter = LIGHT_BLINK_CYCLES;
                                          rightLightCycleCounter--;
                                       }
                                       else if (rightLightCycleCounter == 0) 
                                       {
                                         Serial.print("(RL)");
                                         digitalWrite(PIN_LEFT_LIGHT, LOW);
                                         digitalWrite(PIN_RIGHT_LIGHT, HIGH);
                                         rightLightCycleCounter = LIGHT_BLINK_CYCLES;
                                         leftLightCycleCounter--;
                                       }
                                       else
                                       {
                                         leftLightCycleCounter--;
                                         rightLightCycleCounter--;
                                       }
                                       break;
                                 
                                   }
                                
                                }
                                
                                 
                                /*
                                 Manage incremental changes to the servo position
                                */
                                
                                 
                                void updateGatePosition()
                                {
                                    switch (crossingState) 
                                    {
                                    case lowering:
                                          if (crossingPosition > CROSSING_POSITION_LOWERED) 
                                          {
                                             crossingPosition -= CROSSING_DEGREES_PER_CYCLE;
                                             gateServo.write(crossingPosition);  // Move to next position
                                           }
                                           break;
                                
                                    case raising:
                                         if (crossingPosition < CROSSING_POSITION_RAISED)
                                         {
                                            crossingPosition += CROSSING_DEGREES_PER_CYCLE;
                                            gateServo.write(crossingPosition);  // Move to next position
                                         }
                                         break;
                                
                                    }
                                }
                                /*

                                 

                                The code is interestng.

                                Not sure I've seen so many case statements used and each one has an If statement inside ... oh well.

                                 

                                the code has infrared sensors but in using reed switches and it has a timer that i don't need.  This is the code but i dont know how to change it to what i have wired and get rid of the timer and lcd ect..

                                You need to decide on a couple of pins that the reed switch connects to.

                                My personal preference is to have the switch go between the pin and ground, and use the internal pullup inside the controller.

                                The detection of that pin will trigger the code.

                                 

                                This is the piece of code that tells the sketch its detected a train.

                                 

                                /*
                                Helper to determine if the train is in the sensor
                                */
                                 
                                boolean isTrainPresentAtSensor() 
                                {
                                   int sensorValue = analogRead(PIN_SENSOR);
                                   // Serial.println(sensorValue);
                                   if (analogRead(PIN_SENSOR) > sensorThreshold)
                                   {
                                     Serial.print("S");
                                     return true;
                                   }
                                   else
                                   {
                                      return false;
                                   }
                                  
                                }

                                 

                                const int trainDetector = 8;  // reed switch to detect train is present
                                
                                
                                
                                
                                /*
                                Helper to determine if the train is in the sensor
                                */
                                 
                                boolean isTrainPresentAtSensor() 
                                {
                                   // Serial.println(sensorValue);
                                   if (digitalRead (trainDetector) == LOW)
                                   {
                                     Serial.print("S");
                                     return true;
                                   }
                                   else
                                   {
                                      return false;
                                   }
                                }

                                 

                                The above should get your reed switch working.

                                You'll need to add the const in about line 32 under the other declarations.

                                 

                                Change the code at line 34 to a digitalRead for the reed switch and it should detect the train.

                                 

                                 

                                I'm sure there will be some other snags, but see if that works for now and we can tackle the others later.

                                 

                                A small tip I find useful for these sorts of projects.

                                I tend to save the code with date_time in the name.

                                If I find I've gone backwards at some point, I have the earlier copy to resort to, or copy from.

                                 

                                 

                                Mark

                                3 of 3 people found this helpful
                        • Re: Please I need help Writing code
                          balearicdynamics

                          Hello Edward,

                           

                          I am sorry to miss your question, thanks to tariq.ahmad  now I am on the piece Don't worry we can easily solve your problem; BTW, maybe many users say that the problems are easy. I always found easy the problems I already know the solution

                           

                          I ask you a favor, please. Take a look in the editor features and add the code with Syntax Highlighting so I can easily copy and past it in one Arduino board here to make some test and solve it faster. It was my browser rendering wrond your sources, now I can see them correctly. So, go ahead.

                           

                          As far as I see lights may flash with your code but this approach IMHO may create difficulties implementing the other part, better if we use a couple of separate functions. Let me know as I am almost available to follow you these days.

                           

                          Wait for your code to try it together. What is the Birthday deadline?

                           

                          Enrico

                          2 of 2 people found this helpful
                            • Re: Please I need help Writing code
                              balearicdynamics

                              As waiting for your code I mean your last update after the mcb1 suggestions eventually applied.

                               

                              Enrico

                              1 of 1 people found this helpful
                                • Re: Please I need help Writing code
                                  theshay
                                  [code]
                                  /*
                                  Railroad crossing controller
                                  */
                                  #include 
                                  
                                  // Constants
                                  const int CYCLE_PERIOD_MS = 10;
                                  
                                  const int SENSOR_DELTA_THRESHOLD = 20;
                                  
                                  const int BELL_RING_PERIOD = 400;
                                  const int BELL_RING_CYCLES = BELL_RING_PERIOD / CYCLE_PERIOD_MS;
                                  const int BELL_TONE_FREQUENCY = 300;
                                  const int BELL_DURATION = 180;
                                  
                                  const int LIGHT_BLINK_PERIOD = 1000;
                                  const int LIGHT_BLINK_CYCLES = LIGHT_BLINK_PERIOD / CYCLE_PERIOD_MS;
                                  const int LIGHT_BLINK_HALF_CYCLES = LIGHT_BLINK_CYCLES / 2;
                                  
                                  const float CROSSING_POSITION_RAISED = 110.0;
                                  const float CROSSING_POSITION_LOWERED = 15.0;
                                  const float CROSSING_DEGREES_PER_CYCLE = 0.1;
                                  
                                  const int TRAIN_SPEED_MS_PER_SECTION = 1000;
                                  const int TRAIN_SECTIONS_TO_CROSSING = 13;
                                  
                                  const int TIME_GATE_WARNING_BEFORE_TRAIN_MS = 7000;
                                  const int TIME_GATE_DOWN_BEFORE_TRAIN_MS = 5000;
                                  const int TIME_GATE_DOWN_AFTER_TRAIN_MS = 2000;
                                  const int TIME_GATE_DOWN_BEFORE_TRAIN_CYCLES = TIME_GATE_DOWN_BEFORE_TRAIN_MS / CYCLE_PERIOD_MS;
                                  const int TIME_GATE_DOWN_AFTER_TRAIN_CYCLES = TIME_GATE_DOWN_AFTER_TRAIN_MS / CYCLE_PERIOD_MS;
                                  
                                  const int PIN_SENSOR = 0;
                                  const int PIN_LEFT_LIGHT = 2;
                                  const int PIN_RIGHT_LIGHT = 3;
                                  const int PIN_STATUS_LIGHT_ARRIVAL = 4;
                                  const int PIN_STATUS_LIGHT_DEPARTURE = 5;
                                  const int PIN_BUZZER = 6;
                                  const int PIN_SERVO = 7;
                                  
                                  // Enums and globals
                                  enum sensorState {
                                    out, entering, in, exiting
                                  }
                                  sensorState = out;
                                  
                                  enum crossingState {
                                    up, warning, lowering, down, raising
                                  }
                                  crossingState = up;
                                  
                                  Servo gateServo;
                                  int sensorThreshold = 0;
                                  long trainArrivalCountDownMS = 0;
                                  long trainDepartureCountDownMS = 0;
                                  int bellCycleCounter = 0;
                                  int leftLightCycleCounter = 0;
                                  int rightLightCycleCounter = LIGHT_BLINK_HALF_CYCLES;
                                  float crossingPosition = CROSSING_POSITION_RAISED;
                                  
                                  
                                  /*
                                  One time initializations
                                  */
                                  void setup()
                                  {
                                    pinMode(PIN_LEFT_LIGHT, OUTPUT);
                                    pinMode(PIN_RIGHT_LIGHT, OUTPUT);
                                    pinMode(PIN_STATUS_LIGHT_ARRIVAL, OUTPUT);
                                    pinMode(PIN_STATUS_LIGHT_DEPARTURE, OUTPUT);
                                    pinMode(PIN_BUZZER, OUTPUT);
                                   
                                    // we assume that a train is not in the sensor at startup
                                    sensorThreshold = analogRead(PIN_SENSOR) + SENSOR_DELTA_THRESHOLD;
                                  
                                    gateServo.attach(PIN_SERVO);
                                    gateServo.write(CROSSING_POSITION_RAISED);
                                  
                                    Serial.begin(9600);
                                  }
                                  
                                  /*
                                  Main control loop.
                                  Check the sensor, update outputs, and then wait the cycle period.
                                  */
                                  void loop()
                                  {
                                    checkSensor();
                                    updateTimers();
                                    updateStatusLights();
                                    updateCrossingState();
                                    updateBells();
                                    updateLights();
                                    updateGatePosition();
                                    delay(CYCLE_PERIOD_MS);
                                  }
                                  
                                  
                                  /*
                                   Check sensor and update transitions or states
                                   */
                                  void checkSensor()
                                  {
                                    if (isTrainPresentAtSensor()) {
                                      switch (sensorState) {
                                        case in:
                                          // still in...
                                          break;
                                        case entering:
                                          Serial.println("\nsensor -> in");
                                          sensorState = in;
                                          break;
                                        case out:
                                        case exiting:
                                          Serial.println("\nsensor -> entering");
                                          sensorState = entering;
                                          break;
                                      }
                                    } else {
                                      switch (sensorState) {
                                        case in:
                                        case entering:
                                          Serial.println("\nsensor -> exiting");
                                          sensorState = exiting;
                                          break;
                                        case out:
                                          break;
                                        case exiting:
                                          Serial.println("\nsensor -> out");
                                          sensorState = out;
                                          break;
                                      }  
                                    }
                                  }
                                  
                                  /*
                                   Set the timers when a train arrives,
                                   increment the departure timer if a train is still in the sensor,
                                   decrement the timers if a train is on its way
                                   */
                                  void updateTimers() {
                                    switch (sensorState) {
                                      case in:
                                        trainDepartureCountDownMS += CYCLE_PERIOD_MS;
                                        break;
                                      case entering:
                                        // is this a new train or an additional train?
                                        if (trainDepartureCountDownMS > 0) {
                                          // it is an additional train...
                                          // leave the arrival time as-is, add the time it takes for the new train to arrive on the departure timer
                                          Serial.println("\nAdditional train detected...");
                                          trainDepartureCountDownMS = calculateTrainArrivalTimeMS() + CYCLE_PERIOD_MS + TIME_GATE_DOWN_AFTER_TRAIN_MS;  
                                          // Serial.print("Arrival: ");
                                          // Serial.print(trainArrivalCountDownMS);
                                          // Serial.print("Departure: ");
                                          // Serial.println(trainDepartureCountDownMS);  
                                        } else {
                                          // it is a new train...
                                          Serial.println("\nNew train detected...");
                                          trainArrivalCountDownMS = calculateTrainArrivalTimeMS();
                                          trainDepartureCountDownMS = trainArrivalCountDownMS + CYCLE_PERIOD_MS + TIME_GATE_DOWN_AFTER_TRAIN_MS;
                                          // Serial.print("Arrival: ");
                                          // Serial.print(trainArrivalCountDownMS);
                                          // Serial.print("Departure: ");
                                          // Serial.println(trainDepartureCountDownMS);  
                                        }
                                        break;
                                      case out:    
                                      case exiting:
                                       // do nothing additional
                                       break;
                                    }
                                   
                                    if (trainArrivalCountDownMS > 0) {
                                      trainArrivalCountDownMS -= CYCLE_PERIOD_MS;
                                    }
                                   
                                    if (trainDepartureCountDownMS > 0) {
                                      trainDepartureCountDownMS -= CYCLE_PERIOD_MS;
                                    }
                                  }
                                   
                                  
                                  /*
                                   Manage crossing state transitions
                                   */
                                  void updateCrossingState() {
                                    switch (crossingState) {
                                      case up:
                                        if ((trainDepartureCountDownMS > 0) && (trainArrivalCountDownMS < TIME_GATE_WARNING_BEFORE_TRAIN_MS)) {
                                          Serial.println("\ngate up -> warning");
                                          crossingState = warning;
                                        }
                                        break;
                                      case warning:
                                        if (trainArrivalCountDownMS < TIME_GATE_DOWN_BEFORE_TRAIN_MS) {
                                          Serial.println("\ngate warning -> lowering");
                                          crossingState = lowering;
                                        }
                                        break;
                                      case lowering:
                                        if (crossingPosition <= CROSSING_POSITION_LOWERED) {
                                          Serial.println("\ngate lowering -> down");
                                          crossingState = down;      
                                        } else {
                                          crossingPosition -= CROSSING_DEGREES_PER_CYCLE;
                                        }
                                        break;
                                      case down:
                                        if (trainDepartureCountDownMS <= 0) {
                                          Serial.println("\n(expected train departure from gate)");
                                          Serial.println("\ngate down -> raising");
                                          crossingState = raising;
                                        }
                                        break;
                                      case raising:
                                        if (crossingPosition >= CROSSING_POSITION_RAISED) {
                                          Serial.println("\ngate raising -> up");
                                          crossingState = up;      
                                        } else {
                                          crossingPosition += CROSSING_DEGREES_PER_CYCLE;
                                        }
                                        break;
                                    }
                                  }
                                  
                                  
                                  
                                  /*
                                  We have one light to show the arrival countdown timer > 0 and
                                  another light to show the departure countdown timer > 0
                                   */
                                  void updateStatusLights() {
                                    if (trainArrivalCountDownMS > 0) {
                                      digitalWrite(PIN_STATUS_LIGHT_ARRIVAL, HIGH);
                                    } else {
                                      digitalWrite(PIN_STATUS_LIGHT_ARRIVAL, LOW);
                                    }
                                    
                                    if (trainDepartureCountDownMS > 0) {
                                      digitalWrite(PIN_STATUS_LIGHT_DEPARTURE, HIGH);
                                    } else {
                                      digitalWrite(PIN_STATUS_LIGHT_DEPARTURE, LOW);
                                    }
                                  }
                                  
                                  
                                  /*
                                  Helper to determine if the train is in the sensor
                                  */
                                  boolean isTrainPresentAtSensor() {
                                    int sensorValue = analogRead(PIN_SENSOR);
                                    // Serial.println(sensorValue);
                                    if (analogRead(PIN_SENSOR) > sensorThreshold) {
                                      Serial.print("S");
                                      return true;
                                    } else {
                                      return false;
                                    }
                                  }
                                  
                                  /*
                                  We do a very simplistic calculation with the assumption that all
                                  trains move at the same speed.  If we had a better sensor we could
                                  figure out how fast an individual train was going
                                  */
                                  int calculateTrainArrivalTimeMS() {
                                    return TRAIN_SPEED_MS_PER_SECTION * TRAIN_SECTIONS_TO_CROSSING;
                                  }
                                  
                                  
                                  /*
                                  Bells only ring during the initial warning and
                                  when the gate is lowering
                                  */
                                  void updateBells()
                                  {
                                    switch (crossingState) {
                                      case warning:
                                      case lowering:
                                        if (bellCycleCounter == 0) {
                                          Serial.print("(B!)");
                                          tone(PIN_BUZZER, BELL_TONE_FREQUENCY, BELL_DURATION);
                                          bellCycleCounter = BELL_RING_CYCLES;
                                        } else {
                                          bellCycleCounter--;
                                        }
                                        break;
                                    }
                                  }
                                  
                                  
                                  /*
                                  Lights flash continuously when the gate is not up
                                  */
                                  void updateLights()
                                  {
                                    switch (crossingState) {
                                      case up:
                                        digitalWrite(PIN_LEFT_LIGHT, LOW);
                                        digitalWrite(PIN_RIGHT_LIGHT, LOW);
                                        break;
                                      case warning:
                                      case lowering:
                                      case down:
                                      case raising:
                                        if (leftLightCycleCounter == 0) {
                                          Serial.print("(LL)");
                                          digitalWrite(PIN_LEFT_LIGHT, HIGH);
                                          digitalWrite(PIN_RIGHT_LIGHT, LOW);
                                          leftLightCycleCounter = LIGHT_BLINK_CYCLES;
                                          rightLightCycleCounter--;
                                        } else if (rightLightCycleCounter == 0) {
                                          Serial.print("(RL)");
                                          digitalWrite(PIN_LEFT_LIGHT, LOW);
                                          digitalWrite(PIN_RIGHT_LIGHT, HIGH);
                                            rightLightCycleCounter = LIGHT_BLINK_CYCLES;
                                          leftLightCycleCounter--;
                                        } else {
                                          leftLightCycleCounter--;
                                          rightLightCycleCounter--;
                                        }
                                        break;
                                    }
                                  }
                                  
                                  /*
                                  Manage incremental changes to the servo position
                                  */
                                  void updateGatePosition()
                                  {
                                    switch (crossingState) {
                                       case lowering:
                                         if (crossingPosition > CROSSING_POSITION_LOWERED) {
                                           crossingPosition -= CROSSING_DEGREES_PER_CYCLE;
                                           gateServo.write(crossingPosition);  // Move to next position
                                         }
                                         break;
                                       case raising:
                                         if (crossingPosition < CROSSING_POSITION_RAISED) {
                                           crossingPosition += CROSSING_DEGREES_PER_CYCLE;
                                           gateServo.write(crossingPosition);  // Move to next position
                                         }
                                         break;
                                    }
                                  }
                                  [/code]

                                  this is the code i found that i would like to altar to my needs but unsure how to do it i have no coding experience I can tell you where i have things plugged but not sure how to altar to my needs

                                  pin 2,3 are the leds pins 5.6 are servo pin 9 to act as switch to activate external sound card pins 4,7 will be the reed switches servos have external powersource

                                    • Re: Please I need help Writing code
                                      theshay

                                      oh and the birthday is may second.Thats why im freaking out to get this finished i have been building the table for 3 months its down to the finishing touches, applying trees and detail and getting these crossing gates to work. I tried going through a few tutorials an how to code but i cant learn fast enough. Its tough to teach an old dog new tricks. LOL

                                        • Re: Please I need help Writing code
                                          balearicdynamics

                                          Ok, I should finish something before then this evening I will try to put your code on Arduino and see what it does.

                                           

                                          Enrico

                                          1 of 1 people found this helpful
                                            • Re: Please I need help Writing code
                                              theshay

                                              Enrico,

                                                   Not sure if you had a chance to look at the new code and schematic I posted. I think it would be easier to modify because it is closest to what i am looking for. it only needs the switches added. Unfortunately Ive been trying to figure it out myself but just not getting it. Everyone has advice but I don't think they understand I know nothing about writing code. I wish i had more time to learn, going forward I will be doing more tutorials Because I really like the possibilities of the Arduino system and am interested in learning but for now im in a jam. I appreciate any and all help you can give me. Again I would like to thank you for your time, as I'm sure you have better things to do.

                                                • Re: Please I need help Writing code
                                                  balearicdynamics

                                                  Great! Really, a nice scenario I finally I am closing my stuff tonight and thanks God tomorrow morning I can put your code on an Arduino, then test what's happens. I hope I have not delayed too much and this can be helpful to you.

                                                   

                                                  Enrico

                                                  1 of 1 people found this helpful
                                                    • Re: Please I need help Writing code
                                                      theshay

                                                      Enrico,

                                                           No problem brother I appreciate your help. still plenty of time i have almost two weeks to finish up. I ordered a few more things off line to add they should be here by the weekend. I am adding camping tents and campers around the two fire pits, one is on the mountain looks like a black circle, it is actually lighted just not wired yet. to wire everything will only take me 1 day, I also ordered more street lights to put around the track those are all working lights too just like the ones in the beach parking lot. the empty corner to the lower right is where the petrol station is going. I am building that with foam core board and printed designs. All of the grass is stained saw dust instead of spending 30 bucks or more just for fake grass. trees are branches cut from a bush and glued deer moss and painted. The reeds along the lake side are chip brushes taken apart then glued the bristles into clusters.  All of the miniature people I ordered off wish.com for 2 bucks free shipping. Arduino card from wish for 5 bucks and a clear case for Arduino 2 bucks on wish. The street lamps I got 20 for 10 bucks on wish.comThe parking-lot and roads are printed then glued on foam core. The power to run everything with plenty of add on room is a 200watt computer supply converted into 3v, 5, 12v outputs all packed neatly into a service box used to be old fuse box for my garage. the train, not all shown I have had since the mid 80's. The slot car track I bought 2 years ago for my grandson to play with when he visits. He keeps asking me where it is and can he play with it. I,m so excited I can't wait to see the look on his face when he sees what grandpa has made for him. :-))

                                                    • Re: Please I need help Writing code
                                                      14rhb

                                                      Edward,

                                                       

                                                      That is a great setup you have there.

                                                       

                                                      Rod

                                              • Re: Please I need help Writing code
                                                theshay

                                                my electrical wiring for train layout

                                                1 of 1 people found this helpful
                                                  • Re: Please I need help Writing code
                                                    balearicdynamics

                                                    Great! This helps me a lot

                                                     

                                                    Enrico

                                                      • Re: Please I need help Writing code
                                                        theshay

                                                        I found a different set up real close to what i want. I dont know how to add the reed switches and eliminate the yellow light

                                                        • Re: Please I need help Writing code
                                                          theshay
                                                          [code]
                                                          //Level_crossing
                                                          
                                                          #include <Servo.h>
                                                           Servo myservo1; // create servo object to control a servo
                                                           Servo myservo2;
                                                           // a maximum of eight servo objects can be created
                                                           int pos = 0; // variable to store the servo position
                                                           int led1 = 11 ;// define RED2 LED Interface
                                                           int led2 = 10 ;// define RED1 LED Interface
                                                           int led3 = 9 ;// define Yellow LED Interface
                                                           int buttonpin = 3; // define the obstacle avoidance sensor interface
                                                           int val ;// define numeric variables val
                                                           void setup ()
                                                           {
                                                           pinMode (led1, OUTPUT) ;// define LED as output interface
                                                           pinMode (led2, OUTPUT) ;// define LED as output interface
                                                           pinMode (led3, OUTPUT) ;// define LED as output interface
                                                           pinMode (buttonpin, INPUT) ;// define the obstacle avoidance sensor output interface
                                                           myservo1.attach(8); // attaches the servo on pin 9 to the servo object
                                                           myservo2.attach(7); // attaches the servo on pin 8 to the servo object
                                                           }
                                                           void loop ()
                                                           {
                                                           val = digitalRead (buttonpin) ;// digital interface will be assigned a value of 3 to read val
                                                           if (val == LOW) // When the obstacle avoidance sensor detects a signal, LED flashes
                                                           {
                                                           myservo1.write(90); // tell servo to go to position in variable 'pos'
                                                           myservo2.write(90);
                                                           flashLights();
                                                          
                                                           }
                                                           else
                                                             
                                                           {
                                                           myservo1.write(0); // tell servo to go to position in variable 'pos'
                                                           myservo2.write(0);
                                                           digitalWrite (led1, LOW);
                                                           digitalWrite (led2, LOW);
                                                           digitalWrite (led3, LOW);
                                                           }
                                                          }
                                                          void flashLights() {
                                                           digitalWrite(led3, HIGH); // turn the LED on (HIGH is the voltage level)
                                                           delay(2000); // wait for a second
                                                           digitalWrite(led3, LOW); // turn the LED off by making the voltage LOW
                                                          
                                                           digitalWrite(led1, HIGH); // turn the LED on (HIGH is the voltage level)
                                                           delay(200); // wait for a second
                                                           digitalWrite(led1, LOW); // turn the LED off by making the voltage LOW
                                                          
                                                           digitalWrite(led2, HIGH); // turn the LED on (HIGH is the voltage level)
                                                           delay(200); // wait for a second
                                                           digitalWrite(led2, LOW); // turn the LED off by making the voltage LOW
                                                          
                                                           digitalWrite(led1, HIGH); // turn the LED on (HIGH is the voltage level)
                                                           delay(200); // wait for a second
                                                           digitalWrite(led1, LOW); // turn the LED off by making the voltage LOW
                                                          
                                                           digitalWrite(led2, HIGH); // turn the LED on (HIGH is the voltage level)
                                                           delay(200); // wait for a second
                                                           digitalWrite(led2, LOW); // turn the LED off by making the voltage LOW
                                                          
                                                           digitalWrite(led1, HIGH); // turn the LED on (HIGH is the voltage level)
                                                           delay(200); // wait for a second
                                                           digitalWrite(led1, LOW); // turn the LED off by making the voltage LOW
                                                          
                                                           digitalWrite(led2, HIGH); // turn the LED on (HIGH is the voltage level)
                                                           delay(200); // wait for a second
                                                           digitalWrite(led2, LOW); // turn the LED off by making the voltage LOW
                                                            
                                                            digitalWrite(led1, HIGH); // turn the LED on (HIGH is the voltage level)
                                                           delay(200); // wait for a second
                                                           digitalWrite(led1, LOW); // turn the LED off by making the voltage LOW
                                                          
                                                           digitalWrite(led2, HIGH); // turn the LED on (HIGH is the voltage level)
                                                           delay(200); // wait for a second
                                                           digitalWrite(led2, LOW); // turn the LED off by making the voltage LOW
                                                          
                                                           digitalWrite(led1, HIGH); // turn the LED on (HIGH is the voltage level)
                                                           delay(200); // wait for a second
                                                           digitalWrite(led1, LOW); // turn the LED off by making the voltage LOW
                                                          
                                                           digitalWrite(led2, HIGH); // turn the LED on (HIGH is the voltage level)
                                                           delay(200); // wait for a second
                                                           digitalWrite(led2, LOW); // turn the LED off by making the voltage LOW
                                                          
                                                           digitalWrite(led3, HIGH); // turn the LED on (HIGH is the voltage level)
                                                           delay(1000); // wait for a second
                                                           digitalWrite(led3, LOW); // turn the LED off by making the voltage LOW
                                                          }
                                                          [/code]
                                                          
                                                            • Re: Please I need help Writing code
                                                              balearicdynamics

                                                              Hi, is this the most recent code you have issues on?

                                                               

                                                              Than you. Enrico

                                                              • Re: Please I need help Writing code
                                                                theshay

                                                                well to be honest ive been trying to write the code my self since we last talked What i put together needs the two switches and servos added I was following a couple tutorials I can give you that it doesnt matter what ever is easier for you

                                                                1 of 1 people found this helpful
                                                                  • Re: Please I need help Writing code
                                                                    balearicdynamics

                                                                    Hi,

                                                                     

                                                                    don't worry, it's better trying and making a lot of errors but learning than copying and pasting. So I have started fro your last code, cleaning it a while and optimizing step by step. I'll keep you updated.

                                                                     

                                                                    First, I have created parameters.h header file. All the constant that you define as variables are better put as #define, it saves memory and processor time. Then I have used some loop to make the flash LEDs function shorter.

                                                                     

                                                                    The new flashing sequence is here:

                                                                     

                                                                    // LED flashing sequence
                                                                    void flashLights() {
                                                                      int j;
                                                                    
                                                                    
                                                                      // Light yellow LED
                                                                      digitalWrite(YELLOW, HIGH); // turn the LED on (HIGH is the voltage level)
                                                                      delay(LONG_DELAY); // wait for a second
                                                                      digitalWrite(YELLOW, LOW); // turn the LED off by making the voltage LOW
                                                                    
                                                                    
                                                                      // Two red LEDs cycle
                                                                      for(j = 0; j < RED_FLASHING_CYCLE; j++) {
                                                                        
                                                                        digitalWrite(RED2, HIGH); // turn the LED on (HIGH is the voltage level)
                                                                        delay(SHORT_DELAY); // wait for a second
                                                                        digitalWrite(RED2, LOW); // turn the LED off by making the voltage LOW
                                                                        
                                                                        digitalWrite(RED1, HIGH); // turn the LED on (HIGH is the voltage level)
                                                                        delay(SHORT_DELAY); // wait for a second
                                                                        digitalWrite(RED1, LOW); // turn the LED off by making the voltage LOW
                                                                      } // End LEDs flashing loop
                                                                     
                                                                      digitalWrite(YELLOW, HIGH); // turn the LED on (HIGH is the voltage level)
                                                                      delay(MID_DELAY); // wait for a second
                                                                      digitalWrite(YELLOW, LOW); // turn the LED off by making the voltage LOW
                                                                    }

                                                                     

                                                                    Going ahead

                                                                    • Re: Please I need help Writing code
                                                                      balearicdynamics

                                                                      Until now, the new function for LEDs works fine. Please can you tell me the issue ? Are the two servos not working?

                                                                       

                                                                      Enrico

                                                                      • Re: Please I need help Writing code
                                                                        balearicdynamics

                                                                        Hello Edward.

                                                                         

                                                                        Now button (that replace the reed sensor but the code remains unchanged) and the servos (I have only one here but it should work with two as well) moves accordingly.

                                                                         

                                                                        This is the code:

                                                                         

                                                                        //Level_crossing
                                                                        
                                                                        
                                                                        #include "parameters.h"
                                                                        
                                                                        
                                                                        Servo myservo1; // create servo object to control a servo
                                                                        Servo myservo2;
                                                                        
                                                                        
                                                                         void setup (){
                                                                        
                                                                        
                                                                          pinMode (RED2, OUTPUT) ;// define LED as output interface
                                                                          pinMode (RED1, OUTPUT) ;// define LED as output interface
                                                                          pinMode (YELLOW, OUTPUT) ;// define LED as output interface
                                                                          
                                                                          pinMode (OBSTACLE_AVOIDANCE_SENSOR_PIN, INPUT_PULLUP);
                                                                          
                                                                          myservo1.attach(8);
                                                                          myservo2.attach(7);
                                                                          }
                                                                        
                                                                        
                                                                         void loop (){
                                                                         
                                                                          // When the obstacle avoidance sensor detects a signal, LED flashes
                                                                          if (digitalRead(OBSTACLE_AVOIDANCE_SENSOR_PIN) == LOW) {
                                                                            myservo1.write(SERVO_ALERT); // tell servo to go to position in variable 'pos'
                                                                            myservo2.write(SERVO_ALERT);
                                                                            flashLights();
                                                                            }
                                                                            else {
                                                                              myservo1.write(SERVO_PAUSE);
                                                                              myservo2.write(SERVO_PAUSE);
                                                                              digitalWrite (RED2, LOW);
                                                                              digitalWrite (RED1, LOW);
                                                                              digitalWrite (YELLOW, LOW);
                                                                            }
                                                                        }
                                                                        
                                                                        
                                                                        // LED flashing sequence
                                                                        void flashLights() {
                                                                          int j;
                                                                        
                                                                        
                                                                          // Light yellow LED
                                                                          digitalWrite(YELLOW, HIGH); // turn the LED on (HIGH is the voltage level)
                                                                          delay(LONG_DELAY); // wait for a second
                                                                          digitalWrite(YELLOW, LOW); // turn the LED off by making the voltage LOW
                                                                        
                                                                        
                                                                          // Two red LEDs cycle
                                                                          for(j = 0; j < RED_FLASHING_CYCLE; j++) {
                                                                            
                                                                            digitalWrite(RED2, HIGH); // turn the LED on (HIGH is the voltage level)
                                                                            delay(SHORT_DELAY); // wait for a second
                                                                            digitalWrite(RED2, LOW); // turn the LED off by making the voltage LOW
                                                                            
                                                                            digitalWrite(RED1, HIGH); // turn the LED on (HIGH is the voltage level)
                                                                            delay(SHORT_DELAY); // wait for a second
                                                                            digitalWrite(RED1, LOW); // turn the LED off by making the voltage LOW
                                                                          } // End LEDs flashing loop
                                                                         
                                                                          digitalWrite(YELLOW, HIGH); // turn the LED on (HIGH is the voltage level)
                                                                          delay(MID_DELAY); // wait for a second
                                                                          digitalWrite(YELLOW, LOW); // turn the LED off by making the voltage LOW
                                                                        }

                                                                         

                                                                        And this is parameters.h

                                                                         

                                                                        // Constants and application parameters
                                                                        #include 
                                                                        
                                                                        
                                                                        #define LONG_DELAY 2000     // Long delay in LED flashing sequence
                                                                        #define MID_DELAY 1000      // Mid duration delay
                                                                        #define SHORT_DELAY 200     // Short delay in LED flashing sequence
                                                                        
                                                                        
                                                                        #define RED2 11   // RED2 LED
                                                                        #define RED1 10   // RED1 LED
                                                                        #define YELLOW 9  // Yellow LED
                                                                        
                                                                        
                                                                        #define RED_FLASHING_CYCLE 5  // Red LEDs flashing loop duration
                                                                        
                                                                        
                                                                        #define SERVO1 7    // Pin servo 1
                                                                        #define SERVO2 8    // Pin servo 2
                                                                        
                                                                        
                                                                        #define SERVO_ALERT 90    // Servo position alert (maybe vice-versa)
                                                                        #define SERVO_PAUSE 0     // Servo position pause
                                                                        
                                                                        
                                                                        #define OBSTACLE_AVOIDANCE_SENSOR_PIN 3
                                                                        1 of 1 people found this helpful
                                                                          • Re: Please I need help Writing code
                                                                            theshay

                                                                            Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"

                                                                             

                                                                            C:\Users\Edward\Desktop\rr patterns\my edit crossing bell and lights\RR_Crossing_Bell_Synched_my_edit_1\RR_Crossing_Bell_Synched_my_edit_19\RR_Crossing_Bell_Synched_my_edit_19.ino:3:30: fatal error: parameters.h: No such file or directory

                                                                             

                                                                                 #include "parameters.h" 

                                                                             

                                                                                                          ^

                                                                             

                                                                            compilation terminated.

                                                                             

                                                                            exit status 1

                                                                            Error compiling for board Arduino/Genuino Uno.

                                                                             

                                                                            This report would have more information with

                                                                            "Show verbose output during compilation"

                                                                            option enabled in File -> Preferences.

                                                                            • Re: Please I need help Writing code
                                                                              theshay

                                                                              ok now i get

                                                                              Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"

                                                                               

                                                                              In file included from C:\Users\Edward\Desktop\rr patterns\my edit crossing bell and lights\RR_Crossing_Bell_Synched_my_edit_1\RR_Crossing_Bell_Synched_my_edit_19\RR_Crossing_Bell_Synched_my_edit_19.ino:4:0:

                                                                               

                                                                              parameters.h:2: error: #include expects "FILENAME" or <FILENAME>

                                                                               

                                                                                                               #include 

                                                                               

                                                                                                                         ^

                                                                               

                                                                              exit status 1

                                                                              #include expects "FILENAME" or <FILENAME>

                                                                               

                                                                              This report would have more information with

                                                                              "Show verbose output during compilation"

                                                                              option enabled in File -> Preferences.

                                                                               

                                                                              i have to got to dr appointment now will be back in 2 hrs if you are still up we can continue if not maybe tomorrow. Thank you Enrico for your help you have been a blessing :-)))

                                                                          • Re: Please I need help Writing code
                                                                            balearicdynamics

                                                                            Hi Edward,

                                                                             

                                                                            I am trying to setup your circuit on my Arduino and run your code now.

                                                                             

                                                                            Enrico

                                                                              • Re: Please I need help Writing code
                                                                                theshay
                                                                                /* Railroad crossing using two reed switches one turns on 2 turns off
                                                                                 *  two servos to rais and lower gates from 0 degrees(gates closed) to 50 degrees(gates open)
                                                                                 *  sw1 will activate loop(lights sound and lower gates).
                                                                                 *  sw2 will stop loop and raise gates
                                                                                 */
                                                                                //
                                                                                #define delta   540    // 0.540 seconds on and off
                                                                                #define bstrobe  60
                                                                                //
                                                                                #define led_pin1    11    // the Crossing LED is attached to pin 11
                                                                                #define led_pin2    12    // the Crossing LED is attached to pin 12
                                                                                #define control_pin1 14    //Control Pin is Pin 14 (A0) Low/Ground is OFF reedswitch
                                                                                #define control_pin2 16    //Control Pin  16 (A2) reed switch 2
                                                                                                         // OPEN (Unattachd) Pin is off
                                                                                #define bell_pin    15    // D15 == A1  This is the signal for the single Bell
                                                                                
                                                                                void setup() {
                                                                                  // initialize led_pin as digital output pin
                                                                                  pinMode(led_pin1, OUTPUT);
                                                                                  pinMode(led_pin2, OUTPUT);
                                                                                  pinMode(bell_pin, OUTPUT);
                                                                                  digitalWrite(bell_pin, HIGH);
                                                                                  pinMode(control_pin1,INPUT_PULLUP); 
                                                                                  pinMode(control_pin2,INPUT_PULLUP);
                                                                                }
                                                                                
                                                                                // the loop function runs over and over again forever
                                                                                void loop() {
                                                                                    if (digitalRead(control_pin1)==LOW) {
                                                                                        digitalWrite(led_pin1, HIGH);   // turn the LED on (HIGH is the voltage level)
                                                                                        digitalWrite(led_pin2, LOW);   // turn the LED off (low is the voltage level)
                                                                                        digitalWrite(bell_pin, LOW);    // turn the LED off (low is the voltage level)
                                                                                        delay(bstrobe);
                                                                                        digitalWrite(bell_pin, HIGH);
                                                                                        delay(delta);              // wait for a second
                                                                                        digitalWrite(led_pin1, LOW);    // turn the LED off by making the voltage LOW
                                                                                        digitalWrite(led_pin2, HIGH);   // turn the LED on (HIGH is the voltage level)
                                                                                        digitalWrite(bell_pin, LOW);
                                                                                        delay(bstrobe);
                                                                                        digitalWrite(bell_pin, HIGH);
                                                                                        delay(delta);              // wait for a second
                                                                                    } else {
                                                                                    (digitalRead(control_pin2)==LOW)
                                                                                    digitalWrite(led_pin1, LOW);     // turn the LED off
                                                                                    digitalWrite(led_pin2, LOW);     // turn the LED off
                                                                                    }
                                                                                }

                                                                                this is what i wrote it worked until i tried to ad switches and servos first loop should run until sw2 is activated then shut off loop

                                                                            • Re: Please I need help Writing code
                                                                              theshay

                                                                              I appreciate you taking the time to help me with this your awesome!!

                                                                      • Re: Please I need help Writing code
                                                                        mcb1

                                                                        theshay

                                                                        Did you try the code change I gave you?

                                                                        here https://www.element14.com/community/message/238294/l/re-please-i-need-help-writing-code#238294

                                                                         

                                                                        I suggested replacing the line

                                                                        int sensorValue = analogRead(PIN_SENSOR); 

                                                                         

                                                                        with

                                                                        by adding this in the top section

                                                                        const int trainDetector = 8// reed switch to detect train is present

                                                                         

                                                                        and this

                                                                        if (digitalRead (trainDetector) == LOW)

                                                                         

                                                                         

                                                                        Mark

                                                                         

                                                                         

                                                                        1 of 1 people found this helpful