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

Writing the Python program

We will make use of the Nano text editor to write our Python files. First, we will create a directory to save all of our programs into. Type the following two commands:

mkdir ~/WearableTech
cd ~/WearableTech

We should now be inside our new WearableTech directory. Type the following command to open Nano, and create a new file called ledflash.py:

nano ledflash.py

We are now in the Nano text editor. Type in the following code to create a simple program, which will make the LEDs flash on and off when you press the button, and then stop the LEDs flashing when you press the button again:

#!/usr/bin/python3
from gpiozero import LED, Button

btn = Button(25)
green = LED(23)
red = LED(14)

while True:
btn.wait_for_press()
green.blink(0.5,0.5)
red.blink(0.25,0.25)
btn.wait_for_press()
green.off()
red.off()

Save the file by pressing Ctrl and O together, followed by the Enter key, and then exit Nano by pressing Ctrl and X together. We are now going to make the file executable by typing the following command:

sudo chmod +x ./ledflash.py

We can now run the file by typing this:

./ledflash.py

All being well, you should now be able to press the button wired up to your Pi and LEDs should start blinking at different rates. Press the button again (you may need to hold it for half a second) and your LEDs should switch off! If it doesn't work, check your program and double check your wiring.

If you want to stop your program from running, press Ctrl and C together.

主站蜘蛛池模板: 准格尔旗| 宁化县| 泊头市| 志丹县| 疏附县| 格尔木市| 科技| 礼泉县| 诸城市| 慈溪市| 岚皋县| 凤阳县| 张家港市| 策勒县| 汉川市| 芜湖县| 自治县| 抚州市| 东乌珠穆沁旗| 丹东市| 长泰县| 卫辉市| 福贡县| 威信县| 元氏县| 乌拉特中旗| 陕西省| 巢湖市| 金门县| 巴彦淖尔市| 龙胜| 汤阴县| 休宁县| 澎湖县| 东至县| 台南县| 丰顺县| 浦城县| 宝丰县| 新营市| 双峰县|