파이썬 스크립트 파일 short_press.py을(를) 생성하고 다음 코드를 추가하십시오.
/* * 이 라즈베리 파이 코드는 newbiely.kr 에서 개발되었습니다 * 이 라즈베리 파이 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/raspberry-pi/raspberry-pi-button-long-press-short-press */import RPi.GPIOasGPIOimport timeBUTTON_PIN = 16SHORT_PRESS_TIME = 0.5 # 500 millisecondsDEBOUNCE_TIME = 0.1 # 100 milliseconds# Variables will change:prev_button_state = GPIO.LOW# the previous state from the input pinbutton_state = None# the current reading from the input pinpress_time_start = 0press_time_end = 0# Set up GPIO and configure the pull-up resistorGPIO.setmode(GPIO.BCM)GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)try:whileTrue:# Read the state of the switch/button button_state = GPIO.input(BUTTON_PIN)# Perform debounce by waiting for DEBOUNCE_TIME time.sleep(DEBOUNCE_TIME)if prev_button_state == GPIO.HIGHand button_state == GPIO.LOW: # Button is pressed press_time_start = time.time()elif prev_button_state == GPIO.LOWand button_state == GPIO.HIGH: # Button is released press_time_end = time.time() press_duration = press_time_end - press_time_startif press_duration < SHORT_PRESS_TIME:print("A short press is detected")# Save the last state prev_button_state = button_stateexceptKeyboardInterrupt:print("\nExiting the program.")GPIO.cleanup()
파일을 저장하고 터미널에서 다음 명령을 실행하여 Python 스크립트를 실행하세요:
python3 short_press.py
버튼을 짧게 여러 번 누르세요.
터미널에서 결과를 확인하세요.
PuTTY - Raspberry Pi
A short press is detected
A short press is detected
A short press is detected
스크립트는 터미널에서 Ctrl + C를 누를 때까지 무한 루프에서 계속 실행됩니다.
길게 누르기를 감지하는 방법
긴 누르기를 인식하는 두 가지 시나리오가 있습니다:
버튼이 해제된 직후에 롱 프레스 이벤트가 식별됩니다.
버튼이 눌린 상태에서도, 해제되기 전에도 롱 프레스 이벤트가 식별됩니다.
첫 번째 시나리오에서는 누름 및 해제 이벤트 사이의 지속 시간이 계산됩니다. 이 지속 시간이 미리 정해진 시간을 초과하면, 롱 프레스 이벤트가 식별됩니다.
두 번째 시나리오에서는 버튼이 눌렸을 때, 버튼을 뗄 때까지 누른 시간을 지속적으로 확인합니다. 버튼을 누르고 있는 동안 시간이 미리 정해진 시간을 초과하면, 롱프레스 이벤트가 감지됩니다.
라즈베리 파이 코드: 버튼을 떼면 롱 프레스 감지
자세한 사용 방법
Python 스크립트 파일 long_press_1.py을 생성하고 다음 코드를 추가하세요:
/* * 이 라즈베리 파이 코드는 newbiely.kr 에서 개발되었습니다 * 이 라즈베리 파이 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/raspberry-pi/raspberry-pi-button-long-press-short-press */import RPi.GPIOasGPIOimport timeBUTTON_PIN = 16LONG_PRESS_TIME = 1.0 # 1 secondsDEBOUNCE_TIME = 0.1 # 100 milliseconds# Variables will change:prev_button_state = GPIO.LOW# the previous state from the input pinbutton_state = None# the current reading from the input pinpress_time_start = 0press_time_end = 0# Set up GPIO and configure the pull-up resistorGPIO.setmode(GPIO.BCM)GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)try:whileTrue:# Read the state of the switch/button button_state = GPIO.input(BUTTON_PIN)# Perform debounce by waiting for DEBOUNCE_TIME time.sleep(DEBOUNCE_TIME)if prev_button_state == GPIO.HIGHand button_state == GPIO.LOW: # Button is pressed press_time_start = time.time()elif prev_button_state == GPIO.LOWand button_state == GPIO.HIGH: # Button is released press_time_end = time.time() press_duration = press_time_end - press_time_startif press_duration >= LONG_PRESS_TIME:print("A long press is detected")# Save the last state prev_button_state = button_stateexceptKeyboardInterrupt:print("\nExiting the program.")GPIO.cleanup()
파일을 저장하고 터미널에서 다음 명령을 실행하여 Python 스크립트를 실행하십시오:
python3 long_press_1.py
버튼을 2초 동안 누른 후 버튼을 놓으세요.
터미널에서 결과를 확인하세요.
PuTTY - Raspberry Pi
A long press is detected
버튼이 놓였을 때만 길게 누르는 이벤트가 인식됩니다.
누름 중 장시간 눌림을 감지하는 Raspberry Pi 코드
자세한 사용 방법
파이썬 스크립트 파일 long_press_2.py를 작성하고 다음 코드를 추가하세요.
/* * 이 라즈베리 파이 코드는 newbiely.kr 에서 개발되었습니다 * 이 라즈베리 파이 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/raspberry-pi/raspberry-pi-button-long-press-short-press */import RPi.GPIOasGPIOimport timeBUTTON_PIN = 16LONG_PRESS_TIME = 1.0 # 1000 milliseconds (1 second)# Variables will change:prev_button_state = GPIO.LOW# the previous state from the input pinbutton_state = None# the current reading from the input pinpress_time_start = 0is_pressing = Falseis_long_detected = False# Set up GPIO and configure the pull-up resistorGPIO.setmode(GPIO.BCM)GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)try:whileTrue:# Read the state of the switch/button button_state = GPIO.input(BUTTON_PIN)if prev_button_state == GPIO.HIGHand button_state == GPIO.LOW: # Button is pressed press_time_start = time.time() is_pressing = True is_long_detected = Falseelif prev_button_state == GPIO.LOWand button_state == GPIO.HIGH: # Button is released is_pressing = Falseif is_pressing andnot is_long_detected: press_duration = time.time() - press_time_startif press_duration > LONG_PRESS_TIME:print("A long press is detected") is_long_detected = True# Save the last state prev_button_state = button_stateexceptKeyboardInterrupt:print("\nExiting the program.")GPIO.cleanup()
파일을 저장하고 터미널에서 다음 명령을 실행하여 Python 스크립트를 실행하세요:
python3 long_press_2.py
버튼을 누르고 몇 초간 유지한 후 버튼에서 손을 떼세요.
시리얼 모니터에서 결과를 확인하세요.
PuTTY - Raspberry Pi
A long press is detected
버튼이 놓이지 않았을 때도 길게 누르는 이벤트만 감지됩니다.
길게 누르기와 짧게 누르기를 모두 감지하는 방법
자세한 사용 방법
파이썬 스크립트 파일 long_short_press.py을(를) 생성하고 다음 코드를 추가하십시오:
/* * 이 라즈베리 파이 코드는 newbiely.kr 에서 개발되었습니다 * 이 라즈베리 파이 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/raspberry-pi/raspberry-pi-button-long-press-short-press */import RPi.GPIOasGPIOimport timeBUTTON_PIN = 16SHORT_PRESS_TIME = 0.5 # 500 millisecondsLONG_PRESS_TIME = 1.0 # 1 secondsDEBOUNCE_TIME = 0.1 # 100 milliseconds# Variables will change:prev_button_state = GPIO.LOW# the previous state from the input pinbutton_state = None# the current reading from the input pinpress_time_start = 0press_time_end = 0# Set up GPIO and configure the pull-up resistorGPIO.setmode(GPIO.BCM)GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)try:whileTrue:# Read the state of the switch/button button_state = GPIO.input(BUTTON_PIN)# Perform debounce by waiting for DEBOUNCE_TIME time.sleep(DEBOUNCE_TIME)if prev_button_state == GPIO.HIGHand button_state == GPIO.LOW: # Button is pressed press_time_start = time.time()elif prev_button_state == GPIO.LOWand button_state == GPIO.HIGH: # Button is released press_time_end = time.time() press_duration = press_time_end - press_time_startif press_duration < SHORT_PRESS_TIME:print("A short press is detected")elif press_duration >= LONG_PRESS_TIME:print("A long press is detected")# Save the last state prev_button_state = button_stateexceptKeyboardInterrupt:print("\nExiting the program.")GPIO.cleanup()
파일을 저장하고 터미널에서 다음 명령어를 실행하여 Python 스크립트를 실행하세요:
python3 long_short_press.py
버튼을 짧게 또는 길게 눌러보세요.
터미널에서 결과를 확인하세요.
동영상
비디오 제작은 시간이 많이 걸리는 작업입니다. 비디오 튜토리얼이 학습에 도움이 되었다면, YouTube 채널 을 구독하여 알려 주시기 바랍니다. 비디오에 대한 높은 수요가 있다면, 비디오를 만들기 위해 노력하겠습니다.
왜 길게 누르기와 짧게 누르기가 필요한가
버튼 수를 최소화하기 위해 하나의 버튼으로 여러 기능을 수행할 수 있습니다. 예를 들어, 짧게 누르면 작동 모드를 전환할 수 있고, 길게 누르면 기기를 종료할 수 있습니다.
길게 누르는 기능은 실수로 짧게 누르는 것을 방지하는 데 도움이 됩니다. 예를 들어, 일부 기기는 버튼을 사용하여 초기화를 시작합니다. 버튼이 실수로 눌리면 위험할 수 있습니다. 이를 방지하기 위해 버튼을 일정 시간(예: 5초 동안) 눌러야만 기기가 초기화를 시작하도록 설계되었습니다.