官术网_书友最值得收藏!

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

主站蜘蛛池模板: 闽侯县| 墨竹工卡县| 西贡区| 石林| 左贡县| 新田县| 当阳市| 遵义县| 塘沽区| 辽中县| 宜昌市| 全南县| 潞城市| 铜鼓县| 雅安市| 平乡县| 鹤岗市| 旌德县| 云龙县| 剑河县| 普格县| 会东县| 荆州市| 社旗县| 信宜市| 沅陵县| 杨浦区| 乌拉特前旗| 隆昌县| 吉安市| 拜泉县| 阿瓦提县| 八宿县| 山东| 宜州市| 随州市| 绥芬河市| 三原县| 弥渡县| 苏尼特左旗| 惠州市|