element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Arduino
  • Products
  • More
Arduino
Arduino Forum Please I need help Writing code
  • Blog
  • Forum
  • Documents
  • Quiz
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Arduino to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • State Verified Answer
  • Replies 51 replies
  • Answers 9 answers
  • Subscribers 396 subscribers
  • Views 4256 views
  • Users 0 members are here
  • need help coding
  • need code written
Related

Please I need help Writing code

theshay
theshay over 7 years ago

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

 

}

  • Sign in to reply
  • Cancel

Top Replies

  • theshay
    theshay over 7 years ago in reply to andywest +4 suggested
    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…
  • jomoenginer
    jomoenginer over 7 years ago in reply to theshay +3 suggested
    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…
  • theshay
    theshay over 7 years ago in reply to balearicdynamics +3
    Thank you so very much Enrico You are truly an honor and a scholar. May the guiding light be with you! I cant thank you enough for helping me. you really got me out of a jam. :-))) Not sure if you travel…
Parents
  • andywest
    0 andywest over 7 years ago

    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?

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Verify Answer
    • Reject Answer
    • Cancel
  • theshay
    0 theshay over 7 years ago in reply to andywest

    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.

    • Cancel
    • Vote Up +4 Vote Down
    • Sign in to reply
    • Verify Answer
    • Reject Answer
    • Cancel
  • andywest
    0 andywest over 7 years ago in reply to theshay

    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?

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Verify Answer
    • Reject Answer
    • Cancel
  • theshay
    0 theshay over 7 years ago in reply to andywest

    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 :-(

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Verify Answer
    • Reject Answer
    • Cancel
  • theshay
    0 theshay over 7 years ago in reply to andywest

    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;

     

      }

    }

    /*
    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • andywest
    0 andywest over 7 years ago in reply to theshay

    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.

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Verify Answer
    • Reject Answer
    • Cancel
  • jomoenginer
    0 jomoenginer over 7 years ago in reply to theshay

    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.

    • Cancel
    • Vote Up +3 Vote Down
    • Sign in to reply
    • Verify Answer
    • Reject Answer
    • Cancel
  • mcb1
    0 mcb1 over 7 years ago in reply to theshay

    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

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • Verify Answer
    • Reject Answer
    • Cancel
  • theshay
    0 theshay over 7 years ago in reply to andywest

    thank you for helping me i appreciate it:-))

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • theshay
    0 theshay over 7 years ago in reply to mcb1

    thank you for your help:-))

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
Reply
  • theshay
    0 theshay over 7 years ago in reply to mcb1

    thank you for your help:-))

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
Children
No Data
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube