1

Is there a way I can use the delay command and have something else running in the background?

4 Answers 4

3

Kinda, if you use interrupts. delay itself uses these. But it's not as elegant as a multi-threaded solution (which is probably what you're looking for). There is a Multi-Threading library for Arduino but I'm not sure how well, or even if, it works.

The Arduino is only capable of running a single thread at a time meaning it can only do one thing at a time. You can use interrupts to literally interrupt the normal flow of your code but it's still technically not executing at the same time. The library I linked to attempts to implement what you might call a crude "hyper-threaded" solution. Two threads executing in tandem on a single physical processing core.

Sign up to request clarification or add additional context in comments.

2 Comments

Before multicore processors, there were many ''multithreaded'' processors, but none of them technically executed at the same time. Still though, they could do what can be considered true multithreading in a way that Arduino cannot do. The main difference being the way the stack and registers are saved and restored. That said, interrupts are a pretty good way to fake multithreading.
@Octopus yep. Intel's hyper-threading technology is a great example of that on a mass scale. All those Pentium 4 HTs that shipped before the introduction of the Core 2 Duo.
1

If you need other code to execute, you need to learn how to program with millis(). This involved converting your code from "step by step" execution to a time-based state machine.

For example if you want a LED to flash, you have two states for that LED: On and Off. You change the state when enough time has elapsed.

Here are a series of examples of how to convert delay()-based code into millis()-based code: http://www.cmiyc.com/blog/2011/01/06/millis-tutorial/

Comments

0

Usually all you need is a timer and a ISR routine. You won't manage to live without Interrupts :P Here you can find a good explanation about this.

Comments

0

I agree with JamesC4S, state machine is probably the right formalism to use in your case. You could for example try the ThingML language (which uses components, state machines, etc), and which compiles to Arduino code. A simple example can be found here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.