// Delay-Free Timing 01 // // The Arduino has a built in clock that gives out the number of // milliseconds the Arduino has been running since the last reset // (it actually is a finite number, and resets to 0 after about // 9 hours and 32 minutes). We can use this number, millis(), to // check how long it has been since something has happened, like // the last time an LED was turned on. This can eliminate the bottleneck // caused by the delay() command. // Set variables // Set up three timers, each with a different offset to check against. long timer1 = 0; // Timers are measured in milliseconds, which quickly get quite large. // We'll use "long" instead of "int" because int can only store a number // from -32,768 to 32,768, or + or - 2 to the 15th power, or 2 bytes. // "long" extends the range to 4 bytes, or +/- 2,147,483,684 int timer1offset = 1000; // timer1offest will hold the length of time were using instead of a delay() // Setup pins int ledPin1 = 13; void setup() { // The standard stuff... Serial.begin(9600); // Setup the serial communications so we can debug pinMode(ledPin1, OUTPUT); timer1 = millis(); // Setting the timer to the milliseconds since the board was reset } // Das Loop... void loop() { // Timer 1 if((timer1 + timer1offset) < millis() ) { // In other words, if timer1 plus an offset, say // 123 + 1000 is less than the current time, say 1300, // then the timer is finished, so do something and reset // the timer to the current time doFlash(); // doFlash is a custom function we wrote ourselves, // as opposed to a built-in command. timer1 = millis(); } } // A new function! void doFlash() { Serial.println(digitalRead(ledPin1)); // Output the status to the serial port digitalWrite(ledPin1, !digitalRead(ledPin1)); // This is a neat trick. "!" means "not" // in Arduino language. When we say // !digitalRead(ledPin1) we're saying // "make this statement the opposite // of what is says" }