Перейти к содержанию

Навигация

Работа с GPIO/en: различия между версиями

Нет описания правки
(Новая страница: «Reading:»)
 
(не показаны 43 промежуточные версии 2 участников)
Строка 1: Строка 1:
<languages/>
<languages/>
In Wiren Board part GPIO output to terminal blocks, connectors on the expansion modules, the other part is used for business purposes.
In Wiren Board a part of GPIOs is output to terminal blocks,a part - to connectors on the expansion modules, the other part is used for utility 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 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]].
The correspondence between GPIO numbers in Linux and between 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 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]].
In Wiren Board rev. 2.8 8 GPIO are placed on a special connector and connected via [[Special:MyLanguage/MCP23S08|MCP23S08]] and temporarily do not work with Linux API standard. How to work with them: see page [[Special:MyLanguage/MCP23S08|MCP23S08]].


<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>
<b> All GPIOs (as well as other ports of Wiren Board controllers) work with 3.3V voltage.Do not connect signals with voltage over 3.3V directly to the GPIO! In case you want to connect devices operating at a higher voltage, you must use matching circuits or connect(for 5V) via a resistor of 20 kOhm or more</b>




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]].
On some GPIOs (particularly at the 3 GPIOs, 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 under Linux ===
=== sysfs interface in Linux ===


GPIO under Linux are supported through sysfs-interface.
GPIOs in Linux are supported through sysfs-interface.


To work through a certain GPIO sysfs it must be exported:
To work via sysfs a certain GPIO must be exported:


Here and further N - number of gpio
Here and further N is a number of gpio


<pre>
<pre>
Строка 38: Строка 38:
</pre>
</pre>


В директории <b>/sys/class/gpioN</b> теперь находятся файлы для работы с GPIO (где N - номер GPIO, как и было сказано ранее):
The folder <b>/sys/class/gpioN</b> now contains files to work with GPIO (where N is a GPIO number):
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>
Строка 56: Строка 55:


<pre>
<pre>
echo in > /sys/class/gpio/gpioN/direction #set the GPIO to input
echo in > /sys/class/gpio/gpioN/direction #set the GPIO N to input
echo out > /sys/class/gpio/gpioN/direction # set the GPIO to output  
echo out > /sys/class/gpio/gpioN/direction # set the GPIO N to output  
</pre>
</pre>


Reading and Setting the GPIO is made using the file <b>value</b>.  
Reading and setting the GPIO is made using the file <b>value</b>.  


Reading:
Reading:


<pre>
<pre>
echo in > /sys/class/gpio/gpioN/direction # установим GPIO номер N на ввод
echo in > /sys/class/gpio/gpioN/direction # Set GPIO a number N to input
cat /sys/class/gpio/gpioN/value # вернёт 1 или 0
cat /sys/class/gpio/gpioN/value # returns 1 or 0
</pre>
</pre>


Запись:
Record:


<pre>
<pre>
echo out > /sys/class/gpio/gpioN/direction # установим GPIO номер N на вывод
echo out > /sys/class/gpio/gpioN/direction # set GPIO No. N to output
echo 0 > /sys/class/gpio/gpioN/value # установим логический 0 (низкое напряжение) на GPIO номер N
echo 0 > /sys/class/gpio/gpioN/value # set logic 0 (low voltage) on the GPIO No. N
echo 1 > /sys/class/gpio/gpioN/value # установим логический 1 (высокое напряжение) на GPIO номер N
echo 1 > /sys/class/gpio/gpioN/value # set logical 1 (high voltage) to GPIO No. N
</pre>
</pre>






====Интерфейс sysfs и прерывания====
====Sysfs interface and interrupt====


Через интерфейс sysfs можно запросить прерывания по изменению состояния процессора.
Via sysfs interface, you can request a change of state interrupt processor.


Установка прерывания производится путём записи значения в файл "edge". Значения могут быть:
Setting the interrupt is done by writing the values in the file "edge". Values can be:
* "none" - отключить прерывание
* "none" - disable interrupt
* "rising" - включить прерывание по нисходящему фронту
* "rising" - enable interrupt on falling edge
* "falling" - включить прерывание по восодящему фронту
* "falling" - enable interrupt on the rising edge
* "both" - включить прерывание по обеим фронтам.
* "both" - enable interrupt on both edges.


Пример:
Example:
<pre>
<pre>
root@wirenboard:~# echo 3 >  /sys/class/gpio/export # экспортируем GPIO номер 3 (TB10 на WB3.3)
root@wirenboard:~# echo 3 >  /sys/class/gpio/export # export GPIO No. 3 (TB10 in WB3.3)
root@wirenboard:~# cat /sys/class/gpio/gpio3/edge  # проверяем состояние прерывания
root@wirenboard:~# cat /sys/class/gpio/gpio3/edge  # check the status of the interrupt
none
none
root@wirenboard:~# echo falling > /sys/class/gpio/gpio3/edge # устанавливаем прерывание по нисходящему фронту
root@wirenboard:~# echo falling > /sys/class/gpio/gpio3/edge # set interrupt falling edge
root@wirenboard:~# cat /proc/interrupts  | grep gpiolib # прерывание появилось в списке. 26 - внутренний номер прерывания, 0 - количество событий
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
  26:          0  gpio-mxs  3  gpiolib
root@wirenboard:~# cat /proc/interrupts  | grep gpiolib # после нескольких собтий, 76 - количество событий
root@wirenboard:~# cat /proc/interrupts  | grep gpiolib # After several events, 76 - the number of events
  26:        76  gpio-mxs  3  gpiolib
  26:        76  gpio-mxs  3  gpiolib


Строка 108: Строка 107:




Прерывания можно ловить из userspace с помощью системного вызова epoll() и select() на файл value.
Interrupts can be caught from userspace using the system call epoll () and select () on file value.
Пример работы см. [https://github.com/contactless/wiegand-linux-sysfs]
See example here [https://github.com/contactless/wiegand-linux-sysfs]


См. также [http://elinux.org/GPIO elinux.org]
see also [http://elinux.org/GPIO elinux.org]




===Прямое обращение через память процессора===
===Direct access by processor memory===


<b>Этот метод настоятельно НЕ РЕКОМЕНДУЕТСЯ для использования без достаточных оснований. Для работы из С/C++ стоит использовать работу через файлы в sysfs, как описано в предыдущем разделе</b>.
<b>This method is NOT strongly recommended for use without sufficient reason. To work in C / C ++ is to use the files to work through sysfs, as described in the previous section</b>.


Управлять GPIO можно с помощью прямого доступа к регистрам процессора, в обход Linux через интерфейс /dev/mem. При этом, по сравнению с работой через sysfs минимизуются наладные расходы. Этот метод можно использовать,  
You can manage GPIO using the direct access to the processor registers, bypassing the Linux interface/dev/mem. At the same time, compared to the work via sysfs, this case minimizes costs. This method can be used,
если вам необходим очень быстрый доступ к GPIO, например bitbang протоколов или ШИМ. Стоит иметь в виду, что планировщик процессов всё ещё может вносить в работу программы значительные задержки.
if you need a very fast access to GPIO, such bitbang protocols or PWM. It should be borne in mind that the process scheduler can still contribute to the work program of significant delays.
Рекомендуется выносить критичные ко времени задачи в ядро.
It is recommended to make time-critical tasks in the kernel.


См. [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]
See [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 и Device Tree===
===GPIO and Device Tree===


Указывать GPIO в Device Tree необходимо для настройки GPIO для работы в режиме программного SPI, I2C, для использования GPIO в качестве источника прерываний и т.д.
It's necessary to place the GPIO in Device Tree to configure the GPIO to work in a mode of software SPI, I2C, for GPIO to be used as the source of the interrupt, etc.
Так например на пин 10@UEXT1 (CS) и пины 5@UEXT2 (SCL), 6@UEXT2 (SDA), 10@UEXT2 (CS) выведены линии GPIO процессора. Их можно сконфигурировать для использования например в качестве chip-select для SPI или в качестве I2C.
For example on a pin 10 @ UEXT1 (CS) and pins 5 @ UEXT2 (SCL), 6 @ UEXT2 (SDA), 10 @ UEXT2 (CS) GPIO processor lines are derived. They can be configured to use such as a chip-select for SPI or as I2C.


GPIO процессора и периферийных устройств разбиты на банки (gpiochip). GPIO процессора разбиты на 3 банка по 32 GPIO: gpio0, gpio1, gpio2. Адресация GPIO в Device Tree происходит по номеру банка и номеру GPIO *внутри* банка.
The processor's and peripherals' GPIOs are divided into banks (gpio chip).Processor's  GPIO are split into 3 banks for 32 GPIO: gpio0, gpio1, gpio2. Addressing GPIO in Device Tree comes to the number of the bank and the number of GPIO * in * the bank.




====Пример 1====
====Example 1====


Определим сигнал 6@UEXT2 (SDA) в качестве источника прерываний для драйвера mrf24j40. Согласно таблице [[Special:MyLanguage/Список GPIO|Список GPIO]], сигнал соответствует GPIO 53 процессора. 53 принадлежит второму банку gpio (от 32 до 63). Номер GPIO внутри банка 53-32=21 :
We define signal 6 @ UEXT2 (SDA) as the source of the interrupt driver mrf24j40. According to the table [[Special:MyLanguage/Список_GPIO/en|List of GPIOs]], signal corresponds to 53 GPIO of processor. 53 belongs to the second bank gpio (32 to 63). GPIO number inside the bank 53-32 = 21:


<pre>
<pre>
12 063

правки