wil
wil

Reputation: 171

How to use delays in Arduino code?

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

Upvotes: 1

Views: 851

Answers (4)

bmorin
bmorin

Reputation: 645

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.

Upvotes: 0

JamesC4S
JamesC4S

Reputation:

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/

Upvotes: 1

Daniele Costarella
Daniele Costarella

Reputation: 113

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.

Upvotes: 0

Kevin Mark
Kevin Mark

Reputation: 1671

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.

Upvotes: 3

Related Questions