Introduction
In our previous guide on how to Make a Sound with a Piezo Buzzer, the tone() function and delay() function were used to generate sound. Instead of using delay(), we can use millis(), with the added advantage of multi-tasking.Â
In this guide, learn to use the millis() function instead to create an alarm sound. You will learn about the difference between the delay() function and millis() function, as well as when to use the latter.
Complete this guide to learn to use the millis() function in your Arduino sketches.
Tools
-
-
-
-
-
const int buzzerPin = 9; const int LED = 13; void setup () { pinMode(buzzerPin, OUTPUT); pinMode(LED, OUTPUT); } void loop () { tone(buzzerPin, 1000, 500); delay(3000); digitalWrite(LED, HIGH); delay(1000); digitalWrite(LED, LOW); delay(1000); }
-
int LED = 13; bool ledState; void setup() { Serial.begin(9600); pinMode(LED, OUTPUT); // initialize the digital pin as an OUTPUT digitalWrite(LED, HIGH); // turn LED on ledState = true; // LED is on } void loop() { if (ledState == HIGH) { delay(5000); digitalWrite(LED, LOW); // turn LED off ledState = false; // prevent this code being run more then once Serial.println("Turned LED Off"); } //Other loop code here Serial.println("Run other code"); }
-
const int LED = 13; // the number of the built-in LED pin int ledState = LOW; // Generally, you should use "unsigned long" for variables that hold time // The value will quickly become too large for an int to store unsigned long previousMillis = 0; // will store last time LED was updated const long interval = 5000; // interval at which to blink (milliseconds) void setup() { Serial.begin(9600); pinMode(LED, OUTPUT); // initialize the digital pin as an output. } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { // save the last time you blinked the LED previousMillis = currentMillis; // if the LED is off turn it on and vice-versa: if (ledState == LOW) { ledState = HIGH; } else { ledState = LOW; } // set the LED with the ledState of the variable: digitalWrite(LED, ledState); } // Other loop code here Serial.println("Run Other Code"); }
-
const int buzzerPin = 9; const int onDuration = 1000; const int periodDuration = 5000; unsigned long lastPeriodStart; void setup () { pinMode(buzzerPin, OUTPUT); Serial.begin(9600); } void loop () { if (millis() - lastPeriodStart >= periodDuration) { lastPeriodStart += periodDuration; tone(buzzerPin, 550, onDuration); } // Other loop code here . . . Serial.println("Run Other Code"); }