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 When is the function delay() a delay?
  • 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
  • Replies 41 replies
  • Subscribers 389 subscribers
  • Views 7361 views
  • Users 0 members are here
  • delay
  • arduino_code
Related

When is the function delay() a delay?

colporteur
colporteur over 2 years ago

else if (MainDepartureState == LOW && MainArrivalState == LOW) {
        if (startupMain == HIGH) {
          // pulse turnout for Main train
          digitalWrite(Main_Turnout, HIGH);
          relayDelay();//<-----1
          digitalWrite(Main_Turnout, LOW);
          if (deBug == HIGH) {
            Serial.println("The Main Turnout Activated");
          }
          // Engage Motor for Main
          motors.setSpeedB(minSpeedB);  // Start Motor for Main
          motors.forwardB();
          PowerMain = LOW;
          startupMain = LOW;
          delay(300000);//<----2
          if (deBug == HIGH) {
            Serial.println("Motor Delay Complete");
          }

According to what I have read “The delay() function allows you to pause the execution of your Arduino code for a specified period.”

Why are the delays I am using not working or the values are so extreme? How can I best accomplish a delay?

I tried using the delay() function at point <----1 in my code and it failed miserably. I wanted to activate a relay by turning it on, waiting for relay to engage (delay(2000), then turn it off. The delay(2000) two seconds didn’t work. I wrote a little relay routine that accomplish what I wanted but why did delay(2000) not give me two seconds?

I am using delay() function at <----2 in the code but the value doesn’t reflect the actual delay. I needed to generate some wait time for the motor to engage and trigger a sensor. My desire was a three second delay(3000) but the delay(300000) was a value that actually worked. That would be 300 seconds yes/no?

I'm a code resurrectionist and not an actual programmer. I will try and muddle through discussions 

  • Sign in to reply
  • Cancel

Top Replies

  • colporteur
    colporteur over 2 years ago +6
    Based on GL shared insight, I used a different set of PWM pins so as not to muck with the delay() timer. I also took the BE suggestions and used subtraction in the millis routines. I am happy to report…
  • Gough Lui
    Gough Lui over 2 years ago in reply to colporteur +5
    //user input variables int turnout_delay = 10000; //delay for relay contacts to engage int motor_delay = 900000; //delay for motor to move train unsigned long time_now = 0; int type cannot store outside…
  • Gough Lui
    Gough Lui over 2 years ago in reply to colporteur +3
    I think that it helps if one can see names like "TCCR0B" and know inside that it is short for "Timer Control Counter Register" then that should immediately set-off alarm bells in one's head. Gough Lui…
Parents
  • colporteur
    colporteur over 2 years ago

    I am going to put aside my reservation about posting full code and look to the baldengineer's suggestion  I somewhat suspect the old adage: "code snippets rarely contain the problem" could apply here.  to help understand and possibly resolve my issues.

    https://ln5.sync.com/dl/875622290/stys9mg3-ky7jseyq-9avds3rb-pdpa6z85

    I don't use change management tools like github. The above link will provide access to a zip file of the current arduino ino file.

    The code automates the operation of a model train layout. I have used the work on this project in a few posting.   Pulse Width Modulation a Speed Equalizer(6): The locomotive has arrived in the final post  I'm Board...Cutting Board to Printed Circuit Board  Two trains labeled Siding and Main are controlled using the code. The goal is to alternately switch the two trains onto a loop of track. First one then the other. The code controls turnout switching, speed management and alternating each train.

    https://ln5.sync.com/dl/ca9b041f0/nge29iak-a4mpe5gi-bnvfxbdd-rwi9ubig

    A short video showing the trains in action can be found at the link.

    lines of code 255-273 & 357-374 are the delay areas I am currently trying to resolve.

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • Cancel
Reply
  • colporteur
    colporteur over 2 years ago

    I am going to put aside my reservation about posting full code and look to the baldengineer's suggestion  I somewhat suspect the old adage: "code snippets rarely contain the problem" could apply here.  to help understand and possibly resolve my issues.

    https://ln5.sync.com/dl/875622290/stys9mg3-ky7jseyq-9avds3rb-pdpa6z85

    I don't use change management tools like github. The above link will provide access to a zip file of the current arduino ino file.

    The code automates the operation of a model train layout. I have used the work on this project in a few posting.   Pulse Width Modulation a Speed Equalizer(6): The locomotive has arrived in the final post  I'm Board...Cutting Board to Printed Circuit Board  Two trains labeled Siding and Main are controlled using the code. The goal is to alternately switch the two trains onto a loop of track. First one then the other. The code controls turnout switching, speed management and alternating each train.

    https://ln5.sync.com/dl/ca9b041f0/nge29iak-a4mpe5gi-bnvfxbdd-rwi9ubig

    A short video showing the trains in action can be found at the link.

    lines of code 255-273 & 357-374 are the delay areas I am currently trying to resolve.

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • Cancel
Children
  • baldengineer
    baldengineer over 2 years ago in reply to colporteur

    Where did you get the L298NX2 library from? I'd like to see that in more detail.

    FYI, not related to your problem, since I do not think that code is using it, but you have an error with motor_delay.

    int motor_delay = 900000;   //delay for motor to move train

    You cannot store more than 32,767 in a signed variable 16-bit variable. If you want to use 900,000 then you need to make it an unsigned long.

    Also not related to your problem, but I want to bring it up now... the way you are using millis() does not handle roll-over correctly. (Although, that should not be a problem for another 48 days.)

    The problem is that your comparison will (very likely) rollover before millis() does, which is going to result in unexpected logic. The correct way to handle millis() rollover is by using subtraction. When you subtract two unsigned integers, you get the absolute difference between them.

    time_now = millis();
    while (millis() < time_now + turnout_delay)

    Let's just say the rollover event occurs at 1000 for these variable types. Then let's say turnout_delay = 250 and when you assign millis() to time_now, both are (momentarily) 900. The first time that while statement is evaluated, millis() will have incremented 1-2 counts which means your evaluation is: 902 < (900 + 250).

    Do you see the problem? 

    The comparison is NOT: 902 <  1150! Because, remember I said (for this example) the variable type that holds the value rolls over at 1000. (unsigned longs rollover at 4 million something, 1000 is easier to type.) So instead your comparison effectively became:

    902 < abs(1000 - (900 + 250)) or 902 < 150!

    So now, you're going to sit there spinning for a while because millis() has to catch up to the values that already rolled over!

    Instead, you should include millis() in the calculation and use subtraction. So your spinlock should be:

    previous_time = millis();
    while (millis() - previous_time <= turnout_delay);

    I have a longer write-up here (skip to the "why does this work" section) if you want to see other examples of how this rollover happens with real code.

    In the meantime, I think we need to look at that library to see what it is doing. I suspect it is futzing with a register or two.

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • Cancel
  • Gough Lui
    Gough Lui over 2 years ago in reply to colporteur

    //user input variables
    int turnout_delay = 10000;  //delay for relay contacts to engage
    int motor_delay = 900000;   //delay for motor to move train
    unsigned long time_now = 0;

    int type cannot store outside of -32,768 to 32767 in AVR-based boards. Suggest you use unsigned long. Variable motor_delay will have the wrong value as far as I can tell due to overflow.

      //increase PWM freq to reduce locomotive motor hum
      TCCR1B = TCCR1B & B11111000 | B00000001;  // pin 12 for PWM frequency of 31372.55 Hz Siding
      TCCR0B = TCCR0B & B11111000 | B00000001;  // pin 13 for PWM frequency of 62500 Hz Main

    This is probably what is breaking delay as this is reconfiguring timers! Timer 0 is needed for delay(), so I'd say the second line (TCCR0B) is breaking it.

    - Gough

    • Cancel
    • Vote Up +5 Vote Down
    • Sign in to reply
    • Cancel
  • colporteur
    colporteur over 2 years ago in reply to baldengineer

    https://github.com/AndreaLombardo/L298N the link for the Arduino module to control two motors.

    I think there is some detritus in my code from failed attempts. The motor delay was my attempt at constructing a void function to create a motor delay. I am more aware now of the unsigned long.

    The missus just put supper on the table. I will check in later. Thanks for the insight.

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • baldengineer
    baldengineer over 2 years ago in reply to Gough Lui

    I totally agree with Gough. I misread the register names when I looked at the code. (I thought they were both the same register!)

    Are Serial.print()s working?

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • baldengineer
    baldengineer over 2 years ago in reply to colporteur

    Understandable on the motor_delay. And I recognize it is one of the reasons why it gets tough to share code. People pick apart the things you already know, or think you know, about.

    However, I cannot tell you how many times I've had someone point out some code I thought was commented (or logic'd out) during my debugging.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
  • ntewinkel
    ntewinkel over 2 years ago in reply to Gough Lui

    Awesome catch, Gough Lui  !

    colporteur , you can probably test this by adding that line into the Blink sketch to see what happens.

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • colporteur
    colporteur over 2 years ago in reply to baldengineer

    serial prints appear to be working.

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • colporteur
    colporteur over 2 years ago in reply to Gough Lui

    WOW folks blown away with your input.

    I wasn't aware of limitation on variables. I know some of the basic about types but this unsigned long is something I need to be more aware of.

     ntewinkel suggestion to test delay(0 was spot on. loading (TCCR0B) in void setup and LED no blink anymore.

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • Cancel
  • colporteur
    colporteur over 2 years ago in reply to Gough Lui

    I plan to make some PWM pin changes to hopefully eliminate the problem. I currently use pin 12 & 13. The plan is to use pin 44 & 46

    Code for Available PWM frequency for D44, D45 & D46:

    TCCR5B = TCCR5B & B11111000 | B00000001; // for PWM frequency of 31372.55 Hz

    Can you tell me if this change will cause any possible issues?

    Break....Break...

    What made you aware the void setup conflicted with the delay()

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • baldengineer
    baldengineer over 2 years ago in reply to colporteur

    delay() relies on micros() which relies on TIMER0.

    You can see the full code here:

    https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c

    Jump to line 106 for delay() and then look at micros() right above it.

    Also also, notice how delay() is using milils() (with subtraction!) to do the actual delay time ... (which is similar to what you were trying to do in some sections of your code.)

    delay() isn't magic, it is just a loop.

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • Cancel
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