아두이노 푸쉬버튼 OneButton library 사용하기

시작하기

이 포스트의 테스트는 esp32보드를 사용했습니다.
아두이노 푸쉬버튼을 직접 구현하는 방법이 있습니다. 커스텀에 아주 유용하게 사용할 수 있지만, 코드의 복잡성과 유지보수 혹은 에러 처리에 많은 어려움이 있을 것으로 보아 라이브러리를 찾던도중 가장 사용법이 쉬워보이고 star도 많이 받은것으로 보여 OneButton 라이브러리를 사용하게 됐습니다.

설치하기

아두이노 IDE에서 onebutton 패키지를 검색합니다.

패키지 검색

패키지를 검색하고 설치합니다.

코드 작성

버튼을 26번 핀에 연결했습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <OneButton.h>

/**
* Initialize a new OneButton instance for a button
* connected to digital pin 4 and GND, which is active low
* and uses the internal pull-up resistor.
* https://github.com/mathertel/OneButton
*/
#define BUTTON_PIN 26

OneButton button = OneButton(
BUTTON_PIN, // Input pin for the button
true, // Button is active LOW
true // Enable internal pull-up resistor
);

void singleClick()
{
Serial.println(" 한번 클릭 했습니다.");
}

void doubleClick()
{
Serial.println(" 더블 클릭했습니다.");
}

void longPress()
{
Serial.println(" 버튼을 길게 눌렀습니다.");
}

void setupButton()
{
button.attachClick(singleClick);
button.attachDoubleClick(doubleClick);
button.attachLongPressStop(longPress);
}

setup(){
Serial.begin(9600);
}

loop(){
button.tick(); // 버튼을 인식하는 부분 입니다.
}

결과

버튼을 클릭하면 다음과 같은 출력값을 확인 할 수 있습니다.

버튼 클릭 결과

Share