I have a project where I need to turn a 24V solenoid on for a set amount of time, then have it turn off. I am rather new to Arduino and not certain how to do this or really where to start. Ideally the time would be displayed on a LCD screen as well but this is purely aesthetic. Any advice, help, examples ect would be appreciated. Thanks!


Use millis();

Record millis() in a long variable like below when the solenoid starts StartTime = millis();

to switch off solenoid after 60 seconds you may do

if ( (millis() - StartTime)/1000 ) >  60
   // switch off solenoid

enjoy coding.

There are other ways as well to achieve this... but this is being easiest and you don't have to wait caused by using delay();

  • Division is a very expensive operation on many Arduinos. It is thus better to write if (millis() - StarTtime >= 60000). – Edgar Bonet Apr 24 at 8:29
  • Hmm.. Good to know that.. But would you explain what do you mean by "Expensive" does it draw more power? – AmAr Apr 24 at 8:57
  • 1
    The AVR MCUs do not have hardware support for division, which is thus done by software, bit by bit, and costs quite a lot of CPU cycles. Power consumption should not be affected, unless you care about it. If you do care, you most likely keep the CPU in sleep mode most of the time, and wake it up only when there is work to do. Then, all the cycles you burn doing non-essential operations keep the CPU awake for longer, and cost energy. – Edgar Bonet Apr 24 at 9:23
  • Hmm... ok . Thanks for the information Edgar !! – AmAr Apr 24 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.