Работа с GPIO/en: различия между версиями
Fizikdaos (обсуждение | вклад) (Новая страница: «see also [http://elinux.org/GPIO elinux.org]») |
|||
(не показаны 33 промежуточные версии 2 участников) | |||
Строка 1: | Строка 1: | ||
<languages/> | <languages/> | ||
In Wiren Board | In Wiren Board part GPIO output to terminal blocks, connectors on the expansion modules, the other part is used for business purposes. | ||
GPIO are also used to control the switching transistors for low-voltage load. | GPIO are also used to control the switching transistors for low-voltage load. | ||
The correspondence between GPIO | The correspondence between numbers GPIO Linux and their location and function can be found in the table [[WB SH 3.5: Список GPIO| WB SH 3.5: List of GPIO]] or [[WB rev. 2.8: Список GPIO| WB rev. 2.8: List of GPIO]]. | ||
In Wiren Board rev. 2.8 8 GPIO | In Wiren Board rev. 2.8 8 GPIO on a special connector connected via [[Special: MyLanguage / MCP23S08 | MCP23S08]] and temporarily do not work with standard Linux API. How to work with them there on the page[[Special:MyLanguage/MCP23S08|MCP23S08]]. | ||
<b> All | <b> All GPIO (as well as other ports Wiren Board) working with voltage 3.3V. In no case do not connect directly to the GPIO signals with voltage over 3.3V! In case you want to connect devices operating at a higher voltage, you must use matching circuits or connected (for 5V) through a resistor of 20 kOhm or more</b> | ||
On some | On some GPIO (particularly at the 3 GPIO, launched into terminals in Wiren Board rev. 2.8) can be programmatically set to lift 47K + 3.3V. See. [[Special: MyLanguage / Pin_pull-up | Pin_pull-up]]. | ||
=== sysfs interface | === sysfs interface under Linux === | ||
GPIO under Linux are supported through sysfs-interface. | |||
To work | To work through a certain GPIO sysfs it must be exported: | ||
Here and further N | Here and further N - number of gpio | ||
<pre> | <pre> | ||
Строка 38: | Строка 38: | ||
</pre> | </pre> | ||
The | В директории <b>/sys/class/gpioN</b> теперь находятся файлы для работы с GPIO (где N - номер GPIO, как и было сказано ранее): | ||
The directory <b>/sys/class/gpioN</b> are now files to work with GPIO (where N - No. of GPIO, as was said earlier): | |||
<pre> | <pre> | ||
Строка 55: | Строка 56: | ||
<pre> | <pre> | ||
echo in > /sys/class/gpio/gpioN/direction #set the GPIO | echo in > /sys/class/gpio/gpioN/direction #set the GPIO to input | ||
echo out > /sys/class/gpio/gpioN/direction # set the GPIO | echo out > /sys/class/gpio/gpioN/direction # set the GPIO to output | ||
</pre> | </pre> | ||
Reading and | Reading and Setting the GPIO is made using the file <b>value</b>. | ||
Reading: | Reading: | ||
Строка 107: | Строка 108: | ||
Interrupts can be caught from userspace using the system call | Interrupts can be caught from userspace using the system call poll () and select () on file value. | ||
Example of look here [https://github.com/contactless/wiegand-linux-sysfs] | |||
see also [http://elinux.org/GPIO elinux.org] | see also [http://elinux.org/GPIO elinux.org] | ||
=== | ===Прямое обращение через память процессора=== | ||
<b> | <b>Этот метод настоятельно НЕ РЕКОМЕНДУЕТСЯ для использования без достаточных оснований. Для работы из С/C++ стоит использовать работу через файлы в sysfs, как описано в предыдущем разделе</b>. | ||
Управлять GPIO можно с помощью прямого доступа к регистрам процессора, в обход Linux через интерфейс /dev/mem. При этом, по сравнению с работой через sysfs минимизуются наладные расходы. Этот метод можно использовать, | |||
если вам необходим очень быстрый доступ к GPIO, например bitbang протоколов или ШИМ. Стоит иметь в виду, что планировщик процессов всё ещё может вносить в работу программы значительные задержки. | |||
Рекомендуется выносить критичные ко времени задачи в ядро. | |||
См. [http://olimex.wordpress.com/2012/09/11/imx233-olinuxino-gpios-faster-and-faster/] , [https://github.com/OLIMEX/OLINUXINO/blob/master/SOFTWARE/iMX233/gpio-mmap.h] | |||
===GPIO | ===GPIO и Device Tree=== | ||
Указывать GPIO в Device Tree необходимо для настройки GPIO для работы в режиме программного SPI, I2C, для использования GPIO в качестве источника прерываний и т.д. | |||
Так например на пин 10@UEXT1 (CS) и пины 5@UEXT2 (SCL), 6@UEXT2 (SDA), 10@UEXT2 (CS) выведены линии GPIO процессора. Их можно сконфигурировать для использования например в качестве chip-select для SPI или в качестве I2C. | |||
GPIO процессора и периферийных устройств разбиты на банки (gpiochip). GPIO процессора разбиты на 3 банка по 32 GPIO: gpio0, gpio1, gpio2. Адресация GPIO в Device Tree происходит по номеру банка и номеру GPIO *внутри* банка. | |||
==== | ====Пример 1==== | ||
Определим сигнал 6@UEXT2 (SDA) в качестве источника прерываний для драйвера mrf24j40. Согласно таблице [[Special:MyLanguage/Список GPIO|Список GPIO]], сигнал соответствует GPIO 53 процессора. 53 принадлежит второму банку gpio (от 32 до 63). Номер GPIO внутри банка 53-32=21 : | |||
<pre> | <pre> |
Версия 13:13, 19 января 2016
In Wiren Board part GPIO output to terminal blocks, connectors on the expansion modules, the other part is used for business purposes. GPIO are also used to control the switching transistors for low-voltage load.
The correspondence between numbers GPIO Linux and their location and function can be found in the table WB SH 3.5: List of GPIO or WB rev. 2.8: List of GPIO.
In Wiren Board rev. 2.8 8 GPIO on a special connector connected via MCP23S08 and temporarily do not work with standard Linux API. How to work with them there on the pageMCP23S08.
All GPIO (as well as other ports Wiren Board) working with voltage 3.3V. In no case do not connect directly to the GPIO signals with voltage over 3.3V! In case you want to connect devices operating at a higher voltage, you must use matching circuits or connected (for 5V) through a resistor of 20 kOhm or more
On some GPIO (particularly at the 3 GPIO, launched into terminals in Wiren Board rev. 2.8) can be programmatically set to lift 47K + 3.3V. See. Pin_pull-up.
sysfs interface under Linux
GPIO under Linux are supported through sysfs-interface.
To work through a certain GPIO sysfs it must be exported:
Here and further N - number of gpio
echo N > /sys/class/gpio/export
Exported gpio appear in the catalog /sys/class/gpio :
root@wirenboard:~# ls -1 /sys/class/gpio/ export gpio32 gpiochip0 gpiochip120 gpiochip32 gpiochip64 unexport
В директории /sys/class/gpioN теперь находятся файлы для работы с GPIO (где N - номер GPIO, как и было сказано ранее): The directory /sys/class/gpioN are now files to work with GPIO (where N - No. of GPIO, as was said earlier):
root@wirenboard:~# ls -1 /sys/class/gpio/gpioN/ active_low device direction edge power subsystem uevent value
Setting the direction of GPIO (input / output) is made by writing to the file direction </ b>
echo in > /sys/class/gpio/gpioN/direction #set the GPIO to input echo out > /sys/class/gpio/gpioN/direction # set the GPIO to output
Reading and Setting the GPIO is made using the file value.
Reading:
echo in > /sys/class/gpio/gpioN/direction # Set GPIO a number N to input cat /sys/class/gpio/gpioN/value # returns 1 or 0
Record:
echo out > /sys/class/gpio/gpioN/direction # set GPIO No. N to output echo 0 > /sys/class/gpio/gpioN/value # set logic 0 (low voltage) on the GPIO No. N echo 1 > /sys/class/gpio/gpioN/value # set logical 1 (high voltage) to GPIO No. N
Sysfs interface and interrupt
Via sysfs interface, you can request a change of state interrupt processor.
Setting the interrupt is done by writing the values in the file "edge". Values can be:
- "none" - disable interrupt
- "rising" - enable interrupt on falling edge
- "falling" - enable interrupt on the rising edge
- "both" - enable interrupt on both edges.
Example:
root@wirenboard:~# echo 3 > /sys/class/gpio/export # export GPIO No. 3 (TB10 in WB3.3) root@wirenboard:~# cat /sys/class/gpio/gpio3/edge # check the status of the interrupt none root@wirenboard:~# echo falling > /sys/class/gpio/gpio3/edge # set interrupt falling edge root@wirenboard:~# cat /proc/interrupts | grep gpiolib # interrupt appears in the list. 26 - internal interrupt, 0 - the number of events 26: 0 gpio-mxs 3 gpiolib root@wirenboard:~# cat /proc/interrupts | grep gpiolib # After several events, 76 - the number of events 26: 76 gpio-mxs 3 gpiolib
Interrupts can be caught from userspace using the system call poll () and select () on file value. Example of look here [1]
see also elinux.org
Прямое обращение через память процессора
Этот метод настоятельно НЕ РЕКОМЕНДУЕТСЯ для использования без достаточных оснований. Для работы из С/C++ стоит использовать работу через файлы в sysfs, как описано в предыдущем разделе.
Управлять GPIO можно с помощью прямого доступа к регистрам процессора, в обход Linux через интерфейс /dev/mem. При этом, по сравнению с работой через sysfs минимизуются наладные расходы. Этот метод можно использовать, если вам необходим очень быстрый доступ к GPIO, например bitbang протоколов или ШИМ. Стоит иметь в виду, что планировщик процессов всё ещё может вносить в работу программы значительные задержки. Рекомендуется выносить критичные ко времени задачи в ядро.
GPIO и Device Tree
Указывать GPIO в Device Tree необходимо для настройки GPIO для работы в режиме программного SPI, I2C, для использования GPIO в качестве источника прерываний и т.д. Так например на пин 10@UEXT1 (CS) и пины 5@UEXT2 (SCL), 6@UEXT2 (SDA), 10@UEXT2 (CS) выведены линии GPIO процессора. Их можно сконфигурировать для использования например в качестве chip-select для SPI или в качестве I2C.
GPIO процессора и периферийных устройств разбиты на банки (gpiochip). GPIO процессора разбиты на 3 банка по 32 GPIO: gpio0, gpio1, gpio2. Адресация GPIO в Device Tree происходит по номеру банка и номеру GPIO *внутри* банка.
Пример 1
Определим сигнал 6@UEXT2 (SDA) в качестве источника прерываний для драйвера mrf24j40. Согласно таблице Список GPIO, сигнал соответствует GPIO 53 процессора. 53 принадлежит второму банку gpio (от 32 до 63). Номер GPIO внутри банка 53-32=21 :
6lowpan@0 { compatible = "microchip,mrf24j40"; spi-max-frequency = <100000>; reg = <6>; interrupt-parent = <&gpio1>; interrupts = <21 0>; };