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

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

主站蜘蛛池模板: 砀山县| 利辛县| 澜沧| 象山县| 绿春县| 华安县| 宣武区| 孝感市| 和林格尔县| 东阿县| 西畴县| 昌图县| 康定县| 巴楚县| 磐安县| 会理县| 黄梅县| 洞头县| 龙江县| 郁南县| 贡觉县| 贵定县| 卢氏县| 宿迁市| 萝北县| 林芝县| 剑阁县| 竹山县| 安远县| 黑山县| 新和县| 霍林郭勒市| 东光县| 陇川县| 垦利县| 和平区| 桂东县| 嘉定区| 华阴市| 即墨市| 察隅县|