Оглавление
- C (WiringPi) Setup
- Через что возможно взаимодействовать с GPIO Raspberry
- Switch
- Установка необходимых пакетов для работы с Bluetooth в Raspberry Pi
- Управление GPIO «Малины» через Python
- Introduction to Raspberry Pi 4
- 4.3. Environment variables¶
- Что следует учитывать при работе с GPIO
- Usage
- Обзор плат Raspberry Pi
- Breadboard Basics
- Accessing the GPIO Pins from a Bash Script
- Python (RPi.GPIO) Example
- The gpio Utility
- 4.4. Pin factories¶
- Скорость работы и джиттер
- Libgpiod
- Binary Sensor
C (WiringPi) Setup
Python is a great GPIO-driving option, especially if you’re used to it. But if you’re a rickety old programmer, unfamiliar with the whitespace-driven scripting language, and would rather live within the happy confines of C, then let me introduce the WiringPi library.
1) Install Wiring Pi
Note: Wiring Pi is now pre-installed with standard Raspbian systems. The instructions from the official WiringPi homepage are now depreciated. The original wiringPi source «» is not available.
Wiring Pi is previously not included with early versions of Raspbian. This required users to download and install it. Luckily, Wiring Pi is included in standard Raspbian systems. If you are looking to update using a mirrored Wiring Pi with small updates to support newer hardware, we recommend checking out this GitHub repository.
You’ll need git (may be installed by default). If git is not installed, enter the following into the command line.
We highly recommend using Git to download the latest version. To check what version you have, enter the following command.
If you receive an output similar to to the following with the , you’ll want to update WiringPi on a Raspberry Pi 4 or above.
Enter the following to remove the wiringPi and configuration files.
Then type the following for the Pi to remove all locations that remember wiringPi.
As long as you have Git installed, these commands should be all you need to download and install Wiring Pi.
This will make a folder in your current directory called WiringPi. Head to the Wiring Pi directory.
Then pull the latest changes from the origin.
Then enter the following command. The is a script to build Wiring Pi from the source files. This builds the helper files, modifies some paths in Linux and gets WiringPi ready to rock.
At this point, the library should work. Run the command shown below to view some information about the wiringPi version and the Pi that it is running on.
Entering the following command will draw a table illustrating the configuration for the pins in the 40-pin connector.
Troubleshooting Tip: If you receive an output similar to the one below when using the command to read or configure the pins, this is because of a conflict between wiringPi and the mirrored WiringPi. Make sure to use the command to the previous wiringPi that was installed on your Raspberry Pi.
2) Test Wiring Pi
WiringPi is awesome because it’s actually more than just a C library, it includes a command-line utility as well! You can test your installation of WiringPi with the utility. The following will toggle a pin to turn on/off an LED and then read a button press.
Toggling an LED
Open up a terminal, and try some of these system calls. To configure pin 18, enter the following. By default, the pin is set as an input.
To turn the pin HIGH, enter the following.
To turn it back low, enter the following.
As long as your LED is still connected to pin 18, it should blink on and off following the last two commands.
Reading a Button Press
To test the button, you will first need to configure pin 17 with the Pi’s internal pull-up resistor.
To read the pin, enter for the following.
Either 0 or 1 will be returned, depending on whether the button is pressed or not. Try typing that last line again while pressing the button.
The utility, as stated in the manual, is a «swiss army knife» command-line tool. We highly recommend checking out the man page (type ) to discover everything it can do.
Через что возможно взаимодействовать с GPIO Raspberry
Работать с GPIO Raspberry Pi можно практически через любой инструмент. К сегодняшнему дню созданы соответствующие библиотеки почти под все распространенные языки программирования. С GPIO Raspberry Pi возможно взаимодействовать даже через PHP и JavaScript (node.js).
Однако человеку, который только начинает знакомиться с «Малиной», рекомендуется пробовать взаимодействовать с данным интерфейсом посредством Python. Это обусловлено, во-первых, что для GPIO в Raspbian уже предустановлена соответствующая библиотека для Пайтона, а, во-вторых, этот ЯП является основным для рассматриваемого одноплатника.
Однако при желании, конечно, возможно пользоваться и любыми другими инструментами. Найти название библиотек и описание их не составляет никакого труда.
Switch
The switch platform allows you to control the GPIOs of your Raspberry Pi.
Looking for your configuration file?
ports list Required
Array of used ports.
port integer | string Required
Port numbers and corresponding names (GPIO
invert_logic boolean (Optional, default: false)
If true, inverts the output logic to ACTIVE LOW.
For more details about the GPIO layout, visit the Wikipedia about the Raspberry Pi.
Note that a pin managed by Home Assistant is expected to be exclusive to Home Assistant.
A common question is what does Port refer to, this number is the actual GPIO #, not the pin #.
For example, if you have a relay connected to pin 11 its GPIO # is 17.
Suggest an edit to this page, or provide/view feedback for this page.
Установка необходимых пакетов для работы с Bluetooth в Raspberry Pi
Первым делом нам необходимо установить последние обновления для операционной системы Raspberry Pi OS:
Shell
sudo apt-get update
sudo apt-get upgrade
1 |
sudo apt-getupdate sudo apt-getupgrade |
Затем нам необходимо установить последние обновления для работы с Bluetooth:
Shell
sudo apt-get install bluetooth blueman bluez
1 | sudo apt-getinstall bluetooth blueman bluez |
После этого необходимо перезагрузить плату Raspberry Pi:
Shell
sudo reboot
1 | sudo reboot |
BlueZ – это проект с открытым исходным кодом и официальный стек протоколов Bluetooth для операционной системы Linux. Он поддерживает все ядро протоколов Bluetooth и в настоящее время является официальной частью Linux Kernel (ядра Linux).
Blueman обеспечивает интерфейс рабочего стола для управления Bluetooth устройствами.
Также нам потребуется библиотека Python для работы с протоколом Bluetooth чтобы мы могли в программе передавать и принимать данные через RFCOMM:
Shell
sudo apt-get install python-bluetooth
1 | sudo apt-getinstall python-bluetooth |
Также необходимо установить библиотеку обеспечения работы с контактами ввода/вывода (GPIO) в Raspberry Pi:
Shell
sudo apt-get install python-rpi.gpio
1 | sudo apt-getinstall python-rpi.gpio |
На этом установка всех необходимых пакетов для работы с Bluetooth в Raspberry Pi будет закончена.
Управление GPIO «Малины» через Python
И теперь самое интересное: как выполняется управление GPIO Raspberry Pi через Пайтон.
Абсолютно отсутствует необходимость рассказывать о самом языке Python и подробно описывать библиотеку. Эту информацию легко найти на официальных сайтах соответствующих проектов – лучше изложить материал, чем там, крайне тяжело.
Однако есть смысл просто продемонстрировать некоторые принципы взаимодействия с GPIO. Конечно, перед написанием кода следует подключить устройство, с которым нужно работать к GPIO.
Первое, что потребуется сделать – это подключить библиотеку, делается это так: import PRi.GPIO as GPIO.
Далее нужно дать интерпретатору понять, что обращение к портам будет выполняться по их названиям. Это выполняется инструкцией: GPIO.setmode(GPIO.BCM). Предварительно также рекомендуется сбросить текущее состояние интерфейса (мало ли каково оно, хотя это и не критично) – GPIO.cleanup().
Далее можно сконфигурировать порты на выход и вход. Первое делается так: GPIO.setup(НОМЕР_ПОРТА, GPIO.OUT), а второе – GPIO.setup(НОМЕР_ПОРТА, GPIO.IN).
То есть, как можно убедиться, абсолютно ничего сложного в работе с GPIO нет. Главное – знать название портов (возможно почерпнуть из схемы) и функции, предусмотренные библиотекой.
Introduction to Raspberry Pi 4
The Raspberry Pi 4 Model B is the latest board launched by the Raspberry Pi Foundation in June 2019. This model has the latest high-performance quad-Core 64-bit Broadcom 2711, Cortex A72 processor clocked at 1.5GHz speed.
This processor uses 20% less power and offers 90% greater performance than the previous model. Raspberry Pi 4 GPIO Pinout with functions, schematic, and specs are given in detail below.
Raspberry Pi 4 model comes in three different variants of 2 GB, 4 GB, and 8 GB LPDDR4 SDRAM.
The other new features of the board are dual-display support up to 4k resolutions via a pair of micro-HDMI ports, hardware video decodes at up to 4Kp60, dual-channel 2.4/5.0GHz wireless LAN, true Gigabit Ethernet, two USB 3.0 port, Bluetooth 5.0, and PoE capability (via a separate PoE HAT board).
4.3. Environment variables¶
The simplest way to use devices with remote pins is to set the
environment variable to the IP address of the desired
Raspberry Pi. You must run your Python script or launch your development
environment with the environment variable set using the command line. For
example, one of the following:
$ PIGPIO_ADDR=192.168.1.3 python3 hello.py $ PIGPIO_ADDR=192.168.1.3 python3 $ PIGPIO_ADDR=192.168.1.3 ipython3 $ PIGPIO_ADDR=192.168.1.3 idle3 &
If you are running this from a PC (not a Raspberry Pi) with gpiozero and the
pigpio Python library installed, this will work with no further
configuration. However, if you are running this from a Raspberry Pi, you will
also need to ensure the default pin factory is set to
. If RPi.GPIO is installed,
this will be selected as the default pin factory, so either uninstall it, or
use the environment variable to override it:
$ GPIOZERO_PIN_FACTORY=pigpio PIGPIO_ADDR=192.168.1.3 python3 hello.py
This usage will set the pin factory to
with a default host of
. The pin factory can be changed inline in the code, as seen in
the following sections.
With this usage, you can write gpiozero code like you would on a Raspberry Pi,
with no modifications needed. For example:
from gpiozero import LED from time import sleep red = LED(17) while True red.on() sleep(1) red.off() sleep(1)
When run with:
$ PIGPIO_ADDR=192.168.1.3 python3 led.py
will flash the LED connected to pin 17 of the Raspberry Pi with the IP address
. And:
$ PIGPIO_ADDR=192.168.1.4 python3 led.py
will flash the LED connected to pin 17 of the Raspberry Pi with the IP address
, without any code changes, as long as the Raspberry Pi has the
pigpio daemon running.
Что следует учитывать при работе с GPIO
Можно подключать любые устройства в Raspberry 2, 3 т.д. пины. Однако на GPIO есть специальные порты, которые применять не по назначению возможно, но не рекомендуется. К ним относятся BCM 0 и BCM 1, которые в схеме имеют номера 27 и 28 соответственно. Эти порты предназначены специально для поверхностного монтажа – HAT-устройств, которые, по сути, являются платами расширения.
Также тем, кто планирует работать с GPIO «Малины» рекомендуется следить за силой тока. Максимально через все пины может подаваться электричество в 50мА. При неправильном использовании такая сила может повредить не только внешнее устройство, но и вывести из строя процессор Raspberry.
Usage
Below is example usage on a Raspberry PI Model B+ V1.2.
To detect/list GPIO character devices:
# gpiodetect gpiochip0 (54 lines)
To list the I/O lines available on this device:
# gpioinfo pinctrl-bcm2835 gpiochip0 - 54 lines: line 0: "SDA0" unused input active-high line 1: "SCL0" unused input active-high line 2: "SDA1" unused input active-high line 3: "SCL1" unused input active-high line 4: "GPIO_GCLK" unused input active-high line 5: "CAM_GPIO1" unused input active-high line 6: "LAN_RUN" unused input active-high line 7: "SPI_CE1_N" unused input active-high line 8: "SPI_CE0_N" unused input active-high line 9: "SPI_MISO" unused input active-high line 10: "SPI_MOSI" unused input active-high line 11: "SPI_SCLK" unused input active-high line 12: "NC" unused input active-high line 13: "NC" unused input active-high line 14: "TXD0" unused input active-high line 15: "RXD0" unused input active-high line 16: "STATUS_LED_N" "ACT" output active-low line 17: "GPIO17" unused input active-high line 18: "GPIO18" unused input active-high line 19: "NC" unused input active-high line 20: "NC" unused input active-high line 21: "GPIO21" unused input active-high line 22: "GPIO22" unused input active-high line 23: "GPIO23" unused input active-high line 24: "GPIO24" unused input active-high line 25: "GPIO25" unused output active-high line 26: "NC" unused input active-high line 27: "CAM_GPIO0" unused input active-high line 28: "CONFIG0" unused input active-high line 29: "CONFIG1" unused input active-high line 30: "CONFIG2" unused input active-high line 31: "CONFIG3" unused input active-high line 32: "NC" unused input active-high line 33: "NC" unused input active-high line 34: "NC" unused input active-high line 35: "NC" unused input active-high line 36: "NC" unused input active-high line 37: "NC" unused input active-high line 38: "NC" unused input active-high line 39: "NC" unused input active-high line 40: "PWM0_OUT" unused input active-high line 41: "NC" unused input active-high line 42: "NC" unused input active-high line 43: "NC" unused input active-high line 44: "NC" unused input active-high line 45: "PWM1_OUT" unused input active-high line 46: "HDMI_HPD_P" unused input active-high line 47: "SD_CARD_DET" unused input active-high line 48: "SD_CLK_R" unused input active-high line 49: "SD_CMD_R" unused input active-high line 50: "SD_DATA0_R" unused input active-high line 51: "SD_DATA1_R" unused input active-high line 52: "SD_DATA2_R" unused input active-high line 53: "SD_DATA3_R" unused input active-high
Display help for the gpioset command:
# gpioset --help Usage: gpioset = = ... Set GPIO line values of a GPIO chip Options: -h, --help: display this message and exit -v, --version: display the version and exit -l, --active-low: set the line active state to low -m, --mode= (defaults to 'exit'): tell the program what to do after setting values -s, --sec=SEC: specify the number of seconds to wait (only valid for --mode=time) -u, --usec=USEC: specify the number of microseconds to wait (only valid for --mode=time) -b, --background: after setting values: detach from the controlling terminal Modes: exit: set values and exit immediately wait: set values and wait for user to press ENTER time: set values and sleep for a specified amount of time signal: set values and wait for SIGINT or SIGTERM
To toggle GPIO25 high for 1 second:
# gpioset --mode=time --sec=1 pinctrl-bcm2835 25=1
Обзор плат Raspberry Pi
Raspberry Pi – это миниатюрный одноплатный компьютер, который с лёгкостью поместится на ладони взрослого человека. Несмотря на свои скромные размеры, плата имеет высокую производительность, что позволяет ей выйти на один уровень со стационарными ПК. Изначально Raspberry Pi была разработана, как учебное пособие по информатике. Но сама идея оказалась настолько удачной, что за несколько лет мини-компьютер стал популярен в очень широких кругах. С течением времени Raspberry Pi пережила несколько модификаций, каждая из которых отличалась от предшественника каким-либо параметром. Такой подход позволил регулировать стоимость изделия в зависимости от потребностей пользователя, что также положительно сказалось на популярности устройства. Вся линейка Raspberry Pi применяет процессоры с АРМ-архитектурой, которая зарекомендовала себя с лучшей стороны. На рисунке №1 показан внешний вид одной из популярных плат Raspberry Pi В+.
Рисунок №1 – обзор составных элементов Raspberry Pi
На сегодняшний день (период 2012-2019гг.) существует 11 разновидностей Raspberry Pi. Последние версии оснащены беспроводными WiFi и Bluetooth модулями, расширяющими границы применения мини-пк в области Ethernet-технологий. Ниже приведена сравнительная таблица, в которой отражены особенности каждой модификации с указанием некоторых технических данных.
Модификация |
Процессор |
Тактовая частота |
Количество ядер |
Объём ОЗУ |
Количество GPIO |
Количество USB |
Поддержка Ethernet |
Поддержка WiFi |
Поддержка Bluetooth |
Год выпуска |
В |
ARM1176JZ-F |
700 МГц |
1 |
512 МБ |
26 |
2 |
√ |
2012 |
||
А |
ARM1176JZ-F |
700 МГц |
1 |
256 МБ |
26 |
1 |
2013 |
|||
В+ |
ARM1176JZ-F |
700 МГц |
1 |
512 МБ |
40 |
4 |
√ |
2014 |
||
А+ |
ARM1176JZ-F |
700 МГц |
1 |
256 МБ |
40 |
1 |
2014 |
|||
2В |
ARM Cortex-A7 |
900 МГц |
4 |
1 ГБ |
40 |
4 |
√ |
2015 |
||
Zero |
ARM1176JZ-F |
1 ГГц |
1 |
512 МБ |
40 |
1 |
2015 |
|||
3B |
Cortex-A53 (ARM v8) |
1,2 ГГц |
4 |
1 ГБ |
40 |
4 |
√ |
802.11n |
4.1 |
2016 |
Zero W |
ARM1176JZ-F |
1 ГГц |
1 |
512 МБ |
40 |
1 |
802.11n |
4.0 |
2017 |
|
3B+ |
Cortex-A53 (ARM v8) |
1,4 ГГц |
4 |
1 ГБ |
40 |
4 |
√ |
802.11n |
4.2 |
2018 |
3A+ |
Cortex-A53 (ARM v8) |
1,4 ГГц |
4 |
512 МБ |
40 |
1 |
802.11n |
4.2 |
2018 |
|
4B |
Cortex-A72 (ARM v8) |
1,5 ГГц |
4 |
1, 2, 4 ГБ |
40 |
4 |
√ |
802.11n |
5.0 |
2019 |
Как видно из вышеприведенной таблицы, даже самая младшая модель в линейке имеет вполне серьёзные характеристики, учитывая то, что это одноплатный компьютер размером чуть больше кредитной карты.
На рисунке №2 изображена последняя на момент написания статьи модификация Raspberry Pi 4В, запущенная в продажу в июне 2019г. Она оснащена дополнительным графическим процессором VideoCore VI (OpenGL ES 3.x), а также аппаратным декодером 4Kp60 для воспроизведения HEVC видео. Два порта microHDMI с возможностью пропускать сигнал до 4К, позволяют подключить одновременно два монитора.
Рисунок №2 – внешний вид Raspberry Pi 4В
Основной отличительной чертой Raspberry Pi от обычных компьютеров, является наличие программируемых портов ввода-вывода GPIO. С помощью них можно управлять различными устройствами и принимать телеметрию с различного рода датчиков.
Breadboard Basics
Let’s start with the breadboard.If it’s your first time with it, you may have a hard time understanding how it works.
Breadboard Installation
If you are using the breadboard kit I recommended above, the first step is to install it in the blue plastic case.Generally, you have to stick it in the large space and screw the Raspberry Pi to the corresponding location.
At this point your setup must look like this:
Don’t plug in the Raspberry Pi power cable for the moment.
Power Input
On the edges of the board, there are two lines:
- The red line is for the power input
- The blue line is for the ground
Each port is connected with all the pins from the same line.
Attention, with some breadboards (like mine), there is a separation in the middle, you can see a gap in the red line for example.If you plug near port 0, it will not work near port 50.
Other Ports
The other ports are used for everything else (LEDs, resistors, other modules).A wire connects them in columns.If you take one number on the board, it connects each port from the same column with the others.
Schema
It will be clearer with this picture:
I have squared each connected ports.
The red square corresponds to a power input line.There are four lines of this type on the board.If you input power in one of the squared ports, you can use it from any other highlighted ports.
For the ground ports it’s the same thing (blue square).
And for the other ports, you can see the green square how they are connected together.It’s the same for each column, for both side of the middle line.
If needed, here is a complete schema:
You may also like:
- 25 awesome Raspberry Pi project ideas at home
- 15 best operating systems for Raspberry Pi (with pictures)
- My book: Master your Raspberry Pi in 30 days
Accessing the GPIO Pins from a Bash Script
Without adding further dependencies, Bash scripts can access and control the Pi’s GPIO pins using sysfs. This presents as a set of filesystem paths which can be manipulated to configure individual pins as inputs or outputs and to set and read their values. On the Pi, these paths look like:
and each has a and , for example for GPIO 11:
As we will see later in this article, the direction and value can be set by writing values to these “paths” as the user on the Pi.
The pin numbering scheme used by sysfs is the Broadcom (BCM) one, so the pin numbers that you need to use will match those in the diagram earlier in this article.
Python (RPi.GPIO) Example
Follow along as we use the basic RPi.GPIO functions from the last page to create a simple example GPIO script.
1. Create a File
To begin, we need to create a Python file. You can do this through the GUI-based file explorer. Or, if you want a terminal-based solution, open up LXTerminal, and navigate to a folder you’d like the file to live (or create one). And create a new folder with these commands:
Then move to the folder with the following command.
Create a file — we’ll call ours «blinker» — and terminate it with a .py extension.
Then open it up in your favorite text editor. Nano works, as does Pi’s default GUI text editor, Mousepad.
Note: Previously, Leafpad was the default GUI text editor for Raspberry Pi Images. It is now replaced by Mousepad. You can find Mousepad under the Raspberry Pi Start Menu under Accessories > Text Editor. You can still install leafpad manually with the command. Once installed, you can specify the text editor to open up the file.
That’ll open up a blank text file (the «&» will open it in the background, leaving the terminal in place for future use). Time for some code!
2. Codify
Here’s an example sketch that incorporates everything we learned on the last page. It does a little input and output, and even handles some PWM. This assumes you’ve set up the circuit as arranged on the Hardware Setup page.
After you’ve typed all of that in (don’t forget your whitespace!) save.
Running the Script
The RPi.GPIO module requires administrator privileges, so you’ll need to tag a on to the front of your Python script call. To run your «blinker.py» script, type:
With the code running, press the button to turn on the digital LED. The PWM-ing LED will invert its brightness when you press the button as well.
The gpio Utility
On the Raspberry Pi platform there is a handy command line utility called «gpio» which can control the pins more conveniently than using the sysfs interface. It can export pins, set direction, set and read levels, as well as more advanced functions like PWM. It should be installed by default under Raspbian Linux. If not, just run «sudo apt install wiringpi» to install it.
Here is the command usage:
$ gpio -h
gpio: Usage: gpio -v
gpio -h
gpio …
gpio …
` -x `.«.«.« …
gpio <read/write/wb> …
gpio <mode/read/write/aread/awritewb/pwm/pwmTone/clock> …
gpio <toggle/blink> <pin>
gpio readall
gpio unexportall/exports
gpio export/edge/unexport …
gpio wfi <pin> <mode>
gpio drive <group> <value>
gpio pwm-bal/pwm-ms
gpio pwmr <range>
gpio pwmc <divider>
gpio load spi/i2c
gpio unload spi/i2c
gpio i2cd/i2cdetect
gpio rbx/rbd
gpio wb <value>
gpio usbp high/low
gpio gbr <channel>
gpio gbw <channel> <value>
Running «man gpio» will show the documentation for the command. One useful option will read and display all the GPIO pins, with a representation of the pin numbers and names:
$ gpio readall
+——+——+———+——+—+—Pi 3B—+—+——+———+——+——+
| BCM | wPi | Name | Mode | V | Physical | V | Mode | Name | wPi | BCM |
+——+——+———+——+—+—-++—-+—+——+———+——+——+
| | | 3.3v | | | 1 || 2 | | | 5v | | |
| 2 | 8 | SDA.1 | IN | 1 | 3 || 4 | | | 5v | | |
| 3 | 9 | SCL.1 | IN | 1 | 5 || 6 | | | 0v | | |
| 4 | 7 | GPIO. 7 | IN | 1 | 7 || 8 | 1 | ALT5 | TxD | 15 | 14 |
| | | 0v | | | 9 || 10 | 1 | ALT5 | RxD | 16 | 15 |
| 17 | | GPIO. | IN | | 11 || 12 | | IN | GPIO. 1 | 1 | 18 |
| 27 | 2 | GPIO. 2 | IN | | 13 || 14 | | | 0v | | |
| 22 | 3 | GPIO. 3 | IN | | 15 || 16 | | IN | GPIO. 4 | 4 | 23 |
| | | 3.3v | | | 17 || 18 | | IN | GPIO. 5 | 5 | 24 |
| 10 | 12 | MOSI | IN | | 19 || 20 | | | 0v | | |
| 9 | 13 | MISO | IN | | 21 || 22 | | IN | GPIO. 6 | 6 | 25 |
| 11 | 14 | SCLK | IN | | 23 || 24 | 1 | IN | CE0 | 10 | 8 |
| | | 0v | | | 25 || 26 | 1 | IN | CE1 | 11 | 7 |
| | 30 | SDA.0 | IN | 1 | 27 || 28 | 1 | IN | SCL.0 | 31 | 1 |
| 5 | 21 | GPIO.21 | IN | 1 | 29 || 30 | | | 0v | | |
| 6 | 22 | GPIO.22 | IN | 1 | 31 || 32 | | IN | GPIO.26 | 26 | 12 |
| 13 | 23 | GPIO.23 | IN | | 33 || 34 | | | 0v | | |
| 19 | 24 | GPIO.24 | IN | | 35 || 36 | | IN | GPIO.27 | 27 | 16 |
| 26 | 25 | GPIO.25 | IN | 1 | 37 || 38 | | IN | GPIO.28 | 28 | 20 |
| | | 0v | | | 39 || 40 | | IN | GPIO.29 | 29 | 21 |
+——+——+———+——+—+—-++—-+—+——+———+——+——+
| BCM | wPi | Name | Mode | V | Physical | V | Mode | Name | wPi | BCM |
+——+——+———+——+—+—Pi 3B—+—+——+———+——+——+
From our earlier example, we could set gpio24 high and low with these commands:
$ gpio export 24 out
$ gpio -g write 24 1
$ gpio -g write 24 0
Or even toggle (change) the value or make it blink briefly like this:
$ gpio -g toggle 24
$ gpio -g blink 24
And finally, unexport it:
$ gpio unexport 24
Note the use of the -g option — this tells the command to use the BCM pin numbers rather than the default, which is to use numbers used by the WiringPi library (which we’ll look at in a future blog post). A quirk of the command is that when using the export and unexport commands, it always uses the BCM pin numbers, so the -g option is not needed in this case.
4.4. Pin factories¶
An alternative (or additional) method of configuring gpiozero objects to use
remote pins is to create instances of
objects, and use them when
instantiating device objects. For example, with no environment variables set:
from gpiozero import LED from gpiozero.pins.pigpio import PiGPIOFactory from time import sleep factory = PiGPIOFactory(host='192.168.1.3') led = LED(17, pin_factory=factory) while True led.on() sleep(1) led.off() sleep(1)
This allows devices on multiple Raspberry Pis to be used in the same script:
from gpiozero import LED from gpiozero.pins.pigpio import PiGPIOFactory from time import sleep factory3 = PiGPIOFactory(host='192.168.1.3') factory4 = PiGPIOFactory(host='192.168.1.4') led_1 = LED(17, pin_factory=factory3) led_2 = LED(17, pin_factory=factory4) while True led_1.on() led_2.off() sleep(1) led_1.off() led_2.on() sleep(1)
You can, of course, continue to create gpiozero device objects as normal, and
create others using remote pins. For example, if run on a Raspberry Pi, the
following script will flash an LED on the controller Pi, and also on another Pi
on the network:
from gpiozero import LED from gpiozero.pins.pigpio import PiGPIOFactory from time import sleep remote_factory = PiGPIOFactory(host='192.168.1.3') led_1 = LED(17) # local pin led_2 = LED(17, pin_factory=remote_factory) # remote pin while True led_1.on() led_2.off() sleep(1) led_1.off() led_2.on() sleep(1)
Alternatively, when run with the environment variables
set, the following
script will behave exactly the same as the previous one:
from gpiozero import LED from gpiozero.pins.rpigpio import RPiGPIOFactory from time import sleep local_factory = RPiGPIOFactory() led_1 = LED(17, pin_factory=local_factory) # local pin led_2 = LED(17) # remote pin while True led_1.on() led_2.off() sleep(1) led_1.off() led_2.on() sleep(1)
Of course, multiple IP addresses can be used:
from gpiozero import LED from gpiozero.pins.pigpio import PiGPIOFactory from time import sleep factory3 = PiGPIOFactory(host='192.168.1.3') factory4 = PiGPIOFactory(host='192.168.1.4') led_1 = LED(17) # local pin led_2 = LED(17, pin_factory=factory3) # remote pin on one pi led_3 = LED(17, pin_factory=factory4) # remote pin on another pi while True led_1.on() led_2.off() led_3.on() sleep(1) led_1.off() led_2.on() led_3.off() sleep(1)
Note that these examples use the class, which takes a pin
argument to initialise. Some classes, particularly those representing HATs and
other add-on boards, do not require their pin numbers to be specified. However,
it is still possible to use remote pins with these devices, either using
environment variables, or the pin_factory keyword argument:
import gpiozero from gpiozero import TrafficHat from gpiozero.pins.pigpio import PiGPIOFactory from time import sleep gpiozero.Device.pin_factory = PiGPIOFactory(host='192.168.1.3') th = TrafficHat() # traffic hat on 192.168.1.3 using remote pins
This also allows you to swap between two IP addresses and create instances of
multiple HATs connected to different Pis:
import gpiozero from gpiozero import TrafficHat from gpiozero.pins.pigpio import PiGPIOFactory from time import sleep remote_factory = PiGPIOFactory(host='192.168.1.3') th_1 = TrafficHat() # traffic hat using local pins th_2 = TrafficHat(pin_factory=remote_factory) # traffic hat on 192.168.1.3 using remote pins
You could even use a HAT which is not supported by GPIO Zero (such as the
Sense HAT) on one Pi, and use remote pins to control another over the
network:
from gpiozero import MotionSensor from gpiozero.pins.pigpio import PiGPIOFactory from sense_hat import SenseHat remote_factory = PiGPIOFactory(host='192.198.1.4') pir = MotionSensor(4, pin_factory=remote_factory) # remote motion sensor sense = SenseHat() # local sense hat while True pir.wait_for_motion() sense.show_message(sense.temperature)
Скорость работы и джиттер
Опрос состояния кнопок и управление светодиодами – события относительно медленные, измеряющиеся десятками и сотнями миллисекунд. Иногда встречаются намного более высокоскоростные сигналы. Например, пульт от телевизора излучает инфракрасные световые импульсы со скоростью 40 тыс. раз в секунду. Несмотря на то, что основной процессор RPi работает на частоте 1 ГГц, работа подсистемы ввода/вывода с такой скоростью не поддерживается по ряду причин, как аппаратных, так и программных. Мы рассмотрим некоторые программные аспекты, касающиеся темы статьи.
RPi работает под управлением многозадачной операционной системы (ОС) Linux. Система может превентивно забирать контроль над вашей программой для выполнения других задач. Все это происходит довольно быстро, так что кажется, будто мышка по-прежнему работает во время выполнения вашей программы, но на самом деле вашей программе и коду драйвера мыши ОС предоставляет лишь короткие промежутки времени.
Обычно это не имеет значения, но когда вам нужна обработка коротких или высокоточных событий, это может стать проблемой, проявляющейся (например) в виде джиттера.
Кроме того, немаловажное значение имеет выбор языка программирования, поскольку некоторые библиотеки подходят лучше, чем другие. Интерпретированные и компилированные коды могут выполняться с разными скоростями
Короче говоря, если требуется очень точная временнáя привязка событий, возможно, придется написать драйвер Linux или использовать внешнее оборудование (например, другой микроконтроллер или логические схемы и генератор).
Одним из хороших вопросов, важных для более полного использования возможностей RPi, является то, насколько быстро можно изменять логические состояния выходов GPIO с помощью библиотек Python, Си и описанного выше командного скрипта.
Чтобы узнать это, был написан код для периодического переключения логического состояния выходного порта, к которому был подключен осциллограф. Результат представлен в Таблице 1.
Таблица 1. | Максимальная частота переключения выходов при использовании различных языков программирования |
|||||||||||||||
|
Однако всегда важно помнить о джиттере, которым обязательно сопровождается работа ОС Linux. Для случая простого переключения светодиода это, кончено же, не проблема
Характер джиттера можно увидеть на осциллографе в режиме наложения нескольких каналов при синхронизации общим сигналом (Рисунок 17)
Обратите внимание, что джиттер может принимать множество значений, несмотря на то, что сигналы дискретно разнесены на 4 нс (250 МГц), что связано с аппаратными особенностями RPi
Рисунок 17. | Следствием использования ОС Linux становится джиттер выходного сигнала. |
Libgpiod
Libgpiod (Library General Purpose Input/Output device) provides both API calls for use in your own programs and the following six user-mode applications to manipulate GPIO lines:
- gpiodetect – list all gpiochips present on the system, their names, labels and number of GPIO lines
- gpioinfo – list all lines of specified gpiochips, their names, consumers, direction, active state and additional flags
- gpioget – read values of specified GPIO lines
- gpioset – set values of specified GPIO lines, potentially keep the lines exported and wait until timeout, user input or signal
- gpiofind – find the gpiochip name and line offset given the line name
- gpiomon – wait for events on GPIO lines, specify which events to watch, how many events to process before exiting or if the events should be reported to the console
To cross-compile Libgpiod for the Raspberry PI on your Ubuntu 18.04 host, first install the following prerequisites:
sudo apt-get install autoconf autoconf-archive libtool libkmod-dev pkg-config
Then download, cross-compile and install.
wget https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/snapshot/libgpiod-1.1.1.tar.gz tar -xzf libgpiod-1.1.1.tar.gz cd libgpiod-1.1.1/ ./autogen.sh --enable-tools=yes --host=arm-linux-gnueabi --prefix=/home/<home dir>/export/rootfs ac_cv_func_malloc_0_nonnull=yes make make install
Setting ac_cv_func_malloc_0_nonnull=yes will prevent an undefined reference to `rpl_malloc’ error at linking.
Binary Sensor
The binary sensor platform allows you to read sensor values of the GPIOs of your Raspberry Pi.
Looking for your configuration file?
ports map Required
List of used ports.
port: name string Required
The port numbers (BCM mode pin numbers) and corresponding names.
bouncetime integer (Optional, default: 50)
The time in milliseconds for port debouncing.
invert_logic boolean (Optional)
If , inverts the output logic to ACTIVE LOW.
Default:
(ACTIVE HIGH)
pull_mode string (Optional, default: )
Type of internal pull resistor to use. Options are — pull-up resistor and — pull-down resistor.
For more details about the GPIO layout, visit the Wikipedia about the Raspberry Pi.