아두이노 인터럽트로 제어하는 HIT 센서

2019. 7. 9. 12:08드론

인터럽트란?

실행 중인 프로그램을 일시 중단하고, 다른 프로그램을 끼워 넣어 실행시키는 것

attachInterrupt(pin_interrupt, ISR, mode)

  • 인터럽트가 발생할 때 호출할 인터럽트 서비스 루틴(ISR)을 지정

    • pin_interrupt은 인터럽트 번호(핀 번호가 다를 수 있다)
    • ISR은 인터럽트 발생시 호출될 함수
    • mode는 LOW, HIGH, CHANGE, RISING, FALLING으로 설정

 

  • 아두이노 우노 인터럽트 핀은 총 2개이며, INT0는 2번, INT1은 3번핀

    • 인터럽트 callback 함수는 파라미터를 전달하거나 리턴할 수 없음 (반드시 voidxx())
    • ISR 안에서는 delay() 함수를 사용할 수 없음
    • ISR 안에서 Serial data를 읽을 경우 소실됨

 

interrupts() 함수

  • 인터럽트 발생 허용

 

nointerrupts() 함수

  • 인터럽트 발생 금지

 

int pinHit = 2;
int count = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(pinHit, INPUT);
attachInterrupt(0, hitISR, FALLING);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print("HIT : ");
Serial.println(count);
delay(500);
}
void hitISR(void) {
count++;
}
view raw hit.c hosted with ❤ by GitHub

 

한 번 입력받을 때 LED를 toggle 시키는 소스코드, flag 변수를 이용해 중복을 없앴다

 

int pinHit = 2;
int pinLed = 13;
int ledStatus = LOW;
int count = 0;
volatile int flag = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(pinHit, INPUT);
pinMode(pinLed, OUTPUT);
attachInterrupt(0, hitISR, FALLING);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print("HIT : ");
Serial.println(count);
flag = 0;
digitalWrite(pinLed, ledStatus);
delay(500);
}
void hitISR(void) {
if(flag == 0) {
count++;
flag = 1;
ledStatus = !ledStatus;
}
}
view raw hit_led.c hosted with ❤ by GitHub