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

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

主站蜘蛛池模板: 昌乐县| 军事| 且末县| 安仁县| 壶关县| 松滋市| 苏尼特右旗| 岗巴县| 上饶市| 兴化市| 保定市| 体育| 利津县| 卢氏县| 乌鲁木齐县| 田阳县| 佛学| 双城市| 泸西县| 澳门| 武宣县| 阿城市| 平乐县| 肥西县| 湄潭县| 宜兴市| 林甸县| 弥渡县| 怀化市| 阿勒泰市| 卢湾区| 新闻| 三亚市| 无棣县| 灵宝市| 平远县| 尼玛县| 资中县| 全南县| 柞水县| 临安市|