树莓派实现按钮关机、重启、多功能等(按钮长按篇)




准备

  • 按钮
  • 面包板
  • 杜邦线

接线

代码(python3)

  1. # -*- coding: utf-8 -*-
  2. import time,os
  3. import RPi.GPIO as GPIO
  4. BUTTON=17
  5. press_time=0#(上次)按下时间
  6. GPIO.setmode(GPIO.BCM)
  7. GPIO.setup(BUTTON,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
  8. # 长按
  9. def long_click():
  10. global press_time
  11. v=GPIO.input(BUTTON)
  12. # 按下
  13. if press_time==0 and v==1:
  14. press_time=time.time()
  15. # 抬起
  16. if press_time!=0 and v==0:
  17. count_time=time.time()-press_time
  18. press_time=0
  19. return count_time
  20. return None
  21. while True:
  22. count_time=long_click()
  23. if count_time!=None:
  24. print('按下总时长',round(count_time,2))
  25. time.sleep(0.01)