The "hello world" of the Arduino is the blink sketch. This demonstrates that your board is working by blinking an LED, typically the on-board LED attached to pin13 but it has a problem.
The code uses the "delay" function which waits the desired number of milliseconds before continuing with the next line of the code.
int led = 13; void setup() { // initialize the digital pin as an output. pinMode(led, OUTPUT); } void loop() { digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(led, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second //Code here runs once every 2 seconds }
The problem with the delay function is that nothing else happens whilst the delay is running. This is not only wasteful of the limited processing power of the microcontroller but it also makes any other routines you are using potentially unresponsive. There are several approaches to this problem such as using interrupts. The approach I selected to use a class which implement the non blocking delay.
This delay is implemented with a variable and two function, the first sets the delay and the second checks if the delay has finished.
Here's how it is used:
#include "Delay.h" int led = 13; int ledstate = HIGH; NonBlockDelay d; void setup() { pinMode(led, OUTPUT); } // the loop routine runs over and over again forever: void loop() { if (d.Timeout()) { digitalWrite(led, ledstate); ledstate = ledstate == LOW ? HIGH : LOW; //toggle state d.Delay(1000); } //Code here runs frequently }
Delay.h
#if defined(ARDUINO) && ARDUINO >= 100 #include <Arduino.h> #else #include <WProgram.h> #endif class NonBlockDelay { unsigned long iTimeout; public: void Delay (unsigned long); bool Timeout (void); unsigned long Time(void); };
Delay.cpp
#include "Delay.h" void NonBlockDelay::Delay (unsigned long t) { iTimeout = millis() + t; return; }; bool NonBlockDelay::Timeout (void) { return (iTimeout < millis()); } unsigned long NonBlockDelay::Time(void) { return iTimeout; }
My reason for wrapping the delay in a class is so that I can use it for twice for each of the steppers in my clock project and so my loop will end up as a series of non blocking calls.
void loop() { CheckInput(); ReadClock(); CalcHandPositions(); SetStepperPositions(); StepMotors(); }
Top Comments