element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • 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 & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
  • 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
      • Japan
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Vietnam
      • 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 trying to get an LED to come on for 3 seconds and come off without 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 29 replies
  • Subscribers 405 subscribers
  • Views 6046 views
  • Users 0 members are here
  • arduino_code
Related

trying to get an LED to come on for 3 seconds and come off without delay

Former Member
Former Member over 12 years ago

hey guys i'm just trying to get an led to come on for 3 seconds and then comeoff, without using delay, i'm not understanding the millis function but i've tried a bit. kindly let me know what i'm doing wrong. thank you.

 

int count = 0;
long previousMillis = 0;        




long interval = 3000;           


void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);    
  
}


void loop()
{
  
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    
    previousMillis = currentMillis;   


     if (count <=1)
      digitalWrite(ledPin,HIGH);
    else
      digitalWrite(ledPin,LOW);
count ++;
    
    
  }
}

  • Sign in to reply
  • Cancel

Top Replies

  • billabott
    billabott over 12 years ago in reply to phoenixcomm +2
    Interesting insight Cris H. Unfortunately, your code does not plug into the 'Duino IDE too well. So, I took some time to create my own completely commented version which I now make available to everyone…
  • ntewinkel
    ntewinkel over 12 years ago in reply to Former Member +1
    To have red and green alternating on, you basically copy the lines of code that turn the ledpin high and low and set opposite values for the other LED. ie, when you turn the red led on, at that time you…
  • Former Member
    Former Member over 12 years ago +1
    Thank you Navin and Nico I will definately try out the two versions! You guys are awesome and I will give you 50 cool points each! Seriously though, I just wish I could one day be as helpful as you two…
