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

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

主站蜘蛛池模板: 梧州市| 玛沁县| 慈利县| 巴林右旗| 莱阳市| 奉贤区| 天等县| 龙川县| 苍南县| 股票| 南宫市| 嘉荫县| 西乌珠穆沁旗| 田阳县| 九江县| 灵寿县| 吴忠市| 太康县| 惠安县| 军事| 章丘市| 香河县| 灵石县| 鱼台县| 扶风县| 安远县| 棋牌| 望城县| 石屏县| 内丘县| 延寿县| 崇州市| 乌鲁木齐市| 霍州市| 湛江市| 务川| 永善县| 安西县| 星子县| 中方县| 兴义市|