Hey ive watched this series from part 1-6 and as someone with no prior coding experience, having to learn arduino and coding in a relatively short period of time for university has been quite challenging. I have an upcoming assessment where millis are crucial to the code so these videos were extremely helpful and I cant thank you enough!
Really like your videos!! My 12 yr. old and I are learning together. My goal is to totally automate a greenhouse using Arduino. This video is exactly what we need.
Hi, I´d like to say how much great and important is this playlist to understanding millis function. I´ve been learning millis from excellent videos in Portuguese, Spanish and English, actually I've already watch the last two videos from this playlist weeks ago(maybe months), but only now after watch all the videos from this amazing and F. (funny) playlist I can say that I understand millis. Finally I can drink enjoying an amazing sunset knowing I understand the tensile strength of a rubber band, the Mayan calendar, the intimacy between space- time and black holes while my soul floats through ancient music. Thank You!
Got my first Arduino yesterday. Thought it could be fun to play with a fairly modern system. A lot to learn. Made embedded real time multiprocessor systems decades ago. Both hardware and software, Intel 4040, 8051 8085, 80188. and Z80. Assembly & high level languages like PL/M and Modula-2. This video made it clear how to structure a small stepper motor project.
Just what I was looking for ! I needed to slow down the up and down increment of the set rpm programme on an Arduino that uses a touchscreen display without using the despicable delay function , managed to slot this into one of the if statements inside aviod ReadControls function - works a treat and as this programme is interrupt based ( rpm sensor ) the delay is a big no no . 100 milliseconds did the trick . Thank you !
This has to be best described video tutorial I have seen on almost any topic, very clear descriptions and well thought out content. First time visiting and cant wait to learn more from this channel.
If you have 2 events like on this example, but the first one takes a considerable time to execute, because there are many instructions in between, I guess updating the currentTime variable with the newer mills value wouldn't harm and it's actually recommended to do so before every event.
Thanks for the note Larry! Have you checkout Geoff Bunzas UA-cam Channel? ua-cam.com/channels/KzeYLMEPxWGilqZTNuG0JA.html He uses Arduino in model railroading. Pretty neat stuff.
Thanks Michael. A very well made tutorial and very helpful to me right now as I am writing my first code for an Arduino (aged 63 !) which will strike a bell every hour exactly. I would like to expand the program to move a stepper motor driven hour hand. A stepper motor tutorial would be great ;-). Best regards, Mike
Great video and love the humor sprinkled in there. In your closing remarks relative to the IF statement……it would be nice to say you set the first previous time to zero….you did say it in the up front part. That is when “I got it”…..like you said walk thru it.
Thank you for the nicely laid out tutorial. You showed a simple but effective way to plan out what to do, and then carry it out. While I have programmed in other environments before, I’m new to the Arduino, and you have made it easy to pick up the new parts. Cheers!
I saw an example code where someone created an array to hold the millis readings per item you want to manage, and the condition logic was within a function. That way the code was quite minimal. That was in the Doomsday Communicator UA-cam video where he demonstrated building a Lora chat device.
Hey thanks! I didn't think I would need the millis function till I saw your videos about it. I'm building a miniature dollhouse that I want to have music and dimmed lights. Using delay would have caused me some problems.
Fantastic video. I've been watching the series and hoping you'd cover timed events using the Millis() function. Very difficult to get your head around that function and you have definitely helped.
@@programmingelectronics i guess millis still sucks because if you have any delay()s in those timed events your entire timeline will be screwed up. i think to use millis everything has to be perfectly synchronized
@@yashaswikulshreshtha1588 I don't believe delay() effects the background count of the millis() function - millis() will keep counting. You might consider some timer libraries that trigger interrupts at specific times...
@@programmingelectronics I wanted to use millis for timed events but let's say if one event which turns on led has a delay in it then It won't affect millis counts but yes it will act as blocking code for other code pieces sometimes like permanent blockage, you can a event which happens every one second and then an event which happens every 3 seconds, so ofc the first will execute first but if u put delay of 3000 In it then the second event won't happen at all, it never will. I thought maybe I could use millis to run big code blocks having lot of functionalities. At timed intervals
@@programmingelectronics I would be really grateful if you can make video of classes and objects in Arduino. Probably no has explained good on UA-cam, but if u can make it, it will be on top and it will be helpful to all of us, cuz some of us are trying to learn actual programming concepts using arduino
I like the concept. Just not sure how you handle the rollover of the millis() count? In the reference documentation, millis() will rollover in about 50 days. Seems you should have to check for a rollover condition.
nice, this what i was looking for. intuitively I would have updated the previousTime with the interval, instead of the currentTime... previousTime_1 += eventTime_1 but i expect differences to be minimal, a small (yet slowly increasing) delay in the currentTime version compared to my idea...
This vdo is really helpful for me understand to millis function. Just one question sir am using millis function for one LED blink off time and on time is same. How to change off time only means 1000 Ms is off time and on time is 500 ms. I think you you understand my question sir.
Nice video. I've got a use case that requires both event-driven and timer-driven functions so this was helpful. Regarding your timer update, though, I think I would have updated previousTime_1 & previousTime_2 by ADDING their respective intervals back into them rather than updating to the current time. loop() is subject to blocking and there are other reasons that your loop might lag, so your implementation might creep (e.g. 0... 1003... 2003... 3005... 4006... 5007 vs 0... 1003... 2000... 3002... 4001... 5001). Staying truer to your intervals might be important.
lol how funny is that. I have not long finished writing code very similar to this, except I used a DHT22 and a HC-SR04. I timed three events, temp, humidity and distance (at 5 seconds, 7.5 seconds and 10 seconds). Threw in a millis reading at the end of each loop just to see how often it was going through the loop (and any delay processing). I prefer to update the previous time immediately after the If statement, just in case you are not putting the millis value into a variable like "currentTime" if(millis() - previousTime_1 >= eventInterval_1){ previousTime_1 = millis();
@@programmingelectronics I knew I was on the right track when I saw what you wrote was very similar to what I had come up with. I initially had down what you wrote, but then changed it at the last minute to just tighten it up a little. Doing three different events one after another, I played with both ways. The way you did it might be slightly more memory friendly, the way I did it will keep the timed events slightly more accurate. If we weren't playing around with milliseconds which increment pretty rapidly, I would have normally done it the way you did it. Thinking about it now, I wonder if I can test the value, and pipe it into the variable in the same action to try cut down the time difference even more? Hmmm another thought just occurred to me. If I put it back to the way you have it, and just reset the currentTime before the start of each event it might be even better still.
Yep I think just resetting the currentTime is a winner. That way it isn't so time critical when previousTime_x is updated. Although it is good to get it done out of the way and not forgotten. currentTime = millis() if(currentTime - previousTime_3 >= eventInterval_3){ previousTime_3 = currentTime;
@@programmingelectronics Yeah I think that is the way to go... You are capturing the value immediately before you do the If statement, so if it goes into the If (i.e the right amount of time has elapsed), you don't have any lag between the millis at the time of checking the If statement, and the time of storing in the previousTime variable. I think resetting the currentTime just before the next If can potentially make the difference of it stepping into the If statement and it not stepping in, on projects that require a very minimal delay between checks. If you only set it once and it takes say 50ms to run through the first If statement, in real time the internal counter has increased by 50ms but you are still using the old value. By putting a println of millis at the end of each loop, I noted that the average loop time for a non activity loop was about 7ms, but when it did a sensor check and printed to screen it was around 40-45ms. I have a 10ms Delay between LOW and HIGH Pin to get the reading. Since I am using 5, 7.5 and 10 second intervals (just random values) some loops will do nothing, some loops one activity, others two, and some three. On the ones that do three, the initial time set with currentTime = millis() will be way out by the time it enters the third If statement.
good to know things are: making a variable a constant with "const" will prevent accidentally changing the value later in the program and the compiler will generate an error: "error: assignment of read-only variable 'YourVariable' " "long" = -2,147,483,648 to 2,147,483,647 "unsigned long" = 0 to 4,294,967,295 unsigned just means that the value stored will never be smaller than 0
Great notes! I think the numbers on long and unsigned long need switched though in your comment: "long" = -2,147,483,648 to 2,147,483,647 "unsigned long" = 0 to 4,294,967,295
Thank you very much for explaining the millis() function in such detail. I want to use the millis() function as a monostable multivibrator. I would like to use a 300msec pulse on one of the outputs when a button is pressed. what program should I write? THX
Can you explane how to use millis() for pausing someting ? Like having a little wait loop for ex. 0.5 seconds before making the next without using delay().
Love ALL your videos. You mentioned one on interfacing the LDR and Temp sensor but couldn’t find it on your site. Could you supply me a link. Does it also deal with scaling analog readings to displayed units? Thanks so much. Wayne
This is an old video you probably won't respond, but if you see this then... I need help creating a photogate I know the equations etc. but I don't want to use an Arduino Zero or buy and RTC module, I have a short deadline for a project so I'm not sure if I have time to buy anything else online. I need the photogate to find the time it was broken then do an if statement like /=Divided By Time Broken Phototrsnisotr = millis() or something to get time between beam is broken and restored like a stopwatch Speed = Time Broken Phototransistor / Object Diameter if(Speed == 2 Meters Per Second) {Speed up or something}
thank you so much for this useful narration! Let's say i want to control the digital output with "millis" function. How do i set the exit working time without stopping the loop or other ?
What exactly do you want to use and for how long? You can use this same sketch he shows but instead of reading values and printing them, you can just set up a digital pin to become high or low. You'll need all the code without the display part for just one digital pin. I might have said it a weird way so if its confusing, ask again.
Hi there, your videos helps me a lot since I'm new for this, thank you a lot. Quick question about millis(), is it possible to make a wave of leds fading on and off on different LEDs at the same time like for example chroma lighting for keyboards? I try the whole week to learn how to create a code for this issue and it's very clear with the delay() function it's impossible to do so. Thank you beforehand!
Hello. I'm a beginner on arduino. I appreciate all your videos. Got a question. BTW isn't about the topic bu5 about memory or understanding how to better define variables or constants. Using const unsigned long for values of 1000 and 5000 would be like a waste of space on the memory? Can't they be declared like a type int variable? Got a couple weeks ago an advice on reddit about the use of delay. Your videos really help people who want to really understand how stuff work!
Yes, you are correct. I usually make an exception for values that deal with time, that way all the timing variable types are similar. Whatever variable you have tracking time from millis should definitely be a long, otherwise though, you are correct, and int would work fine. Great question.
If any of your multiple events take "significant" amounts of time, then your events are going to start drifting away from your intended intervals. To solve that, I would suggest replacing your lines "previousTime_1 = currentTime" etc with "previousTime_1 += eventTime_1_LDR" etc.
I enjoy your videos but this one has me stumped! I tried to substitute leds as a test as you suggested. My timing was led1 once every second and led2 once every 10 seconds. One the first loop it went well BUT following that both leds were on all the time! I tried with delays added and that allowed the leds to blink correctly. My uncertainty is based on the thought that we were to AVOID using delay??? By the way I am 79. Here is my code int led1 = 12; int led2 = 11; /* Two "independant" timed events */ const long eventTime_1_led1 = 1000; //in ms const long eventTime_2_led2 = 10000; //in ms /* When did they start the race? */ unsigned long previousTime_1 = 0; unsigned long previousTime_2 = 0; void setup() { //initialize digital pin led1 & led2 as an outputs. pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); Serial.begin(9600); } void loop() { /* Updates frequently */ unsigned long currentTime = millis(); /* This is my event_1 */ if ( currentTime - previousTime_1 >= eventTime_1_led1) { Serial.println("led1 "); digitalWrite (led1, HIGH); delay (100); digitalWrite (led1, LOW); /* Update the timing for the next event*/ previousTime_1 = currentTime; } /* This is my event_2 */ if ( currentTime - previousTime_2 >= eventTime_2_led2) { Serial.println("led2: "); digitalWrite (led2, HIGH); delay (100); digitalWrite (led2, LOW); delay (200); /* Update the timing for the next event*/ previousTime_2 = currentTime; } }
Awesome! So... you're obviously not guaranteed that your function is getting called "on time". If your other operations aren't too taxing on the processor, you'd be fine. Maybe it'd be interesting to display the millis or the variance to see how far off it was when the function was executed.
this is wonderful, i would like to program a variable time input so when the button-A is pushed for 1 second something will happen or when button-A is pushed for 2 seconds something else will happen, then maybe a 3rd event? thanks a lot...:)
Thank you very much for this tutorial. Theoretically soon after millis() overflows, previousTime variable will be larger than currentTime and the currentTime-previousTime will be a large negative value. Will not be this an issue?
Is there a potential problem, when millis() rolls over after 49 days, that the sensor updates to serial could stop when the if statement is not true and is there a way to avoid this happening?
Hi Steve, Great question. I am planning on releasing a video about the roll over (at some point...) In the meantime, you can check out this article on stack exchange arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover/12588#12588 Hope this helps some!
@@programmingelectronics sir please do a tutorial about this rollover problem of millis in a code. It is easier to understand your explaination than reading a book :)
For everyone worrying about the currentTime rollover after 3 weeks: If currentTime is smaller than previousTime, a rollover has happened. Check for this condition and then just set previousTime to zero (basically reset your program this wasy).
The rollover is handled automatically by this code. Do the maths in binary instead of thinking in decimal and you will find it works correctly as is. The key is to subtract the times rather than using addition.
hi, is there a way to have time events, but when the event happens, let it continue longer. For example, I want to turn on LED1 for 21 seconds straight, at the same time, turn on LED2 for 3 seconds then turn off LED2 for 4 seconds, then turn LED2 back on for 3 seconds and turn LED2 off for 4 more seconds, until the 21 seconds is up.
Yes, this is definitely possible. You could potentially break the 2nd LED event into two separate timed events, and set up different event variables for the turning on and turning off of the LED.
Can you explain how this method avoids overflowing of a unsigned long variable? I'm taking 4 readings from 4 different Distance Sensors and lighting up the LED on the basis of output I gathered from each sensor .But the values which is coming from distance sensors are overflowing the functions . I appreciate if you help me out.
How large in value can the current time variable grow to before it causes issues in the register? It is not a wiser choice to utilize a Count++ function that grows on every loop until it reaches the largest required count and then reset the count to zero and start over?
Help an idiot out. Is it necessary to assign currentTime to millis() and use currentTime in the conditional statements or can you just use the millis() function itself in the conditionals?
Sir, can I use milis() if say, I want to analogRead from my sensor every 16 ms? I have project to read voltage and current sensor from charging capacitor which is happend about 800 ms to fully charge. I want to measure 50 data point (AnalogRead()) from my sensor during 800 ms. I really appreciate your help Sir?
Cool project - > Yes, using millis() would allow you to sample something everything 16ms. If you look at the blink without delay example in the Arduino IDE, or watch this series, you should get a thorough idea of how to implement that in code.
This what you call High Quality Video.
Thank you!
Hey ive watched this series from part 1-6 and as someone with no prior coding experience, having to learn arduino and coding in a relatively short period of time for university has been quite challenging. I have an upcoming assessment where millis are crucial to the code so these videos were extremely helpful and I cant thank you enough!
Great to hear!
Really like your videos!! My 12 yr. old and I are learning together. My goal is to totally automate a greenhouse using Arduino. This video is exactly what we need.
Sounds like a cool project! It's great you and your son are learning it together.
I couldn't have said it better.@@programmingelectronics
Hi, I´d like to say how much great and important is this playlist to understanding millis function. I´ve been learning millis from excellent videos in Portuguese, Spanish and English, actually I've already watch the last two videos from this playlist weeks ago(maybe months), but only now after watch all the videos from this amazing and F. (funny) playlist I can say that I understand millis. Finally I can drink enjoying an amazing sunset knowing I understand the tensile strength of a rubber band, the Mayan calendar, the intimacy between space- time and black holes while my soul floats through ancient music. Thank You!
So glad it helped!
Man this millis series of you saves my life. Thanks a lot.
Glad it was helpful!
Got my first Arduino yesterday. Thought it could be fun to play with a fairly modern system. A lot to learn.
Made embedded real time multiprocessor systems decades ago. Both hardware and software, Intel 4040, 8051 8085, 80188. and Z80. Assembly & high level languages like PL/M and Modula-2.
This video made it clear how to structure a small stepper motor project.
Thanks for the note! I hope you have fun!
best millis explanation on tintanet understood instanly,, total new to arduino, never done any code, now ive got 6 led running without delay ... thks
Just what I was looking for ! I needed to slow down the up and down increment of the set rpm programme on an Arduino that uses a touchscreen display without using the despicable delay function , managed to slot this into one of the if statements inside aviod ReadControls function - works a treat and as this programme is interrupt based ( rpm sensor ) the delay is a big no no . 100 milliseconds did the trick .
Thank you !
So glad it helped!
Dude I would never have figured this out without you.. thank you
Awesome! I'm glad it helped!
the only person that explained millis the right way...thanks bro
I appreciate that Anakie!
You're the hero we need.
Thanks James ;)
thank you very much
That was very helpful and clear
I was struggling to understand the mills function until I saw your videos
thanks
Glad it helped - thanks so much for watching!
Timing can be confusing as all get out and it's not always easy to think through, let alone code.
This has to be best described video tutorial I have seen on almost any topic, very clear descriptions and well thought out content. First time visiting and cant wait to learn more from this channel.
Thank you so much. I’m working on a walking 4 legged robot and I didn’t want to use the delay function. This video saved my butt.
cool application - best of luck on our robot!
If you have 2 events like on this example, but the first one takes a considerable time to execute, because there are many instructions in between, I guess updating the currentTime variable with the newer mills value wouldn't harm and it's actually recommended to do so before every event.
How?
Great lessons; Easy to understand!
(I'm trying to develop multiple debounce sensors for my model railroading, using millis).
Thanks for the note Larry! Have you checkout Geoff Bunzas UA-cam Channel?
ua-cam.com/channels/KzeYLMEPxWGilqZTNuG0JA.html He uses Arduino in model railroading. Pretty neat stuff.
@@programmingelectronics
Thanks so much!
Thanks for the tip.
I'll check it out.
That was a cool series, I learnt a load of new stuff .. will go and do your full course now I think. Super clear!
Thanks Michael. A very well made tutorial and very helpful to me right now as I am writing my first code for an Arduino (aged 63 !) which will strike a bell every hour exactly. I would like to expand the program to move a stepper motor driven hour hand. A stepper motor tutorial would be great ;-). Best regards, Mike
Thanks Mike - nice work! Note taken on Steppers ;)
Excellent, I really enjoyed the millis series, I hope you can explain state machines in another video using the millis function.
Thanks Vasilis - that's a great idea, I'll look into it!
Great video and love the humor sprinkled in there. In your closing remarks relative to the IF statement……it would be nice to say you set the first previous time to zero….you did say it in the up front part. That is when “I got it”…..like you said walk thru it.
Great point! Thanks Steve.
Thank you for the nicely laid out tutorial. You showed a simple but effective way to plan out what to do, and then carry it out. While I have programmed in other environments before, I’m new to the Arduino, and you have made it easy to pick up the new parts. Cheers!
Glad it was helpful!
I saw an example code where someone created an array to hold the millis readings per item you want to manage, and the condition logic was within a function. That way the code was quite minimal. That was in the Doomsday Communicator UA-cam video where he demonstrated building a Lora chat device.
That sounds a lot cleaner, will have to check it out
You explained it really well, thank you, it really helped. Thanks for making this and all your videos!
Glad it was helpful!
Hey thanks! I didn't think I would need the millis function till I saw your videos about it.
I'm building a miniature dollhouse that I want to have music and dimmed lights. Using delay would have caused me some problems.
Great - I hope it helps!
Awesome! I find your lectures easy to understand. Thanks!
Thank you! I appreciate that!
Can't explain how much I love these videos ;~; luv u
Very nicely done with Millis function. Thank you.
Glad it was helpful!
hi! thank you so much for this series (btw I think you forgot to add this video to the playlist lol), it's super clear and your explanation is amazing
Thank you!
wow , the quality of your videos have improved alot
Thanks! Always trying to get better.
Absolutely amazing videos, i can do more about millis function by now, thank you for making this videos and keep it up! 😁😁😁
Thanks a ton Ivan!
Fantastic video. I've been watching the series and hoping you'd cover timed events using the Millis() function. Very difficult to get your head around that function and you have definitely helped.
Thanks Jake - I appreciate that! I often still scratch my head on using it well.
@@programmingelectronics i guess millis still sucks because if you have any delay()s in those timed events your entire timeline will be screwed up. i think to use millis everything has to be perfectly synchronized
@@yashaswikulshreshtha1588 I don't believe delay() effects the background count of the millis() function - millis() will keep counting. You might consider some timer libraries that trigger interrupts at specific times...
@@programmingelectronics I wanted to use millis for timed events but let's say if one event which turns on led has a delay in it then It won't affect millis counts but yes it will act as blocking code for other code pieces sometimes like permanent blockage, you can a event which happens every one second and then an event which happens every 3 seconds, so ofc the first will execute first but if u put delay of 3000 In it then the second event won't happen at all, it never will. I thought maybe I could use millis to run big code blocks having lot of functionalities. At timed intervals
@@programmingelectronics I would be really grateful if you can make video of classes and objects in Arduino. Probably no has explained good on UA-cam, but if u can make it, it will be on top and it will be helpful to all of us, cuz some of us are trying to learn actual programming concepts using arduino
Thank you so much this is the best arduino video
Thanks for watching!
Right traight to the point and it works!
I like the concept. Just not sure how you handle the rollover of the millis() count? In the reference documentation, millis() will rollover in about 50 days. Seems you should have to check for a rollover condition.
Amazing free content. Very well explained
Thanks!
Very high quality instruction. Thanks
Thanks Wayne!
Brilliant tutorial 👏
Thank you! I hope it helped!
This is some great stuff. Thanks!!
You are really good. How night celt you explain anybody can understand great job I too started learning don’t be surprised
Thanks!
nice, this what i was looking for.
intuitively I would have updated the previousTime with the interval, instead of the currentTime...
previousTime_1 += eventTime_1
but i expect differences to be minimal, a small (yet slowly increasing) delay in the currentTime version compared to my idea...
This vdo is really helpful for me understand to millis function. Just one question sir am using millis function for one LED blink off time and on time is same. How to change off time only means 1000 Ms is off time and on time is 500 ms. I think you you understand my question sir.
Nice video. I've got a use case that requires both event-driven and timer-driven functions so this was helpful.
Regarding your timer update, though, I think I would have updated previousTime_1 & previousTime_2 by ADDING their respective intervals back into them rather than updating to the current time. loop() is subject to blocking and there are other reasons that your loop might lag, so your implementation might creep (e.g. 0... 1003... 2003... 3005... 4006... 5007 vs 0... 1003... 2000... 3002... 4001... 5001). Staying truer to your intervals might be important.
You are good teacher *****
Thanks Ace!
lol how funny is that. I have not long finished writing code very similar to this, except I used a DHT22 and a HC-SR04. I timed three events, temp, humidity and distance (at 5 seconds, 7.5 seconds and 10 seconds). Threw in a millis reading at the end of each loop just to see how often it was going through the loop (and any delay processing). I prefer to update the previous time immediately after the If statement, just in case you are not putting the millis value into a variable like "currentTime" if(millis() - previousTime_1 >= eventInterval_1){ previousTime_1 = millis();
Thanks for sharing that! That makes for more succinct code for sure.
@@programmingelectronics I knew I was on the right track when I saw what you wrote was very similar to what I had come up with. I initially had down what you wrote, but then changed it at the last minute to just tighten it up a little. Doing three different events one after another, I played with both ways. The way you did it might be slightly more memory friendly, the way I did it will keep the timed events slightly more accurate. If we weren't playing around with milliseconds which increment pretty rapidly, I would have normally done it the way you did it. Thinking about it now, I wonder if I can test the value, and pipe it into the variable in the same action to try cut down the time difference even more? Hmmm another thought just occurred to me. If I put it back to the way you have it, and just reset the currentTime before the start of each event it might be even better still.
Yep I think just resetting the currentTime is a winner. That way it isn't so time critical when previousTime_x is updated. Although it is good to get it done out of the way and not forgotten.
currentTime = millis()
if(currentTime - previousTime_3 >= eventInterval_3){
previousTime_3 = currentTime;
Great thought - so adding that currentTime = millis() line before each if condition. Thanks again for sharing!
@@programmingelectronics Yeah I think that is the way to go... You are capturing the value immediately before you do the If statement, so if it goes into the If (i.e the right amount of time has elapsed), you don't have any lag between the millis at the time of checking the If statement, and the time of storing in the previousTime variable.
I think resetting the currentTime just before the next If can potentially make the difference of it stepping into the If statement and it not stepping in, on projects that require a very minimal delay between checks. If you only set it once and it takes say 50ms to run through the first If statement, in real time the internal counter has increased by 50ms but you are still using the old value.
By putting a println of millis at the end of each loop, I noted that the average loop time for a non activity loop was about 7ms, but when it did a sensor check and printed to screen it was around 40-45ms. I have a 10ms Delay between LOW and HIGH Pin to get the reading.
Since I am using 5, 7.5 and 10 second intervals (just random values) some loops will do nothing, some loops one activity, others two, and some three. On the ones that do three, the initial time set with currentTime = millis() will be way out by the time it enters the third If statement.
Nice Video. Do you wanna explain how to use the actuall timer to do such things faster than every millisecond?
super helpful, thank you!
Glad it was helpful!
Thanks very much!
Thank so much for your lensson in my a late night , it is my event !
great explanation
Glad it was helpful!
Thanks man, amazing video
I also like the title from the videos: "Unleash the millis()!" - Awesome! - not just the content :) Thanks very much!
good to know things are:
making a variable a constant with "const" will prevent accidentally changing the value later in the program and the compiler will generate an error: "error: assignment of read-only variable 'YourVariable' "
"long" = -2,147,483,648 to 2,147,483,647
"unsigned long" = 0 to 4,294,967,295
unsigned just means that the value stored will never be smaller than 0
Great notes! I think the numbers on long and unsigned long need switched though in your comment:
"long" = -2,147,483,648 to 2,147,483,647
"unsigned long" = 0 to 4,294,967,295
@@programmingelectronics yes you are correct i have mistakenly swapped the values ^^
Amazingly taught.
Thanks for watching!
Thank you very much for explaining the millis() function in such detail.
I want to use the millis() function as a monostable multivibrator.
I would like to use a 300msec pulse on one of the outputs when a button is pressed. what program should I write? THX
There are several event manager and timer libraries for Arduino which are much easier and more powerful than manually writing lots of millis() code.
Very true! It's fun to dive into some details. Do you have any specific libraries you would recommend?
Thank you. Just what I needed
Great - glad it could help. Thanks Gran's Stuff!
Sir keep making awesome courses . Soon will take your paid course its awesome . Love from india
Thank you Siddharth!
Well done!
Thank you!
Great explanation. I was wondering what happens when milis overflows. Would this stop working around day 49?
you're a genius
Thanks! I hope you found this helpful!
really helpful. thanks a lot.
Glad it was helpful!
So good! Thank you. Are you guys still uploading new content?
Yes! We have taken a break and been focusing on our member content for quite some time though.
Reall great.🙌 Thank you.❤
Thanks Joshua!
Can you explane how to use millis() for pausing someting ? Like having a little wait loop for ex. 0.5 seconds before making the next without using delay().
Excellent description. I just wanted to know weather i can use delay function in side the loop without affecting the over all working? Thanks.
Can you explain how this method avoids overflowing of a unsigned long variable?
Love ALL your videos. You mentioned one on interfacing the LDR and Temp sensor but couldn’t find it on your site. Could you supply me a link. Does it also deal with scaling analog readings to displayed units? Thanks so much. Wayne
Wonderful as always...
Thanks Ruwan!!!!
Well explained.
Thanks Hans!
Great tutorial!!! Two questions 1) the event's happen exactly in one and five seconds?? Instead of const uns... can I put define ...? Thanks
9:20 We can write this line as " if(currentTime >= previousTime_1 + eventTime_1_LDR)"
That way it is easy to understand!
You de best my man!!. What a way to explain things
Amazing. Subscribed
Awesome, thank you!
This is an old video you probably won't respond, but if you see this then...
I need help creating a photogate I know the equations etc. but I don't want to use an Arduino Zero or buy and RTC module, I have a short deadline for a project so I'm not sure if I have time to buy anything else online. I need the photogate to find the time it was broken then do an if statement like
/=Divided By
Time Broken Phototrsnisotr = millis() or something to get time between beam is broken and restored like a stopwatch
Speed = Time Broken Phototransistor / Object Diameter
if(Speed == 2 Meters Per Second) {Speed up or something}
You saved me thank you!!!!
Glad it helped!
thank you so much for this useful narration!
Let's say i want to control the digital output with "millis" function. How do i set the exit working time without stopping the loop or other ?
What exactly do you want to use and for how long? You can use this same sketch he shows but instead of reading values and printing them, you can just set up a digital pin to become high or low. You'll need all the code without the display part for just one digital pin. I might have said it a weird way so if its confusing, ask again.
Hi there, your videos helps me a lot since I'm new for this, thank you a lot.
Quick question about millis(), is it possible to make a wave of leds fading on and off on different LEDs at the same time like for example chroma lighting for keyboards?
I try the whole week to learn how to create a code for this issue and it's very clear with the delay() function it's impossible to do so. Thank you beforehand!
Hello. I'm a beginner on arduino. I appreciate all your videos. Got a question. BTW isn't about the topic bu5 about memory or understanding how to better define variables or constants. Using const unsigned long for values of 1000 and 5000 would be like a waste of space on the memory? Can't they be declared like a type int variable?
Got a couple weeks ago an advice on reddit about the use of delay. Your videos really help people who want to really understand how stuff work!
Yes, you are correct.
I usually make an exception for values that deal with time, that way all the timing variable types are similar. Whatever variable you have tracking time from millis should definitely be a long, otherwise though, you are correct, and int would work fine. Great question.
very nice tutorial!
Thank you!
If any of your multiple events take "significant" amounts of time, then your events are going to start drifting away from your intended intervals. To solve that, I would suggest replacing your lines "previousTime_1 = currentTime" etc with "previousTime_1 += eventTime_1_LDR" etc.
Veru nice i would like to explain how to setup 8relay depending on reading sensor ac voltage as example
I'm attempting that very thing right now!
I enjoy your videos but this one has me stumped! I tried to substitute leds as a test as you suggested.
My timing was led1 once every second and led2 once every 10 seconds. One the first loop it went well BUT following that both leds were on all the time! I tried with delays added and that allowed the leds to blink correctly. My uncertainty is based on the thought that we were to AVOID using delay???
By the way I am 79. Here is my code
int led1 = 12;
int led2 = 11;
/* Two "independant" timed events */
const long eventTime_1_led1 = 1000; //in ms
const long eventTime_2_led2 = 10000; //in ms
/* When did they start the race? */
unsigned long previousTime_1 = 0;
unsigned long previousTime_2 = 0;
void setup() {
//initialize digital pin led1 & led2 as an outputs.
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
Serial.begin(9600);
}
void loop() {
/* Updates frequently */
unsigned long currentTime = millis();
/* This is my event_1 */
if ( currentTime - previousTime_1 >= eventTime_1_led1) {
Serial.println("led1 ");
digitalWrite (led1, HIGH);
delay (100);
digitalWrite (led1, LOW);
/* Update the timing for the next event*/
previousTime_1 = currentTime;
}
/* This is my event_2 */
if ( currentTime - previousTime_2 >= eventTime_2_led2) {
Serial.println("led2: ");
digitalWrite (led2, HIGH);
delay (100);
digitalWrite (led2, LOW);
delay (200);
/* Update the timing for the next event*/
previousTime_2 = currentTime;
}
}
Thank you.
Thanks for watching!
Awesome! So... you're obviously not guaranteed that your function is getting called "on time". If your other operations aren't too taxing on the processor, you'd be fine. Maybe it'd be interesting to display the millis or the variance to see how far off it was when the function was executed.
this is wonderful, i would like to program a variable time input so when the button-A is pushed for 1 second something will happen or when button-A is pushed for 2 seconds something else will happen, then maybe a 3rd event? thanks a lot...:)
Thank you very much for this tutorial. Theoretically soon after millis() overflows, previousTime variable will be larger than currentTime and the currentTime-previousTime will be a large negative value. Will not be this an issue?
is there any function called micros? I mean what if I need the values in micro second. Can arduino produce that precise data?
Yes, there is a micros() function as well, that returns the number of microseconds:
www.arduino.cc/reference/en/language/functions/time/micros/
Is there a potential problem, when millis() rolls over after 49 days, that the sensor updates to serial could stop when the if statement is not true and is there a way to avoid this happening?
Hi Steve, Great question. I am planning on releasing a video about the roll over (at some point...) In the meantime, you can check out this article on stack exchange arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover/12588#12588 Hope this helps some!
@@programmingelectronics sir please do a tutorial about this rollover problem of millis in a code. It is easier to understand your explaination than reading a book :)
I think with another if statement ; if (previousTime_1 > 49days || previousTime_2 > 49days) {previousTime_1 = 0; previousTime_2 =0}
Please disable arduino ide showing line number for better readability of the code
For everyone worrying about the currentTime rollover after 3 weeks:
If currentTime is smaller than previousTime, a rollover has happened. Check for this condition and then just set previousTime to zero (basically reset your program this wasy).
The rollover is handled automatically by this code. Do the maths in binary instead of thinking in decimal and you will find it works correctly as is. The key is to subtract the times rather than using addition.
sir I have 1 question:
can we run both tasks at same time means both tasks at per second speed????????
hi, is there a way to have time events, but when the event happens, let it continue longer.
For example, I want to turn on LED1 for 21 seconds straight, at the same time, turn on LED2 for 3 seconds then turn off LED2 for 4 seconds, then turn LED2 back on for 3 seconds and turn LED2 off for 4 more seconds, until the 21 seconds is up.
Yes, this is definitely possible. You could potentially break the 2nd LED event into two separate timed events, and set up different event variables for the turning on and turning off of the LED.
Can you explain how this method avoids overflowing of a unsigned long variable?
I'm taking 4 readings from 4 different Distance Sensors and lighting up the LED on the basis of output I gathered from each sensor .But the values which is coming from distance sensors are overflowing the functions .
I appreciate if you help me out.
How large in value can the current time variable grow to before it causes issues in the register?
It is not a wiser choice to utilize a Count++ function that grows on every loop until it reaches the largest required count and then reset the count to zero and start over?
Hi. What about overflow?
great!
Hello.. can using currentTime_1=millis();, currentTime_2=millis(); ... etc . because if use many library using millis to. sory for my bad english
Could this be used to call lcd.clear without using delay?
So what happens in 49 days when current time rolls over?
Help an idiot out. Is it necessary to assign currentTime to millis() and use currentTime in the conditional statements or can you just use the millis() function itself in the conditionals?
You could use millis in the conditionals. Not an idiotic question at all.
Thank you very much!@@programmingelectronics 🙂
Sir, can I use milis() if say, I want to analogRead from my sensor every 16 ms? I have project to read voltage and current sensor from charging capacitor which is happend about 800 ms to fully charge. I want to measure 50 data point (AnalogRead()) from my sensor during 800 ms. I really appreciate your help Sir?
Cool project - > Yes, using millis() would allow you to sample something everything 16ms. If you look at the blink without delay example in the Arduino IDE, or watch this series, you should get a thorough idea of how to implement that in code.
@@programmingelectronics Thank you Sir. I am still to follow along series videos that you provide in this channel, Sir. very helpful. Many thanks Sir.