Arduino 보드를 처음 사용 했을 때 아마도 다음과 같이 했을 것입니다.
- Arduino에 LED를 연결했습니다.
- 1초마다 LED를 켜고 끄는 기본 깜박임 스케치를 업로드했습니다.
이것은 Arduino의 "Hello World" 프로그램이라고 하며
몇 줄의 코드로 실제 응용 프로그램이 있는 무언가를 만들 수 있음을 보여줍니다.
앞의 예에서 delay() 함수를 사용하여 LED가 켜지고 꺼지는 간격을 정의합니다.
delay() 는 편리하고 기본적인 예제에서는 작동하지만 실제로 사용해서는 안 됩니다.
이유를 알아보려면 계속 읽으십시오.
어떻게 delay() 함수는 작용하나
Arduino delay() 함수가 작동하는 방식은 매우 간단합니다.
단일 정수를 인수로 허용합니다.
이 숫자는 프로그램이 다음 코드 줄로 이동할 때까지 기다려야 하는 시간(밀리초)을 나타냅니다.
delay(1000)을 수행하면 Arduino가 해당 라인에서 1초 동안 멈춥니다.
delay() 는 차단 함수입니다.
차단 기능은 특정 작업이 완료될 때까지 프로그램이 다른 작업을 수행하지 못하도록 합니다.
동시에 여러 작업을 수행해야 하는 경우 delay() 를 사용할 수 없습니다.
애플리케이션에서 입력에서 데이터를 지속적으로 읽고 저장해야 하는 경우
delay() 함수를 사용하지 않아야 합니다. 다행히 해결책이 있습니다.
해결책으로 millis() 함수
millis() 함수는 프로그램이 처음 시작된 이후 경과 한 시간 (밀리 초)을 반환합니다.
왜 유용한가요?
약간의 수학을 사용하면 코드를 차단하지 않고도
시간이 얼마나 지났는지 쉽게 확인할 수 있기 때문입니다.
아래 스케치는 millis()함수를 사용하여 깜박임 프로젝트를 만드는 방법을 보여줍니다 .
LED 조명을 1000밀리초 동안 켠 다음 끕니다. 그러나 비차단 방식( non-blocking)으로 수행합니다 .
delay() 없이 작동하는 깜박임 스케치를 자세히 살펴보겠습니다.
/*
Blink without Delay, example here: arduino.cc/en/Tutorial/BlinkWithoutDelay
*/
// constants won't change. Used here to set a pin number :
const int ledPin = 13; // the number of the LED pin
// Variables will change :
int ledState = LOW; // ledState used to set the LED
// 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
// constants won't change :
const long interval = 1000; // interval at which to blink (milliseconds)
void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
}
void loop() {
// here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
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(ledPin, ledState);
}
}
위의 이 스케치는 여기 에서 찾을 수 있으며
현재 시간( currentMillis )에서 이전에 기록된 시간( previousMillis )을 빼서 작동합니다 .
나머지가 간격(이 경우 1000밀리초)보다 크면
프로그램은 previousMillis 변수를 현재 시간으로 업데이트 하고 LED를 켜거나 끕니다.
그리고 non-blocking 이므로 첫 번째 if 문 외부에 있는 모든 코드는 정상적으로 작동해야 합니다.
이제 loop() 함수에 다른 작업을 추가할 수 있습니다.
코드가 여전히 1초마다 LED를 깜박임을 이해할 수 있습니다.
어떤 기능을 사용해야 할까요?
우리는 Arduino로 시간을 다루는 두 가지 다른 방법을 배웠습니다.
millis()를 사용하는 것은 delay() 사용에 비해 추가 작업을 조금 더 할 수 있습니다
[출처번역인용] https://randomnerdtutorials.com/why-you-shouldnt-always-use-the-arduino-delay-function/