개발자/Arduino

아두이노 짧은 시간 Delay 사용 하지 않는 코드

지구빵집 2023. 10. 18. 08:20
반응형

 

Dela(1000분의 1초 숫자) 함수를 사용하는 것은 우리의 유능한 아두이노의 마이크로 프로세서를 익사시키는 일과 같다. 제어 코드를 실행하는 과정에 Delay( ) 함수를 만나면 아무일도 못하고(예외가 있는데 외부 입역 인터럽트나 타이머 인터럽트는 실행된다.) 기다린다. 한없이 기다린다. 아무일도 하지 않고 그저 기다린다. 이것은 어마어마한 낭비다.

 

그래서 여기서는 Fade in, out 즉 점점 LED 밝기가 점점 환해지거나 흐려지는 동작을 delay 함수를 쓰지 않고 사용하는 방법을 살펴 본다. 이와 같은 방법은 자주 사용하므로 정확히 알아두는게 개발자로 사는데에 도움이 된다. 믿어라.

 

아두이노 예제 코드에서 페이딩 예제를 한 번 살펴보면

 

int led = 9;         // the PWM pin the LED is attached to
int brightness = 0;  // how bright the LED is
int fadeAmount = 5;  // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

 

파일 -> 예제 -> 01.Basics -> Fade 예제입니다. 소스를 보면 delay(30) 부분이 찝찝합니다. 짧은 시간이지만 이 시간 동안 아두이노는 다른 일을 할 수 없게 됩니다. 그렇다고 없으면 동작에 구분이 안되어 패이딩 효과를 나타낼 수 없습니다. 

 

 

멀티태스킹 코딩이란 delay(), for 반복문, while 반복문 등은 아주 짧은 시간이 아니면 사용하지 말아야 합니다. 인터넷에서 for 반복문을 사용한 소스를 구해서 멀티태스킹 소스로 바꾸어야 한다면 Fading 예제를 Fade 예제로 바꾼 것 처럼 for 반복문을 if 조건문을 사용하여 수정합니다. 

 

파일 -> 예제 -> 02.Digital -> BlinkWithoutDelay 예제입니다. 파일명 그대로 delay() 함수를 사용하지 않고 블링크 동작을 하는 소스입니다. 아두이노가 멀티태스킹을 할려면 delay() 함수를 어떻게 바꾸어야 하는지 교본같은 소스입니다. 

 

// constants won't change. Used here to set a pin number:
const int ledPin = LED_BUILTIN;  // 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);
  }
}

 

특정 시간 간격마다 실행되는 소스 :

 

이런 좋은 소스를 보면 자주 사용할 것 같으므로 양식(form)으로 만들어 두면 자산이 됩니다. 예를 들면 온습도 센서값를 10초마다 읽고 싶을 때 등 다양한 곳에 응용할 수 있습니다. 특정 시간 간격마다 실행되는 양식을 만들어 봅니다. 

 

unsigned long previousMillis = 0;

const long interval = 10000;           // 10초

void setup() {
}

void loop() {

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
   // 10초마다 동작해야 하는 부분 코딩
  }
}

 

 

아래 코드는 특정 시간 간격마다 실행되는 코드를 보여줍니다. 여기서 인터벌 간격은 30msec 로 설정하였어요. 다른 시간이라도 얼마든지 잘 동작하는 코드입니다. 중요한 코드니까 반드시 익히길 바랍니다.

 

int ledPin = 9;
int brightness = 0;
int fadeAmount = 5;
unsigned long previousMillis = 0;
const long interval = 30;            // 30밀리초 주기로 동작
void setup() {
  pinMode(ledPin, OUTPUT);
 }
void loop() {
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    
    analogWrite(ledPin, brightness);
    brightness = brightness + fadeAmount;
    
    if (brightness == 0 || brightness == 255) {
      fadeAmount = -fadeAmount ;
    }
  }
}

 

이거 적용해서 원격 조명기기 제어 프로그램을 다시 짜기로 한다. 즉시 한다. 악마는 우리가 마음을 놓거나 잠시 한눈 파는 사이에 귀신같이 들어와 훼방을 놓고 사라진다. 조심해라!

 

 

문제가 되면 쉽게 해결한다. 그러니 일단 실행한다.

 

 

반응형