- Python Programming with Raspberry Pi
- Sai Yamanoor Srihari Yamanoor
- 276字
- 2021-07-02 23:48:46
Code
We will make use of the python3-gpiozero library (https://gpiozero.readthedocs.io/en/v1.3.1/). The Raspbian Jessie OS image comes with the pre-installed library. It is very simple to use, and it is the best option to get started as a beginner. It supports a standard set of devices that helps us get started easily.
For example, in order to interface an LED, we need to import the LED class from the gpiozero library:
from gpiozero import LED
We will be turning the LED on and off at a 1-second interval. In order to do so, we will be importing the time library. In Python, we need to import a library to make use of it. Since we interfaced the LED to the GPIO pin 2, let's make a mention of that in our code:
import time
led = LED(2)
We just created a variable named led and defined that we will be making use of GPIO pin 2 in the LED class. Let's make use of a while loop to turn the LED on and off with a 1-second interval.
The gpiozero library's LED class comes with functions named on() and off() to set the GPIO pin 2 to high and low, respectively:
while True:
led.on()
time.sleep(1)
led.off()
time.sleep(1)
In Python's time library, there is a sleep function that enables introducing a 1-second delay between turning on/off the LED. This is executed in an infinite loop! We just built a practical example using the Raspberry Pi Zero.
Putting all the code together in a file named blinky.py (available for download along with this book), run the code from the command-line terminal (alternatively, you may use IDLE3):
python3 blinky.py
- Hands-On Intelligent Agents with OpenAI Gym
- Div+CSS 3.0網頁布局案例精粹
- Hands-On Cloud Solutions with Azure
- 樂高創意機器人教程(中級 下冊 10~16歲) (青少年iCAN+創新創意實踐指導叢書)
- 80x86/Pentium微型計算機原理及應用
- Maya極速引擎:材質篇
- C語言開發技術詳解
- Docker High Performance(Second Edition)
- Linux:Powerful Server Administration
- Nginx高性能Web服務器詳解
- 深度學習與目標檢測
- MATLAB-Simulink系統仿真超級學習手冊
- Mastering Predictive Analytics with scikit:learn and TensorFlow
- Natural Language Processing and Computational Linguistics
- 無人駕駛感知智能