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 Multiple Arduino functions 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
  • State Not Answered
  • Replies 20 replies
  • Subscribers 395 subscribers
  • Views 2566 views
  • Users 0 members are here
  • timers
  • arduinouno
  • delay
  • interval_timer
  • delay_interval
  • led
  • arduino
  • solenoid
Related

Multiple Arduino functions without delay

Former Member
Former Member over 10 years ago

I have literally zero coding experience but have run into the need for it at my job -- all help appreciated. Basically, I am trying to accomplish many things at once and am not sure how to translate what i need into code. What I need: a tone and a light to simultaneously flash on for 500 milliseconds and then off again for 6 seconds; water reward to be delivered (by turning on/ off a solenoid) 2 seconds after the tone/LED have turned off, with the solenoid being open for 25 milliseconds; continuous collection of data from an input potentiometer. Since i need to monitor the input from the potentiometer at all times, i cannot use "delay()" because i cannot have the board stop reading the values from the potentiometer to preform a function.

 

This is a code i attempted -- however, the issue is the timing for the LED/tone and the solenoid. I need the solenoid to always open 2 seconds after the LED/tone turn off and it needs to open for 25 milliseconds and then shut back off. i have put hours into trying to figure out a way to do this --- as the code is now, the led/tone turn on and off fine, but the solenoid has a longer delay time (because i was trying to get it to come 2 seconds after the led/tone went off) and the excess time builds onto itself and makes the timing of the solenoid vary in its proximity to the LED/tone.

 

#include <elapsedMillis.h> //the timer.

 

 

//stopwatches

elapsedMillis timer; 

 

 

int ledPin = 11;

int lick = 4;

int solenoid = 8;

int speaker = 2;

int ledOn = 500;       //milliseconds

int ledOff = 6000;

int solenoidOn = 25;

int solenoidOff = 8475;

int LickState;

 

 

int playTime = 500;  //how long speakers will play for

int freq = 8000;  //frequency for left prize speakers in hz

int toneTime = 500;

 

 

unsigned long lms;        //time from millis()

unsigned long lmsLast;    //last time the LED changed state

unsigned long sms;        //time from millis()

unsigned long smsLast;

unsigned int LedOn = 0;

unsigned int Reward = 0;

unsigned int Lick = 0;

boolean ledState;        //current LED state

boolean solenoidState;

 

 

void setup(void){

  Serial.begin(9600);

  pinMode(lick, INPUT); 

  pinMode(ledPin, OUTPUT);

  pinMode(solenoid, OUTPUT);

  pinMode(speaker, OUTPUT);

 

 

  elapsedMillis timer = 0;

}

 

 

void loop(void){

  int ledState = digitalRead(ledPin);

  int lickstate = digitalRead(lick);

  if (lickstate == HIGH){

//    Serial.println(lickstate);

    Serial.println(timer); }

  lms = millis();

    blinkLED();

  sms = millis();

    blinkLED();

   

 

} }

 

 

void blinkLED(void){

 

 

    if (lms - lmsLast > (ledState ? ledOn : ledOff)) {

        digitalWrite(ledPin, ledState = !ledState);

        lmsLast = lms;

        tone (speaker, freq, toneTime);

        Serial.print("Led");

        Serial.println(timer);

    }

    if (sms - smsLast > (solenoidState ? solenoidOn : solenoidOff)) {

        digitalWrite(solenoid, solenoidState = !solenoidState);

        smsLast = sms;

        Serial.print("Reward");

        Serial.println(timer);

    }

}

 

I have tried using if then statements to say that if the LED state is HIGH, then wait 2 seconds and deliver the reward --- the issue is the "wait 2 seconds part". how do i get the arduino to add two seconds to the current time when the LED turns off and then give my 25 millisecond reward without messing up the on/off times of the LED? Very confused.

  • Sign in to reply
  • Cancel

Top Replies

  • shabaz
    shabaz over 10 years ago +1
    This is a classic problem when creating real-time systems (which this is, since you want things to occur at or within certain times). Writing code without an OS to provide real time capabilities is difficult…
