- Python Programming with Raspberry Pi
- Sai Yamanoor Srihari Yamanoor
- 150字
- 2021-07-02 23:48:47
Breaking out a loop by counting button presses
Let's review another example where we would like to count the number of button presses and break out of the infinite loop when the button has received a predetermined number of presses:
i = 0
while True:
if button.is_pressed:
button.wait_for_release()
i += 1
print("Button pressed")
if i >= 10:
break
The preceding example is available for downloading along with this chapter as GPIO_button_loop_break.py.
In this example, the program checks for the state of the is_pressed variable. On receiving a button press, the program can be paused until the button is released using the wait_for_release method. When the button is released, the variable used to store the number of presses is incremented by one.
The program breaks out of the infinite loop, when the button has received 10 presses.

A red momentary push button interfaced to Raspberry Pi Zero GPIO pin 2
推薦閱讀
- PostgreSQL 11 Server Side Programming Quick Start Guide
- Getting Started with Clickteam Fusion
- 來吧!帶你玩轉Excel VBA
- 影視后期制作(Avid Media Composer 5.0)
- 自動控制理論(非自動化專業)
- 統計學習理論與方法:R語言版
- 液壓機智能故障診斷方法集成技術
- 所羅門的密碼
- INSTANT VMware vCloud Starter
- 機床電氣控制與PLC
- Hands-On DevOps
- 大數據時代的調查師
- ROS Robotics By Example(Second Edition)
- 百度智能小程序:AI賦能新機遇
- 機器人手工制作