Pattern for doing 2 things at once.

I'm brand new to Arduino, but have a .Net development background.

What is the pattern that would be used if you want to pulse a LED (On for 1 sec, off for 1 sec), but at the same time, sound a buzzer every 300ms (On for 33ms, off for 300ms).

Because of the delay(1000) on the LED, the loop can't really handle the buzzer on/off. This is a threading issue, which I believe we have no threading.

So is there a pattern to handle this sort of situation?

It sounds like using delay in the loop is too blocking. Maybe some other timer? Spinning off a buzzer class that gets called to see if a change in the buzzer status should happen, and then loop has no delay... just Buzzer.Update() and MyLed.Update() and those methods somehow check a timer?

Take a look at Using millis() for timing. A beginners guide, Several things at the same time and look at the BlinkWithoutDelay example in the IDE.

I have found this youtube video useful for understanding blink without delay for two independent blinks.

UKHeliBob:
Take a look at Using millis() for timing. A beginners guide, Several things at the same time and look at the BlinkWithoutDelay example in the IDE.

Thanks! That is a fantastic post! Reading now... and it makes sense... Thanks.

Cralis:
Thanks! That is a fantastic post! Reading now... and it makes sense... Thanks.

So basically, here you are the OS, you yourself will handle the threads slicing.

I wonder if anyone has ever counted what % of forum questions relate to this? Probably about 90%. And another 90% is about servo power, and let's not forget the 90% about switch edge detection.

neiklot:
I wonder if anyone has ever counted what % of forum questions relate to this? Probably about 90%. And another 90% is about servo power, and let’s not forget the 90% about switch edge detection.

I don’t believe any of those figures.

A recent study showed that 84% of all statistics quoted on the Web are invented to suit the poster’s case :slight_smile:

UKHeliBob:
A recent study showed that 84% of all statistics quoted on the Web are invented to suit the poster's case :slight_smile:

LOL

...R

Thanks guys. I followed that example of using millis and have a flashing and fading LED. That’s way better.

I fear it could get quite complex. But much better nevertheless. I’ll try with an input next.

Great help. Thanks.

Cralis:
I fear it could get quite complex.

It will, but so what if you have a zillion previousMillisRedLed and previousMillisLeftMotor and so on... you can manage them all from calls in loop() and keep everything tidy.

There are also a couple of "blink without delay in a box" examples around, such as this Flasher class at adafruit.

Thanks nieklot! Just read that. Looking forward to now trying the more improved OOP version of my millis demo I’ve made. Thats going to make life a lot easier. Great article once again. Thanks for the link.

As they say there "Put a little OOP in your loop"