Using Arduino Delay and Millis Commands: Arduino for Beginners

Arduino beginners will probably spend a lot of time on the Arduino Playground, exploring and experimenting with the sketches others have written. As you gain experience and begin to write your own sketches, understanding the difference between the delay() and millis() commands is essential.

Despite sharing some superficial commonalities, these two commands are quite different and useful for different kinds of applications. Here, we’ll clarify the difference and examine how to start using the Arduino millis() command effectively.

Arduino Commands: Millis vs. Delay 

Let’s start with the similarities:

1. You can use both delay() and millis() commands to regulate the timing of operations.

2. We measure both in milliseconds.

The differences, however, are what make the millis() command really shine. Simply put, the primary difference is that the delay() command regulates the timing of an activity (such as blinking an LED) by temporarily suspending nearly all of the Arduino’s functions for a specified amount of time. The millis() command, on the other hand, bases its timing on changes in a timer that starts at 0 and continues to advance, unrelated to other activities, then pauses and begins again.

In practical terms, while the delay() function interrupts the other processes – essentially putting everything on hold – the millis() command can establish timing without interrupting other functions, enabling a sort of “multitasking” effect.

For a very simple sketch, like making an LED blink without other functionality, the delay() command may be sufficient. After all, the unit doesn’t need to accomplish anything else in the time that the LED is on or off. If, however, your task involves more “moving parts” (such as blinking the LED and periodically printing out a counter), you’ll need millis() to do that.

In such a case, you can use the millis() command to set each task to occur when the counter reaches a certain difference (such as blinking every 500ms and printing out every 1500ms).

Millis () Code Example:

const byte ledPin =  13; //the number of the LED pin
byte ledState = 0; //ledState used to set the LED
unsigned long previousMillis1 = 0; //will store last time LED was updated
unsigned long interval1 = 500; //interval at which to blink (milliseconds)
unsigned long previousMillis2 = 0;
unsigned long interval2 = 1500;
unsigned int counter = 0;

void setup() {
  Serial.begin(19200);
  delay(2000);
  pinMode(ledPin, OUTPUT); //set the digital pin as output:
}

void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis1 > interval1) {
    previousMillis1 = currentMillis; // save the last time I blinked the LED
    //if the LED is off turn it on and vice-versa:
    ledState ^= 1;
    digitalWrite(ledPin, ledState);
  }
  currentMillis = millis();
  if (currentMillis - previousMillis2 > interval2) {
    previousMillis2 = currentMillis; // save the last time I printed on the serial
    Serial.println(++counter);
  }
}

Looking at the code above, which we developed by slightly modifying this code, you can see that the command doesn’t stop the total functioning of the Arduino. Therefore, both tasks can occur on their own schedules without interruption.

How to Use Arduino Millis 

The delay() function is a great starting point, and you can use it to accomplish many simple tasks. It’s one of the first commands you’re likely to learn, but as you move forward and develop more complicated sketches, you should get familiar with the millis() command, which lets you run more complicated sketches with more tasks without the stops that delay() causes. For more detailed explanations of these commands and their differences, take a look at this post on the Arduino Forum or the tutorial by Norwegian Creations.

 

관련 뉴스 기사

최신 뉴스

Sorry, your filter selection returned no results.

개인정보 보호정책이 업데이트되었습니다. 잠시 시간을 내어 변경사항을 검토하시기 바랍니다. 동의를 클릭하면 Arrow Electronics 개인정보 보호정책 및 이용 조건에 동의하는 것입니다.

당사의 웹사이트에서는 사용자의 경험 향상과 사이트 개선을 위해 사용자의 기기에 쿠키를 저장합니다. 당사에서 사용하는 쿠키 및 쿠키 비활성화 방법에 대해 자세히 알아보십시오. 쿠키와 추적 기술은 마케팅 목적으로 사용될 수 있습니다. '동의'를 클릭하면 기기에 쿠키를 배치하고 추적 기술을 사용하는 데 동의하는 것입니다. 쿠키 및 추적 기술을 해제하는 방법에 대한 자세한 내용과 지침을 알아보려면 아래의 '자세히 알아보기'를 클릭하십시오. 쿠키 및 추적 기술 수락은 사용자의 자발적 선택이지만, 웹사이트가 제대로 작동하지 않을 수 있으며 사용자와 관련이 적은 광고가 표시될 수 있습니다. Arrow는 사용자의 개인정보를 존중합니다. 여기에서 당사의 개인정보 보호정책을 읽을 수 있습니다.