Parents
  • phoenixcomm
    phoenixcomm over 12 years ago

    lots of ideas...

    but:

    1. you don't want to write the code twice
    2. and using the % function is ok but it is only clouding the issues

     

    you never said how long you wanted to make the led blink.

    blinking, or oscillation is a repetitive process of turning something on and then off.

    so why not write two loops one count the delay the other controls the state of the led

    FINS

    enjoy

    Cris H.image

     

    #define OFF 0

    #define ON 1

    #define FOREVER for(;;)

    long delay 3000; //msecs

    // set the digital pin as output:

    pinMode(ledPin, OUTPUT);

     

    // we are going to start in the ON state

    int led = ON;

    long millis = 0;

     

    FOREVER {

      

         for( ; millis < delay; millis++ );                              //  this  is the delay loop

              millis = 0;                                      

    // following could have been done differantly by using the =! operator and changing a var name

         if( led == ON ) {                                                  //  switch logic

              led = OFF;

              int LedPin = LOW;}

         else if( led == OFF ){

              led = ON;

               LedPin = HIGH;}

    //  LedPin =! LedPin; // no if() no else if()..

         digitalWrite(ledPin,LedPin);}       // write to the led

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
  • billabott
    billabott over 12 years ago in reply to phoenixcomm

     

    Interesting insight Cris H.   Unfortunately, your code does not plug into the 'Duino IDE too well.  So, I took some time to create my own completely commented version which I now make available to everyone.  It has been tested and runs on UNO using IDE 0023.


    #define OFF 0

     

    #define ON 1

     

    unsigned long int timecheck;

    unsigned long int mydelay = 3000;  //  3000 msecs = 3 secs

    int ledPin =13;   //  onboard led blinking with a 50 % duty cycle @ 0.166 Hz

                              //  tells user that the program is running normally

     

    int Led = ON;  //  start in the ON state

     

    void setup()

    {

       pinMode(ledPin, OUTPUT);     // config pin for output, duh  image    

       digitalWrite(ledPin,Led);      // initialize state of output pin

       timecheck = millis() + mydelay;       // initialize timecheck 

    }   // putes

     

     

    void loop()

    {

       if (millis() > timecheck) {      // have 3 seconds gone by?

             Led = !Led;      // complement the value  ON or OFF

             digitalWrite(ledPin,Led);  //  update state of output pin

             timecheck = millis() + mydelay;     // update timecheck   

             }  // fi

    // else {

            ;     // other tasks needing to be done between led transistions are placed here

            ;     //  could use a counter to limit number of iterations thru this code subblock

            ;     //  so process returns in time to catch the above timecheck condition.

    //  }  //  esle

     

    }  // pool

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • Cancel
  • phoenixcomm
    phoenixcomm over 12 years ago in reply to billabott

    bill, I was not writing a Duino application. I don't like to spoon feed people.. I just wanted to show how to do the programing logic. one comment about yours thou, is the you created a function mills in the 8 bit arena that is a call (push) and a return (pop) which with limited memory and a slow cpu I would not have done.

    one other thing... I do not like the 'Duino IDE at all. It hides a lot of things. Like the real interrupt structure ( The Select Statement ) and you loose the 30 or 40 years of Leverage with the C library. I use for the Duinos the AVR - Eclipse tools, and I use Eclipse for all my other work as well.

     

    BTW I have been writing with C for few decades at least.

     

    Cris H.

     

    UPDATE I really like your  use of the =! operator.. no muss no fuss. But I didn't know if a nubie would get it so i did it the long way with the two if()s.

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • R_Phoenix
    R_Phoenix over 12 years ago in reply to billabott

    http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • billabott
    billabott over 12 years ago in reply to phoenixcomm

    @Chis

        I have great respect for anyone that has been programming in C for many years.  I have not yet had the opportunity to get involved with AVR - Eclipse IDE although I hope to after this summer is over.  Don't spead it around but I did read Smiley's AVR Butterfly Book.   

     

        I was incentivised by someone at e14 to spend a whole month and a half after last Christmas exploring the Microchip PIC MPLAB ide.  I found it quite a rewarding experience. 

     

       What do you call your example's coding style?  Generic C or something else?

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
  • billabott
    billabott over 12 years ago in reply to R_Phoenix

    R_Phoenix wrote:

     

    http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

    The sketch I wrote does basicly the same thing but with my personal coding style and flavor.  It is the best I can possibly do.  I like the official arduino tutorial examples because they comment the code extensively.  I believe that my code comments also provide a reasonable justification to adopt it as a basic structure for all sketches.  Who doesn't benefit from a visual indication that the program is alive and doing the tasks assigned to it?  One thing I personally dislike are complicated condition tests,  I try to follow the KISS design philosophy.   

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
  • billabott
    billabott over 12 years ago in reply to phoenixcomm

    @Cris

    I do understand that there are good arguments for assembly code on low priced 8 bit uC.  However, Our Future is low priced 32 bit core Cortex M0, M1, M2, and M4 uC and DSP ICs.  I see the Arduino as a springboard for the programmers of the Future.  It is just an easy enough platform for those whose naturaly abilities allow them to "Get It" to start programming in C and hopefully never stop. 

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
  • phoenixcomm
    phoenixcomm over 12 years ago in reply to billabott

    coding style?! LOL  I personally despise enforced coding styles.. (And that was about 2am and off the cuff) My normal thing is my own C/C++/Perl/php that I have been using for years

     

    void function_name( type arg...){

         int count;

         do{

              something;

              }( test);

         }

     

    #defines, enums etc. should be in a .h file

    they should be CAPPED

    NEVER use 1, 0 or other thing like that just define them!

    if a variable 'attributes' has 4 states that you know about then define the states:

     

    enum attributes {

              NOP      = 0x80,

              BLANK   = 0x81,

              BLINK    = 0x82,

              LAMP          = 0x83

    };

     

    your code should also should fit  on a page (easy to read on paper)

     

    Also before you write your function it should be well thought out and documented. sometimes it might be easier to flow chart it. ( really showing my age now )

    but there are times when working with aircraft my code conforms to MISRA coding standards. image

     

    there is more of this kind of drivil image

     

    Enjoy

    Cris H. image

     

    BTW assembly code == non portable == not reusable = garbage.

    with the 680xx which was orthogonal C++ = --B * G++; was  equal to one line of C code.

    If there is a compiler USE IT.

    yes I can use asm on 80xx, Z80, IBM360/370, hp21mx and others.. but why when I have a C complier?

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • mcb1
    mcb1 over 12 years ago in reply to phoenixcomm

    Bill

     

    re your line

    if (millis() > timecheck) {      // have 3 seconds gone by?

    It was pointed out to me that the millis() timer rolls over after 49 days + some minutes and seconds, hence you should always subtract.

     

    If I'm not mistaken at the rollover the if statement will fail because millis() will be lower than the timecheck.

     

    Ever since that lesson on another forum, I always use this.

    if ((millis()-timecheck) >=mydelay)

     

    Simply make timecheck = millis() and then when the mydelay time has passed the if statement will become true.

     

    As a beginner into Arduino IDE I think the reference section is quite poor.

    It is probably very suitable for someone already versed in software.

     

    As a good reference book I liked the Arduino Cookbook. It tended to be wrtten for a beginner and turned it around, by presenting the problem then the solution.

     

     

    @Cristina

    Some of us hardware types are still struggling to get our heads around software.

    I never did learn C, but appreciate it is very powerful, and quicker.

     

    Our/my  problem is we only have so much tiome to create our projects, so sometimes its a trade-off between very efficient code and something that works on hardware that is being under utilised.

    The Arduino IDE has at least introduced me to C++, and opened up a world that was there, but not something I was willing to take the plunge into.

    (Don't laugh about flowcharts I tend to utilise a flow type diagram when putting together some of my projects ... maybe I'm showing my age)

     

    cheers

    mark

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • billabott
    billabott over 12 years ago in reply to mcb1

    @Mark

    Thanks for improving the mouse trap.  I think your suggestion is important for projects that are going to run for many weeks without interruption and I will adopt this method.  Thanks again.  Let us pray for the swift recovery of New Zealand cricketer Jesse Ryder.


    Just to be sure I have understood 100%, it should go like this:

     

    void setup()

    {

       pinMode(ledPin, OUTPUT);     // config pin for output, duh  image   

       digitalWrite(ledPin,Led);      // initialize state of output pin

       timecheck = millis();       // initialize timecheck

    }   // putes

     

     

    void loop()

    {

       if (millis() - timecheck >= mydelay) {      // have at least 3 seconds gone by

                                                                          // or has timer rolled over?

             Led = !Led;      // complement the value  ON or OFF

             digitalWrite(ledPin,Led);  //  update state of output pin

             timecheck = millis();     // update timecheck  

             }  // fi         

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
Reply
  • billabott
    billabott over 12 years ago in reply to mcb1

    @Mark

    Thanks for improving the mouse trap.  I think your suggestion is important for projects that are going to run for many weeks without interruption and I will adopt this method.  Thanks again.  Let us pray for the swift recovery of New Zealand cricketer Jesse Ryder.


    Just to be sure I have understood 100%, it should go like this:

     

    void setup()

    {

       pinMode(ledPin, OUTPUT);     // config pin for output, duh  image   

       digitalWrite(ledPin,Led);      // initialize state of output pin

       timecheck = millis();       // initialize timecheck

    }   // putes

     

     

    void loop()

    {

       if (millis() - timecheck >= mydelay) {      // have at least 3 seconds gone by

                                                                          // or has timer rolled over?

             Led = !Led;      // complement the value  ON or OFF

             digitalWrite(ledPin,Led);  //  update state of output pin

             timecheck = millis();     // update timecheck  

             }  // fi         

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
Children
  • mcb1
    mcb1 over 12 years ago in reply to billabott

    Bill

    Yep thats pretty much it.

     

    Navin wanted it to be on for 3 secs and not toggle, but I think he has enough info now to make it work.

     

    @lahiboi671

    For the red even, green odd there are multiple ways to achieve it.

    You can simply store the last colour, and change, it when you turn the colour ON.

    You toggle a true/false, or a 0/1 and use it to set which colour led to trun ON.

     

    Good luck.

    Mark.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
  • Former Member
    Former Member over 12 years ago in reply to mcb1

    Thanks Mr, Beckett! I will try the true/false toggle method. Hopefully I can get the hang of writing in C, soo much to learn so little time!

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
  • mcb1
    mcb1 over 12 years ago in reply to Former Member

    Lahiboi671

    Arduino uses c++, but can use C as as well.

    The reference in the IDe gives you the commands available, even if the examples are not the nicest for beginners.

     

    I found the Arduino Cookbook was written from a 'I have this problem, what can I use' style which makes it easier on beginners.

     

    Hop onto the arduino.cc forum and have a look at some of the examples.

    There is a good search function with lots of code floating around.

     

    I've found you learn much more by trying, rather than having someone do the work for you.

    It wasn't long ago that this was foreign to me, so you'll be surprised at how quick you can pick it up.

     

     

    Mark

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
  • Former Member
    Former Member over 12 years ago in reply to mcb1

    Thanks Mark!

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
  • Former Member
    Former Member over 12 years ago in reply to mcb1

    Awesome reccomendations Mr. Beckett! I have been borrowing that book off and on from the library for the past few months, before I even settled on getting an Arduino! image I am liking it especially when I get to throw in a book titled, "Make: Arduino Bots and Gadgets by Tero Karvinen. For some reason it seems to be the best prescription for "newbie-nitess", with decent information to digest and absorb. And as disenchanting as 'C for dummies" by Dan Gookin sounds I found it best to throw away my closed-mindedness and try to learn a bit in that arena. I also found from an instructor, and in the intro pages of the books I have read, that I should go to forums at Arduino.CC something that sounds soo familiar. It has been said that someone, somewhere, at some point in time around the world probably came to the same fork in the road as I have. I am tinkering every chance I get! LOL! So far my budget is a little strapped so I went to goodwill and desoldered a bunch of rc cars and cd players and have a scrounge area in my room for project prototypes. Hopefully, I can get a video or something started on my page as a thank you for everyone who gave constructive input without involving too much of their personal touch to their replies. Best regards and happy hunting!

    • Cancel
    • Vote Up 0 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