Parents
  • Robert Peter Oakes
    0 Robert Peter Oakes over 10 years ago

    here is an alternate approach you can try

     

    I have not included the actual digital IO, you already know how to do that but it does use a rudimentary state machine that should work for you and is easy extended if you need

     

    the code does compile on an arduino but I have not uploaded or tested it yet

     

    it will run every 6 seconds, will never re-run until the state machine is complete and reached the 6 seconds (Or should behave that way image )

     

    hope it helps, I will try to execute it and verify i got it right over the next few days but you can have a look now and try it for your self if you feel lucky image

    // constants
    #define  solenoidOnTime 25 // 25mS
    #define  LEDBuzzerTime 500 // 500mS
    #define  SolenoidDelayTime 2000 // 2 seconds
    #define  LoopTime 6000 // 6 seconds
    
    #define LEDPin 8
    #define BUZZERPin 9
    #define SOLENOIDPin 11
    
    //variables
    double LoopTrigger = 0; // loop timer
    int stateMachineValue = -1; // state tracker “-1” = waiting for trigger
    double nextState = 0; // used by the state machine function for timing
    
    void setup()
    {
      Serial.begin(9600); // add other initialization stuff
      LoopTrigger = millis();
      stateMachineValue = 0; // start state machine
    }
    
    void loop()
    {
      if ( (LoopTrigger <= (millis() - LoopTime)) && (stateMachineValue == -1)) // waiting for trigger and looptime has elapsed
      {
        stateMachineValue = 0 ; // start the state machine
        LoopTrigger = millis(); // reset loop timer, not this will not trigger until the state machine has completed
      }
      stateMachine();
    }
    
    void stateMachine()
    {
      switch (stateMachineValue)
      {
      case 0: 
        {
          nextState = millis();
          LEDBUZZERON();
          stateMachineValue ++; // next state
          break;
        }
      case 1: 
        {
          if(nextState <= (millis()-LEDBuzzerTime))
          {
            nextState = millis();
            LEDBUZZEROFF();
            stateMachineValue++; // next state
            break;
          }
        }
      case 2: 
        {
          if(nextState <= (millis()-SolenoidDelayTime))
          {
            nextState = millis(); 
            SOLENOIDON();
            stateMachineValue++; 
            break;
          }
        }
      case 3: 
        {
          if(nextState <= (millis()-solenoidOnTime))
          {
            nextState = millis(); 
            SOLENOIDOFF();
            stateMachineValue == -1;  // end state machine
            break;
          }
        }
        default:
        {
          LEDBUZZEROFF();
          SOLENOIDOFF();
        }
      }
    }
    void  LEDBUZZERON()
    {
      Serial.println("LED and Buzzer ON");
    }
    void  LEDBUZZEROFF()
    {
      Serial.println("LED and Buzzer OFF");
    }
    void  SOLENOIDON() 
    {
      Serial.println("LED and Buzzer ON");
    }
    void  SOLENOIDOFF() 
    {
      Serial.println("LED and Buzzer OFF");
    }

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
Reply
  • Robert Peter Oakes
    0 Robert Peter Oakes over 10 years ago

    here is an alternate approach you can try

     

    I have not included the actual digital IO, you already know how to do that but it does use a rudimentary state machine that should work for you and is easy extended if you need

     

    the code does compile on an arduino but I have not uploaded or tested it yet

     

    it will run every 6 seconds, will never re-run until the state machine is complete and reached the 6 seconds (Or should behave that way image )

     

    hope it helps, I will try to execute it and verify i got it right over the next few days but you can have a look now and try it for your self if you feel lucky image

    // constants
    #define  solenoidOnTime 25 // 25mS
    #define  LEDBuzzerTime 500 // 500mS
    #define  SolenoidDelayTime 2000 // 2 seconds
    #define  LoopTime 6000 // 6 seconds
    
    #define LEDPin 8
    #define BUZZERPin 9
    #define SOLENOIDPin 11
    
    //variables
    double LoopTrigger = 0; // loop timer
    int stateMachineValue = -1; // state tracker “-1” = waiting for trigger
    double nextState = 0; // used by the state machine function for timing
    
    void setup()
    {
      Serial.begin(9600); // add other initialization stuff
      LoopTrigger = millis();
      stateMachineValue = 0; // start state machine
    }
    
    void loop()
    {
      if ( (LoopTrigger <= (millis() - LoopTime)) && (stateMachineValue == -1)) // waiting for trigger and looptime has elapsed
      {
        stateMachineValue = 0 ; // start the state machine
        LoopTrigger = millis(); // reset loop timer, not this will not trigger until the state machine has completed
      }
      stateMachine();
    }
    
    void stateMachine()
    {
      switch (stateMachineValue)
      {
      case 0: 
        {
          nextState = millis();
          LEDBUZZERON();
          stateMachineValue ++; // next state
          break;
        }
      case 1: 
        {
          if(nextState <= (millis()-LEDBuzzerTime))
          {
            nextState = millis();
            LEDBUZZEROFF();
            stateMachineValue++; // next state
            break;
          }
        }
      case 2: 
        {
          if(nextState <= (millis()-SolenoidDelayTime))
          {
            nextState = millis(); 
            SOLENOIDON();
            stateMachineValue++; 
            break;
          }
        }
      case 3: 
        {
          if(nextState <= (millis()-solenoidOnTime))
          {
            nextState = millis(); 
            SOLENOIDOFF();
            stateMachineValue == -1;  // end state machine
            break;
          }
        }
        default:
        {
          LEDBUZZEROFF();
          SOLENOIDOFF();
        }
      }
    }
    void  LEDBUZZERON()
    {
      Serial.println("LED and Buzzer ON");
    }
    void  LEDBUZZEROFF()
    {
      Serial.println("LED and Buzzer OFF");
    }
    void  SOLENOIDON() 
    {
      Serial.println("LED and Buzzer ON");
    }
    void  SOLENOIDOFF() 
    {
      Serial.println("LED and Buzzer OFF");
    }

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
Children
  • Former Member
    0 Former Member over 10 years ago in reply to Robert Peter Oakes

    That is amazing, thank you. I'll be able to check it with the rig on Tuesday, but it looks perfect.

     

    Everyone's help has been so so appreciated!

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Former Member
    0 Former Member over 10 years ago in reply to Robert Peter Oakes

    One question -- So should I set the tone and potentiometer the same way? I should define the tone/LED/solenoid as outputs and the potentiometer as an input  in the void setup and keep the "lick" set up as is, correct?

     

    sorry -- I am just not 100% what you are referring to when you say the "actual digital IO". I know, I am very knew to all of this and it must seem trivial, but I want to make sure I have it all set up correctly.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Former Member
    0 Former Member over 10 years ago in reply to Robert Peter Oakes

    is this how it should all come together?

     

    #include <elapsedMillis.h> //the timer. 
    
    
    //stopwatches
    elapsedMillis timer;  
    
    
    // constants  
    int solenoidOnTime = 25; // 25mS  
    int LEDBuzzerTime  = 500; // 500mS  
    int SolenoidDelayTime = 2000; // 2 seconds  
    int LoopTime = 6000; // 6 seconds  
      
    int LEDPin = 8;
    int BUZZERPin = 9;  
    int SOLENOIDPin = 11;  
    int LICK = 4;
    
    
    int playTime = 500;  //how long speakers will play for
    int freq = 8000;  //frequency for left prize speakers in hz
    int toneTime = 500;   
      
      
    //variables  
    double LoopTrigger = 0; // loop timer  
    int stateMachineValue = -1; // state tracker “-1” = waiting for trigger  
    double nextState = 0; // used by the state machine function for timing  
      
    void setup()  
    {  
      Serial.begin(9600); // initialization stuff  
      pinMode(LICK, INPUT);  
      pinMode(LEDPin, OUTPUT); 
      pinMode(SPEAKERPin, OUTPUT);
      pinMode(SPOLENOIDPin, OUTPUT);
      LoopTrigger = millis();  
      stateMachineValue = 0; // start state machine  
      elapsedMillis timer = 0;
    }  
      
    void loop()  
    {  
      int lickstate = digitalRead(lick);
     if (lickstate == HIGH){
        //    Serial.println(lickstate);
        Serial.println(timer);  
        
      if ( (LoopTrigger <= (millis() - LoopTime)) && (stateMachineValue == -1)) // waiting for trigger and looptime has elapsed  
      {  
        stateMachineValue = 0 ; // start the state machine  
        LoopTrigger = millis(); // reset loop timer, not this will not trigger until the state machine has completed  
      }  
      stateMachine();  
    }  
      
    void stateMachine()  
    {  
      switch (stateMachineValue)  
      {  
      case 0:   
        {  
          nextState = millis();  
          LEDBUZZERON(); 
           
          stateMachineValue ++; // next state  
          break;  
        }  
      case 1:   
        {  
          if(nextState <= (millis()-LEDBuzzerTime))  
          {  
            nextState = millis();  
            LEDBUZZEROFF();  
            stateMachineValue++; // next state  
            break;  
          }  
        }  
      case 2:   
        {  
          if(nextState <= (millis()-SolenoidDelayTime))  
          {  
            nextState = millis();   
            SOLENOIDON();  
            stateMachineValue++;   
            break;  
          }  
        }  
      case 3:   
        {  
          if(nextState <= (millis()-solenoidOnTime))  
          {  
            nextState = millis();   
            SOLENOIDOFF();  
            stateMachineValue == -1;  // end state machine  
            break;  
          }  
        }  
        default:  
        {  
          LEDBUZZEROFF();  
          SOLENOIDOFF();  
        }  
      }  
    }  
    void  LEDBUZZERON()  
    {  
      Serial.println("LED and Buzzer ON");  
      Serial.println (timer)
    }  
    void  LEDBUZZEROFF()  
    {  
      Serial.println("LED and Buzzer OFF"); 
      Serial.println (timer) 
    }  
    void  SOLENOIDON()   
    {  
      Serial.println("Solenoid ON");  
      Serial.println (timer)
    }  
    void  SOLENOIDOFF()   
    {  
      Serial.println("Solenoid OFF");  
      Serial.println (timer)
    } 

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Robert Peter Oakes
    0 Robert Peter Oakes over 10 years ago in reply to Former Member

    looks like your on the right track, keep it up

     

    I would be pleased to see your progress as you move forward

     

    If you need more help, please ask

     

    Peter

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Robert Peter Oakes
    0 Robert Peter Oakes over 10 years ago in reply to Former Member

    What is the Lick for, is the system waiting for a fuzzy creature to lick the end of a pipe for a drink to trigger the system or is the idea to “Train” said fuzzy creature to come lick the pipe 2 seconds after it hears or sees the alarm signal (LED/Buzzer) and record if it does come and lick ?

     

     

     

    Peter

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Former Member
    0 Former Member over 10 years ago in reply to Robert Peter Oakes

    Spot on!

     

    I m still playing around with the statemachine code trying to get it ironed out -- what statemachine library did you include, FMS?

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Robert Peter Oakes
    0 Robert Peter Oakes over 10 years ago in reply to Former Member

    There is no library, what you see is it

     

    for something this simple there was no need for additional libraries

     

    is it working for you or are you having issues, as I stated above, I was able to compile but did not have time to test it

     

    look forward to your feedback

     

    Peter

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Former Member
    0 Former Member over 10 years ago in reply to Robert Peter Oakes

    It does compile -- but there is still an issue with the ending of one command and the beginning of another. Where should I put the actual command for turning on/off a pin? For instance, should I put digitalWrite(LEDPin, HIGH); in the void LEDBUZZEROn section or in the case 0 zero section? I assume it is necessary to put that (or something like it) in the code, otherwise i'm not clear on how the arduino will receive the command to turn a pin on/off.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Robert Peter Oakes
    0 Robert Peter Oakes over 10 years ago in reply to Former Member

    yes you need to add the digital write etc to the code, i figured you knew how to do that part already, I have empty functions for that in the sample that currently just output the expected behaviour to the serial console

     

    so LEDBUZZERON would have code added to turn on the LED and the Buzzer

    LEDBUZZEROFF would have code added to turn off the buzzer and led

    etc.


    If it is still confusing, let me know and ill add some more code but I cant get to it till the weekend


    Regards


    Peter

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Former Member
    0 Former Member over 10 years ago in reply to Robert Peter Oakes

    Hopefully I can sort it out myself! Just to clarify-- will the digitalWrite prices of the code go under the void LEDBUZZERON() sections or will they be in the place of "LEDBUZZERON" etc. in the void statemachine() region of the code?

     

    thank you!

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • 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