1

I'm trying to make two functions one will be running in a loop the second one will be running with a time interval of 1 seconde
I made a piece of code to do so it runs fine in the beginning but after a bit of time (aproximately 35 secondes) the code loses its mind and starts executing without caring about the delays.
I don't know what's going on
here is my code

void loop() {
  if(millis()-prev>=gap){
    Serial.print("Prev: ");Serial.println(millis()-prev);
    prev = millis();
  }

  Serial.print("Prev2: ");Serial.println(millis()-prev2);
  delay(mils);
  prev2 = millis();
}

You can try it yourself the code runs fine at the begining but bugs after some time. What i'm trying to acomplish is having some code that runs in a loop and a function that will run each seconde. the code is tried on multiple boards of Arduino Uno.

1
  • Show us the rest of your code. 35 seconds you say? I bet prev and prev2 are int type variables and not unsigned long like they should.
    – Delta_G
    May 13 '20 at 2:16
0

Your problem is that you use delay() in your loop. This stops the code execution for the given time, so no wonder your code starts to frickle after some time.

To achieve what you want try this:

void loop() {
  if(millis() - prev >= gap){
    Serial.print("Prev: ");Serial.println(millis()-prev);
    prev = millis();
  }
  if(millis() - prev2 >= mils){    
  Serial.print("Prev2: ");Serial.println(millis()-prev2);
  prev2 = millis();
 }
}

EDIT If you try to create a frequency generator, it won't work that way - read this thread and look at the program in the last third which uses bitbanging technique to achieve that.
Here an example of a wave generator (with extra hardware)

3
  • I was using that in the begining but i removed it because the second one should use a higher resolution so it should use micros instead of millis but when I use micros instead of millis it doesn't work as expected so I used delays.I just simplified the code to focus on whats causing the problem.but my code that will run in a loop is code that use micros to generate a precise pulse that varies between 1ms and 220ms so I was forced to use delay and delaymicroseconds to acheive it is there any other way to get a pulse ON time and OFF time should be the same but width varies.tone doesn't reach 1ms
    – Jwdsoft
    Apr 12 '20 at 22:36
  • When the same principle didn't work with micros(), you have done something wrong with it. You can show us your micros code
    – chrisl
    Apr 12 '20 at 22:55
  • The same code for 1 seconde just change millis to micros and gap to 1000000 and it will not work if(micros() - prev >= 1000000){ Serial.print("Prev: ");Serial.println(micros()-prev); prev = micros(); }
    – Jwdsoft
    Apr 12 '20 at 22:59

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.