전자, 전기, 소프트웨어, 기계, 3D 프린터, 아두이노, 라즈베리파이, 쇼핑몰 창업

전체 페이지뷰

이 블로그 검색

최신글

[Blender] 3D viewport 사용법

[강좌] 9. 아두이노에서 delay 없이 LED 깜빡이기


무작정 보고 따라하며 배우는 아두이노 강좌입니다.
아두이노 공식 사이트에서 제공하는 강좌를 바탕으로 작성되었습니다.
해당 게시글은 Arduino UNO 보드를 기준으로 작성되었습니다.

9. delay 없이 LED 깜빡이기


- millis() 사용하여 LED 제어하기

  때때로 아두이노 코딩을 하다보면, 두가지 일을 작동시켜야 할 때가 있습니다. 이런 경우 delay()를 사용하면 코드 전체가 일시정지 되기 때문에 두가지 일을 한번에 할 수가 없습니다. 예를 들어, delay()를 사용하여 LED를 깜빡이는 작업을 하는 도중 버튼의 입력을 받아야 하는 경우가 생기면, 버튼을 눌렀을때 delay()가 발효된 상태라면 버튼의 입력을 읽어올 수 없습니다. 
  본 강좌에서는, delay()를 사용하지 않고 LED를 깜빡이는 방법을 알려드립니다. 이 방법은, LED를 시간에 흐름에 따라 키고 끄는 방식입니다. 그리고, loop() 함수 내에서 마지막 LED 제어 후 흐른 시간을 확인하여 LED를 제어하는 방법입니다. 이 방법을 사용하면 LED 제어를 별다른 지연없이 할 수 있게 됩니다.

준비물 ( 아두이노와 PC는 기본입니다 )

브레드보드, 점퍼케이블, LED, 220옴 저항

회로도

회로는 비교적 간단합니다. 위 회로처럼 외장 LED를 사용하지 않더라도, 아두이노의 내장 LED (13번핀)을 사용하면 LED의 깜빡임을 확인할 수 있습니다.

코드설명 

아래 코드는  millis() 를 사용합니다. 이 함수의 기능은 아두이노에 전원이 공급된 순간부터, 현재까지의 경과시간을 millisecond 단위로 알려줍니다.

먼저,  const int 를  setup() 보다 위에 작성하여 전역변수로 설정해 줍니다. 아래 코드에서는  int 만 사용해도 되지만,  const int 를 사용하는 이유는  const 의 경우 값이 변하지 않게 됩니다.  아래 코드에서는  ledPin 을  LED_BUILTIN 으로 지정했습니다.  LED_BUILTIN 으로 사용하면 보드에 따른 내장 LED 핀을 잡아줍니다. 내장 LED를 사용하지 않고 다른 핀에 연결한 외장 LED를 사용할 것이라면,  LED_BUILTIN 자리에 사용하는 핀 번호를 입력해주면 됩니다.

 const int ledPin = 핀번호; 

LED의 상태를 미리 지정해줍니다. 이후 LED의 상태를 제어하기 위해 변수로 지정합니다. 취향에 따라 HIGH 상태로 시작해도 무관합니다.

 int ledState = LOW; 

 millis() 를 사용하여 LED를 제어하기 위해 두번의 시간 체크가 필요합니다. 마지막으로 LED를 제어한 시간, 현재의 시간을 확인해야합니다. 마지막으로 제어한 LED의 시간을 저장하기위해 변수를 하나 지정해 줍니다.  millis() 의 값은 엄청나게 증가하기 때문에 약 42억까지 저장이 가능한 변수인  unsigned long 을 사용해줍니다.

 unsigned long previousMillis = 0; 

LED를 제어할 시간간격을 지정해 줍니다. 기존  delay() 를 사용하는 코드에서는  delay() 의 값을 지정해주는 것과 같습니다.  loop() 내에서 현재시간과 과거시간을 비교할 때 기준으로 사용합니다.  millis() 의 값과 비교하기 때문에  interval 의 단위를 똑같이  millisecond 로 지정해 줍니다.

 const long interval = 1000; 

 loop() 구문 내에서는 현재 시간을 나타내는 변수를 추가하여 현재시간/ 이전시간의 비교를 편하게 합니다. 마찬가지로 변수의 값이 매우 커질 수 있어  unsigned long 변수로 지정해 줍니다.

 unsigned long currentMillis = millis(); 

이후  previousMillis 와  currentMillis 의 차를 구하여 그 차가  interval 이상이 된다면,  previousMillis 를  currentMillis 와 같게하고 LED의 현 상태를 알아와서 HIGH면 LOW로 LOW면 HIGH로  digitalWrite() 해줍니다.

/* Blink without Delay

 Turns on and off a light emitting diode (LED) connected to a digital
 pin, without using the delay() function.  This means that other code
 can run at the same time without being interrupted by the LED code.

 The circuit:
 * Use the onboard LED.
 * Note: Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO 
  it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
  the correct LED pin independent of which board is used.
  If you want to know what pin the on-board LED is connected to on your Arduino model, check
  the Technical Specs of your board  at https://www.arduino.cc/en/Main/Products

 created 2005
 by David A. Mellis
 modified 8 Feb 2010
 by Paul Stoffregen
 modified 11 Nov 2013
 by Scott Fitzgerald
 modified 9 Jan 2017
 by Arturo Guadalupi


 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
 */

// 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);
  }
}

0 개의 댓글:

댓글 쓰기