GPIO в Linux

Вопросы программного кода и архитектуры Linux

Модератор: Olej

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: GPIO в Linux

Непрочитанное сообщение Olej » 25 авг 2022, 20:49

И ещё:

Код: Выделить всё

root@orangepione:~# gpioget --help
Usage: gpioget [OPTIONS] <chip name/number> <offset 1> <offset 2> ...
Read line value(s) from 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

Код: Выделить всё

  
root@orangepione:~# gpioset --help
Usage: gpioset [OPTIONS] <chip name/number> <offset1>=<value1> <offset2>=<value2> ...
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=[exit|wait|time|signal] (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

Код: Выделить всё

root@orangepione:~# gpiodetect
gpiochip0 [1c20800.pinctrl] (224 lines)
gpiochip1 [1f02c00.pinctrl] (32 lines)
И используем:

Код: Выделить всё

root@orangepione:~# gpiodetect
gpiochip0 [1c20800.pinctrl] (224 lines)
gpiochip1 [1f02c00.pinctrl] (32 lines)

Код: Выделить всё

root@orangepione:~# gpioset 1 11=1

root@orangepione:~# gpioget 1 11
1

Код: Выделить всё

root@orangepione:~# gpioset 1 11=0

root@orangepione:~# gpioget 1 11
0

Код: Выделить всё

root@orangepione:~# gpioget gpiochip1 9
1

root@orangepione:~# gpioget gpiochip1 11
0

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: GPIO в Linux

Непрочитанное сообщение Olej » 25 авг 2022, 20:55

Olej писал(а):
25 авг 2022, 20:45
В Orange Pi One обнаруживаем:
Я, насколько помню, в этой инсталляции ничего с GPIO не устанавливал ... это свежая инсталляция:

Код: Выделить всё

olej@orangepione:~$ lsb_release -a
No LSB modules are available.
Distributor ID:	Debian
Description:	Debian GNU/Linux 10 (buster)
Release:	10
Codename:	buster

olej@orangepione:~$ uname -a
Linux orangepione 5.15.48-sunxi #22.05.3 SMP Wed Jun 22 07:35:10 UTC 2022 armv7l GNU/Linux

Значит это по умолчаию заложили сборщики Armbian, потому что собирали имидж под конкретный тип железки.
Тогда нужно установить в составе какого пакета устанавливается этот CLI комплект:

Код: Выделить всё

root@orangepione:~# apt-file find gpiodetect
gpiod: /usr/bin/gpiodetect                
python3-libgpiod: /usr/share/doc/python3-libgpiod/examples/gpiodetect.py
Вот он: gpiod

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: GPIO в Linux

Непрочитанное сообщение Olej » 25 авг 2022, 21:01

Olej писал(а):
25 авг 2022, 16:40
2. Новый интерфейс к GPIO
Olej писал(а):
25 авг 2022, 16:40
4. Программный kernel API GPIO
Эти позиции пока оставлю на потом ... иначе запутаюсь совсем.
Пока помотрю как выглядят п.п.1,3 в Raspberry Pi:

Код: Выделить всё

olej@raspberrypi:~/2022/kernel/examples/GPIO $ inxi -MCxxxf
Machine:   Type: ARM Device System: Raspberry Pi 2 Model B Rev 1.1 details: BCM2835 rev: a21041 serial: 00000000f57e2ca8 
CPU:       Info: Quad Core model: ARMv7 v7l variant: cortex-a7 bits: 32 type: MCP arch: v7l rev: 5 bogomips: 256 
           Speed: 1000 MHz min/max: 600/1000 MHz Core speeds (MHz): 1: 1000 2: 1000 3: 1000 4: 1000 
           Features: edsp evtstrm fastmult half idiva idivt lpae neon thumb tls vfp vfpd32 vfpv3 vfpv4 
Система Raspbian OS - их рожная, рекомендуемая от производителя:

Код: Выделить всё

olej@raspberrypi:~/2022/kernel/examples/GPIO $ inxi -Sxxx
System:    Host: raspberrypi Kernel: 5.15.32-v7+ armv7l bits: 32 compiler: gcc v: 10.2.1 Console: tty 4 DM: LightDM 1.26.0 
           Distro: Raspbian GNU/Linux 11 (bullseye) 
           
olej@raspberrypi:~/2022/kernel/examples/GPIO $ lsb_release -a
No LSB modules are available.
Distributor ID:	Raspbian
Description:	Raspbian GNU/Linux 11 (bullseye)
Release:	11
Codename:	bullseye

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: GPIO в Linux

Непрочитанное сообщение Olej » 25 авг 2022, 21:12

Olej писал(а):
25 авг 2022, 21:01
Пока помотрю как выглядят п.п.1,3 в Raspberry Pi:
1. Интерфейс (старый) sysfs:

Код: Выделить всё

olej@raspberrypi:~ $ ls -l /sys/class/gpio
итого 0
--w--w---- 1 root gpio 4096 авг 25 14:14 export
lrwxrwxrwx 1 root gpio    0 авг 25 14:14 gpiochip0 -> ../../devices/platform/soc/3f200000.gpio/gpio/gpiochip0
--w--w---- 1 root gpio 4096 авг 25 14:14 unexport

Код: Выделить всё

olej@raspberrypi:~ $ cat /sys/class/gpio/gpiochip*/ngpio
54

Код: Выделить всё

root@raspberrypi:~# echo 16 > /sys/class/gpio/export

root@raspberrypi:~# ls -l /sys/class/gpio
итого 0
--w--w---- 1 root gpio 4096 авг 25 21:05 export
lrwxrwxrwx 1 root root    0 авг 25 21:05 gpio16 -> ../../devices/platform/soc/3f200000.gpio/gpiochip0/gpio/gpio16
lrwxrwxrwx 1 root gpio    0 авг 25 14:14 gpiochip0 -> ../../devices/platform/soc/3f200000.gpio/gpio/gpiochip0
--w--w---- 1 root gpio 4096 авг 25 14:14 unexport

Код: Выделить всё

root@raspberrypi:~# tree /sys/class/gpio/gpio16
/sys/class/gpio/gpio16
├── active_low
├── device -> ../../../gpiochip0
├── direction
├── edge
├── power
│   ├── autosuspend_delay_ms
│   ├── control
│   ├── runtime_active_time
│   ├── runtime_status
│   └── runtime_suspended_time
├── subsystem -> ../../../../../../../class/gpio
├── uevent
└── value

3 directories, 10 files

Код: Выделить всё

root@raspberrypi:~# cat /sys/class/gpio/gpio16/direction
in

root@raspberrypi:~# echo out > /sys/class/gpio/gpio16/direction

root@raspberrypi:~# cat /sys/class/gpio/gpio16/direction
out

Код: Выделить всё

root@raspberrypi:~# cat /sys/class/gpio/gpio16/value
0

root@raspberrypi:~# echo 1 > /sys/class/gpio/gpio16/value

root@raspberrypi:~# cat /sys/class/gpio/gpio16/value
1

Код: Выделить всё

root@raspberrypi:~# echo 16 > /sys/class/gpio/unexport

Код: Выделить всё

root@raspberrypi:~# ls -l /sys/class/gpio
итого 0
--w--w---- 1 root gpio 4096 авг 25 21:05 export
lrwxrwxrwx 1 root gpio    0 авг 25 14:14 gpiochip0 -> ../../devices/platform/soc/3f200000.gpio/gpio/gpiochip0
--w--w---- 1 root gpio 4096 авг 25 21:10 unexport
Всё так же как уже видели...

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: GPIO в Linux

Непрочитанное сообщение Olej » 25 авг 2022, 21:12

Olej писал(а):
25 авг 2022, 21:01
Пока помотрю как выглядят п.п.1,3 в Raspberry Pi:
3. набор CLI утилит...

Код: Выделить всё

root@R420:~# ls /bin/*gpio*
ls: невозможно получить доступ к '/bin/*gpio*': Нет такого файла или каталога

root@R420:~# ls /usr/bin/*gpio*
ls: невозможно получить доступ к '/usr/bin/*gpio*': Нет такого файла или каталога
Нет тех утилит...

Код: Выделить всё

olej@raspberrypi:~/2022/kernel/examples/GPIO $ aptitude search gpio
p   gpiod                                                                       - Tools for interacting with Linux GPIO character device - binary
p   libgpiod-dev                                                                - C library for interacting with Linux GPIO device - static libraries and headers
p   libgpiod-doc                                                                - C library for interacting with Linux GPIO device - library documentation
p   libgpiod2                                                                   - C library for interacting with Linux GPIO device - shared libraries
i A libpigpio-dev                                                               - Client tools for Raspberry Pi GPIO control
i A libpigpio1                                                                  - Library for Raspberry Pi GPIO control
i A libpigpiod-if-dev                                                           - Development headers for client libraries for Raspberry Pi GPIO control
i A libpigpiod-if1                                                              - Client library for Raspberry Pi GPIO control (deprecated)
i A libpigpiod-if2-1                                                            - Client library for Raspberry Pi GPIO control
i   pigpio                                                                      - Raspberry Pi GPIO control transitional package.
i A pigpio-tools                                                                - Client tools for Raspberry Pi GPIO control
i A pigpiod                                                                     - Client tools for Raspberry Pi GPIO control
p   python-gpiozero                                                             - Simple API for controlling devices attached to a Pi's GPIO pins.
p   python-gpiozero-doc                                                         - Simple API for controlling devices attached to a Pi's GPIO pins.
p   python-pigpio                                                               - Python module which talks to the pigpio daemon (Python 2)
i   python3-gpiozero                                                            - Simple API for controlling devices attached to a Pi's GPIO pins.
p   python3-libgpiod                                                            - Python bindings for libgpiod (Python 3)
i   python3-pigpio                                                              - Python module which talks to the pigpio daemon (Python 3)
i   python3-rpi.gpio                                                            - Module to control Raspberry Pi GPIO channels (Python 3)
i   raspi-gpio                                                                  - Dump the state of the BCM270x GPIOs
p   raspi-gpio-dbgsym                                                           - debug symbols for raspi-gpio
i A rpi.gpio-common                                                             - Module to control Raspberry Pi GPIO channels (common files)
p   svxlink-gpio                                                                - GPIO control scripts SvxLink amateur radio server
Не установлен gpiod. Но зато установлен свой собственный пакет(ы)...

Код: Выделить всё

root@raspberrypi:~# apt show pigpio-tools
Package: pigpio-tools
Version: 1.79-1+rpt1
Priority: optional
Section: utils
Source: pigpio
Maintainer: Peter Michael Green <plugwash@debian.org>
Installed-Size: 77,8 kB
Depends: libc6 (>= 2.7)
Conflicts: pigpio (<< 1.68-1)
Homepage: http://abyz.co.uk/rpi/pigpio/
Download-Size: 42,9 kB
APT-Manual-Installed: no
APT-Sources: http://archive.raspberrypi.org/debian bullseye/main armhf Packages
Description: Client tools for Raspberry Pi GPIO control
 Pigpio is a set of software which allows control of the General Purpose Input
 Outputs (GPIO) locally or remotely.
 .
 This package provides the pigs and pig2vcd tools.

Код: Выделить всё

 
root@raspberrypi:~# apt show pigpiod
Package: pigpiod
Version: 1.79-1+rpt1
Priority: optional
Section: utils
Source: pigpio
Maintainer: Peter Michael Green <plugwash@debian.org>
Installed-Size: 35,8 kB
Depends: libc6 (>= 2.28), libpigpio1
Conflicts: pigpio (<< 1.68-1)
Homepage: http://abyz.co.uk/rpi/pigpio/
Download-Size: 9.900 B
APT-Manual-Installed: no
APT-Sources: http://archive.raspberrypi.org/debian bullseye/main armhf Packages
Description: Client tools for Raspberry Pi GPIO control
 Pigpio is a set of software which allows control of the General Purpose Input
 Outputs (GPIO) locally or remotely.
 .
 This package provides the pigpiod daemon which offers a socket and pipe
 interface to the underlying library.

Начну сразу с них ... раньше дженерика gpiod ...

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: GPIO в Linux

Непрочитанное сообщение Olej » 25 авг 2022, 21:21

Olej писал(а):
25 авг 2022, 21:12
Начну сразу с них ... раньше дженерика gpiod ...

Код: Выделить всё

root@raspberrypi:~# which pigs
/usr/bin/pigs

root@raspberrypi:~# which pig2vcd
/usr/bin/pig2vcd

root@raspberrypi:~# which pigpiod
/usr/bin/pigpiod

root@raspberrypi:~# ls /usr/bin/*gpio*
/usr/bin/pigpiod  /usr/bin/raspi-gpio

root@raspberrypi:~# ls /bin/*gpio*
/bin/pigpiod  /bin/raspi-gpio
Диагностика:

Код: Выделить всё

root@raspberrypi:~# raspi-gpio help

WARNING! raspi-gpio set writes directly to the GPIO control registers
ignoring whatever else may be using them (such as Linux drivers) -
it is designed as a debug tool, only use it if you know what you
are doing and at your own risk!

The raspi-gpio tool is designed to help hack / debug BCM283x GPIO.
Running raspi-gpio with the help argument prints this help.
raspi-gpio can get and print the state of a GPIO (or all GPIOs)
and can be used to set the function, pulls and value of a GPIO.
raspi-gpio must be run as root.
Use:
  raspi-gpio get [GPIO]
OR
  raspi-gpio set <GPIO> [options]
OR
  raspi-gpio funcs [GPIO]
OR
  raspi-gpio raw

GPIO is a comma-separated list of pin numbers or ranges (without spaces),
e.g. 4 or 18-21 or 7,9-11
Note that omitting [GPIO] from raspi-gpio get prints all GPIOs.
raspi-gpio funcs will dump all the possible GPIO alt funcions in CSV format
or if [GPIO] is specified the alternate funcs just for that specific GPIO.
Valid [options] for raspi-gpio set are:
  ip      set GPIO as input
  op      set GPIO as output
  a0-a5   set GPIO to alternate function alt0-alt5
  pu      set GPIO in-pad pull up
  pd      set GPIO pin-pad pull down
  pn      set GPIO pull none (no pull)
  dh      set GPIO to drive to high (1) level (only valid if set to be an output)
  dl      set GPIO to drive low (0) level (only valid if set to be an output)
Examples:
  raspi-gpio get              Prints state of all GPIOs one per line
  raspi-gpio get 20           Prints state of GPIO20
  raspi-gpio get 20,21        Prints state of GPIO20 and GPIO21
  raspi-gpio set 20 a5        Set GPIO20 to ALT5 function (GPCLK0)
  raspi-gpio set 20 pu        Enable GPIO20 ~50k in-pad pull up
  raspi-gpio set 20 pd        Enable GPIO20 ~50k in-pad pull down
  raspi-gpio set 20 op        Set GPIO20 to be an output
  raspi-gpio set 20 dl        Set GPIO20 to output low/zero (must already be set as an output)
  raspi-gpio set 20 ip pd     Set GPIO20 to input with pull down
  raspi-gpio set 35 a0 pu     Set GPIO35 to ALT0 function (SPI_CE1_N) with pull up
  raspi-gpio set 20 op pn dh  Set GPIO20 to ouput with no pull and driving high

Код: Выделить всё

root@raspberrypi:~# raspi-gpio get
BANK0 (GPIO 0 to 27):
GPIO 0: level=1 fsel=0 func=INPUT
GPIO 1: level=1 fsel=0 func=INPUT
GPIO 2: level=1 fsel=0 func=INPUT
GPIO 3: level=1 fsel=0 func=INPUT
GPIO 4: level=1 fsel=0 func=INPUT
GPIO 5: level=1 fsel=0 func=INPUT
GPIO 6: level=1 fsel=0 func=INPUT
GPIO 7: level=1 fsel=0 func=INPUT
GPIO 8: level=1 fsel=0 func=INPUT
GPIO 9: level=0 fsel=0 func=INPUT
GPIO 10: level=0 fsel=0 func=INPUT
GPIO 11: level=0 fsel=0 func=INPUT
GPIO 12: level=0 fsel=0 func=INPUT
GPIO 13: level=0 fsel=0 func=INPUT
GPIO 14: level=1 fsel=4 alt=0 func=TXD0
GPIO 15: level=1 fsel=4 alt=0 func=RXD0
GPIO 16: level=0 fsel=0 func=INPUT
GPIO 17: level=0 fsel=0 func=INPUT
GPIO 18: level=0 fsel=0 func=INPUT
GPIO 19: level=0 fsel=0 func=INPUT
GPIO 20: level=0 fsel=0 func=INPUT
GPIO 21: level=0 fsel=0 func=INPUT
GPIO 22: level=0 fsel=0 func=INPUT
GPIO 23: level=0 fsel=0 func=INPUT
GPIO 24: level=0 fsel=0 func=INPUT
GPIO 25: level=0 fsel=0 func=INPUT
GPIO 26: level=0 fsel=0 func=INPUT
GPIO 27: level=0 fsel=0 func=INPUT
BANK1 (GPIO 28 to 45):
GPIO 28: level=1 fsel=0 func=INPUT
GPIO 29: level=1 fsel=0 func=INPUT
GPIO 30: level=0 fsel=0 func=INPUT
GPIO 31: level=1 fsel=1 func=OUTPUT
GPIO 32: level=1 fsel=1 func=OUTPUT
GPIO 33: level=0 fsel=0 func=INPUT
GPIO 34: level=1 fsel=0 func=INPUT
GPIO 35: level=0 fsel=0 func=INPUT
GPIO 36: level=1 fsel=0 func=INPUT
GPIO 37: level=0 fsel=0 func=INPUT
GPIO 38: level=1 fsel=1 func=OUTPUT
GPIO 39: level=0 fsel=0 func=INPUT
GPIO 40: level=1 fsel=4 alt=0 func=PWM0
GPIO 41: level=0 fsel=1 func=OUTPUT
GPIO 42: level=1 fsel=1 func=OUTPUT
GPIO 43: level=1 fsel=0 func=INPUT
GPIO 44: level=0 fsel=4 alt=0 func=GPCLK1
GPIO 45: level=1 fsel=4 alt=0 func=PWM1
BANK2 (GPIO 46 to 53):
GPIO 46: level=0 fsel=0 func=INPUT
GPIO 47: level=1 fsel=1 func=OUTPUT
GPIO 48: level=1 fsel=4 alt=0 func=SD0_CLK
GPIO 49: level=1 fsel=4 alt=0 func=SD0_CMD
GPIO 50: level=0 fsel=4 alt=0 func=SD0_DAT0
GPIO 51: level=0 fsel=4 alt=0 func=SD0_DAT1
GPIO 52: level=0 fsel=4 alt=0 func=SD0_DAT2
GPIO 53: level=0 fsel=4 alt=0 func=SD0_DAT3
Вот они - все те 54 линии:

Код: Выделить всё

olej@raspberrypi:~ $ cat /sys/class/gpio/gpiochip*/ngpio
54
Но что там такое у них BANK1, BANK2, BANK3 - ума не приложу!

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: GPIO в Linux

Непрочитанное сообщение Olej » 25 авг 2022, 21:25

Olej писал(а):
25 авг 2022, 21:21
Диагностика:
И далее:

Код: Выделить всё

root@raspberrypi:~# pigs help

BC1 bits         Clear GPIO in bank 1
BC2 bits         Clear GPIO in bank 2
BI2CC sda        Close bit bang I2C
BI2CO sda scl baud | Open bit bang I2C
BI2CZ sda ...    I2C bit bang multiple transactions

BSPIC cs        Close bit bang SPI
BSPIO cs miso mosi sclk baud flag | Open bit bang SPI
BSPIX cs ...    SPI bit bang transfer

BR1              Read bank 1 GPIO
BR2              Read bank 2 GPIO

BS1 bits         Set GPIO in bank 1
BS2 bits         Set GPIO in bank 2

BSCX bctl bvs    BSC I2C/SPI transfer

CF1 ...          Custom function 1
CF2 ...          Custom function 2

CGI              Configuration get internals
CSI v            Configuration set internals

EVM h bits       Set events to monitor
EVT n            Trigger event

FC h             Close file handle
FG g steady      Set glitch filter on GPIO
FL pat n         List files which match pattern
FN g steady active | Set noise filter on GPIO
FO file mode     Open a file in mode
FR h n           Read bytes from file handle
FS h n from      Seek to file handle position
FW h ...         Write bytes to file handle

GDC g            Get PWM dutycycle for GPIO
GPW g            Get servo pulsewidth for GPIO

H/HELP           Display command help
HC g f           Set hardware clock frequency
HP g f dc        Set hardware PWM frequency and dutycycle
HWVER            Get hardware version

I2CC h           Close I2C handle
I2CO bus device flags | Open I2C bus and device with flags
I2CPC h r word   SMBus Process Call: exchange register with word
I2CPK h r ...    SMBus Block Process Call: exchange data bytes with register
I2CRB h r        SMBus Read Byte Data: read byte from register
I2CRD h n        I2C Read bytes
I2CRI h r n      SMBus Read I2C Block Data: read bytes from register
I2CRK h r        SMBus Read Block Data: read data from register
I2CRS h          SMBus Read Byte: read byte
I2CRW h r        SMBus Read Word Data: read word from register
I2CWB h r byte   SMBus Write Byte Data: write byte to register
I2CWD h ...      I2C Write data
I2CWI h r ...    SMBus Write I2C Block Data
I2CWK h r ...    SMBus Write Block Data: write data to register
I2CWQ h b        SMBus Write Quick: write bit
I2CWS h b        SMBus Write Byte: write byte
I2CWW h r word   SMBus Write Word Data: write word to register
I2CZ  h ...      I2C multiple transactions

M/MODES g mode   Set GPIO mode
MG/MODEG g       Get GPIO mode
MICS n           Delay for microseconds
MILS n           Delay for milliseconds

NB h bits        Start notification
NC h             Close notification
NO               Request a notification
NP h             Pause notification

P/PWM g v        Set GPIO PWM value
PADG pad         Get pad drive strength
PADS pad v       Set pad drive strength
PARSE text       Validate script
PFG g            Get GPIO PWM frequency
PFS g v          Set GPIO PWM frequency
PIGPV            Get pigpio library version
PRG g            Get GPIO PWM range
PROC text        Store script
PROCD sid        Delete script
PROCP sid        Get script status and parameters
PROCR sid ...    Run script
PROCS sid        Stop script
PROCU sid ...    Set script parameters
PRRG g           Get GPIO PWM real range
PRS g v          Set GPIO PWM range
PUD g pud        Set GPIO pull up/down

R/READ g         Read GPIO level

S/SERVO g v      Set GPIO servo pulsewidth
SERC h           Close serial handle
SERDA h          Check for serial data ready to read
SERO text baud flags | Open serial device at baud with flags
SERR h n         Read bytes from serial handle
SERRB h          Read byte from serial handle
SERW h ...       Write bytes to serial handle
SERWB h byte     Write byte to serial handle
SHELL name str   Execute a shell command
SLR g v          Read bit bang serial data from GPIO
SLRC g           Close GPIO for bit bang serial data
SLRO g baud bitlen | Open GPIO for bit bang serial data
SLRI g invert    Invert serial logic (1 invert, 0 normal)
SPIC h           SPI close handle
SPIO channel baud flags | SPI open channel at baud with flags
SPIR h v         SPI read bytes from handle
SPIW h ...       SPI write bytes to handle
SPIX h ...       SPI transfer bytes to handle

T/TICK           Get current tick
TRIG g micros l  Trigger level for micros on GPIO

W/WRITE g l      Write level to GPIO
WDOG g millis    Set millisecond watchdog on GPIO
WVAG triplets    Wave add generic pulses
WVAS g baud bitlen stopbits offset ... | Wave add serial data
WVBSY            Check if wave busy
WVCHA            Transmit a chain of waves
WVCLR            Wave clear
WVCRE            Create wave from added pulses
WVDEL wid        Delete waves w and higher
WVGO             Wave transmit (DEPRECATED)
WVGOR            Wave transmit repeatedly (DEPRECATED)
WVHLT            Wave stop
WVNEW            Start a new empty wave
WVSC 0,1,2       Wave get DMA control block stats
WVSM 0,1,2       Wave get micros stats
WVSP 0,1,2       Wave get pulses stats
WVTAT            Returns the current transmitting wave
WVTX wid         Transmit wave as one-shot
WVTXM wid wmde   Transmit wave using mode
WVTXR wid        Transmit wave repeatedly

Numbers may be entered as hex (prefix 0x), octal (prefix 0),
otherwise they are assumed to be decimal.

Examples

pigs w 4 1         # set GPIO 4 high
pigs r 5           # read GPIO 5
pigs t             # get current tick
pigs i2co 1 0x20 0 # get handle to device 0x20 on I2C bus 1

man pigs for full details.

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: GPIO в Linux

Непрочитанное сообщение Olej » 25 авг 2022, 21:30

Olej писал(а):
25 авг 2022, 21:12
раньше дженерика gpiod ...

Код: Выделить всё

olej@raspberrypi:~/2022/kernel/examples/GPIO $ sudo apt install gpiod
Чтение списков пакетов… Готово
Построение дерева зависимостей… Готово
Чтение информации о состоянии… Готово
Будут установлены следующие дополнительные пакеты:
  libgpiod2
Следующие НОВЫЕ пакеты будут установлены:
  gpiod libgpiod2
Обновлено 0 пакетов, установлено 2 новых пакетов, для удаления отмечено 0 пакетов, и 0 пакетов не обновлено.
Необходимо скачать 57,0 kB архивов.
После данной операции объём занятого дискового пространства возрастёт на 227 kB.
Хотите продолжить? [Д/н] y
Пол:1 http://raspbian.raspberrypi.org/raspbian bullseye/main armhf libgpiod2 armhf 1.6.2-1+rpi1 [34,3 kB]
Пол:2 http://raspbian.raspberrypi.org/raspbian bullseye/main armhf gpiod armhf 1.6.2-1+rpi1 [22,7 kB]
Получено 57,0 kB за 1с (61,9 kB/s)
Выбор ранее не выбранного пакета libgpiod2:armhf.
(Чтение базы данных … на данный момент установлено 265236 файлов и каталогов.)
Подготовка к распаковке …/libgpiod2_1.6.2-1+rpi1_armhf.deb …
Распаковывается libgpiod2:armhf (1.6.2-1+rpi1) …
Выбор ранее не выбранного пакета gpiod.
Подготовка к распаковке …/gpiod_1.6.2-1+rpi1_armhf.deb …
Распаковывается gpiod (1.6.2-1+rpi1) …
Настраивается пакет libgpiod2:armhf (1.6.2-1+rpi1) …
Настраивается пакет gpiod (1.6.2-1+rpi1) …
Обрабатываются триггеры для man-db (2.9.4-2) …
Обрабатываются триггеры для libc-bin (2.31-13+rpt2+rpi1+deb11u3) …
И всё сразу появилось:

Код: Выделить всё

olej@raspberrypi:~/2022/kernel/examples/GPIO $ ls /bin/*gpio*
/bin/gpiodetect  /bin/gpiofind  /bin/gpioget  /bin/gpioinfo  /bin/gpiomon  /bin/gpioset  /bin/pigpiod  /bin/raspi-gpio

olej@raspberrypi:~/2022/kernel/examples/GPIO $ ls /usr/bin/*gpio*
/usr/bin/gpiodetect  /usr/bin/gpiofind  /usr/bin/gpioget  /usr/bin/gpioinfo  /usr/bin/gpiomon  /usr/bin/gpioset  /usr/bin/pigpiod  /usr/bin/raspi-gpio

Код: Выделить всё

root@raspberrypi:~# gpiodetect
gpiochip0 [pinctrl-bcm2835] (54 lines)
И диагностика всех линий:

Код: Выделить всё

root@raspberrypi:~# gpioinfo gpiochip0
gpiochip0 - 54 lines:
	line   0:     "ID_SDA"       unused   input  active-high 
	line   1:     "ID_SCL"       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:      "GPIO5"       unused   input  active-high 
	line   6:      "GPIO6"       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:     "GPIO12"       unused   input  active-high 
	line  13:     "GPIO13"       unused   input  active-high 
	line  14:       "TXD0"       unused   input  active-high 
	line  15:       "RXD0"       unused   input  active-high 
	line  16:     "GPIO16"       unused  output  active-high 
	line  17:     "GPIO17"       unused   input  active-high 
	line  18:     "GPIO18"       unused   input  active-high 
	line  19:     "GPIO19"       unused   input  active-high 
	line  20:     "GPIO20"       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   input  active-high 
	line  26:     "GPIO26"       unused   input  active-high 
	line  27:     "GPIO27"       unused   input  active-high 
	line  28:       "SDA0"       unused   input  active-high 
	line  29:       "SCL0"       unused   input  active-high 
	line  30:         "NC"       unused   input  active-high 
	line  31:    "LAN_RUN"       unused  output  active-high 
	line  32:  "CAM_GPIO1"       unused  output  active-high 
	line  33:         "NC"       unused   input  active-high 
	line  34:         "NC"       unused   input  active-high 
	line  35:  "PWR_LOW_N"       "led1"   input  active-high [used]
	line  36:         "NC"       unused   input  active-high 
	line  37:         "NC"       unused   input  active-high 
	line  38:  "USB_LIMIT"       unused  output  active-high 
	line  39:         "NC"       unused   input  active-high 
	line  40:   "PWM0_OUT"       unused   input  active-high 
	line  41:  "CAM_GPIO0" "cam1_regulator" output active-high [used]
	line  42:   "SMPS_SCL"       unused  output  active-high 
	line  43:   "SMPS_SDA"       unused   input  active-high 
	line  44:    "ETH_CLK"       unused   input  active-high 
	line  45:   "PWM1_OUT"       unused   input  active-high 
	line  46: "HDMI_HPD_N"        "hpd"   input   active-low [used]
	line  47: "STATUS_LED"       "led0"  output  active-high [used]
	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 
Вот почему мы могли раньше выбрать линию 16 - одну из немногих (16) свободных линий, не занятых в работе других подсистем:

Код: Выделить всё

root@raspberrypi:~# gpioinfo gpiochip0 | grep ' "GPIO' | grep -v _
	line   5:      "GPIO5"       unused   input  active-high 
	line   6:      "GPIO6"       unused   input  active-high 
	line  12:     "GPIO12"       unused   input  active-high 
	line  13:     "GPIO13"       unused   input  active-high 
	line  16:     "GPIO16"       unused  output  active-high 
	line  17:     "GPIO17"       unused   input  active-high 
	line  18:     "GPIO18"       unused   input  active-high 
	line  19:     "GPIO19"       unused   input  active-high 
	line  20:     "GPIO20"       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   input  active-high 
	line  26:     "GPIO26"       unused   input  active-high 
	line  27:     "GPIO27"       unused   input  active-high 
Но, в общем, всё знакомое.

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: GPIO в Linux

Непрочитанное сообщение Olej » 26 авг 2022, 00:56

Olej писал(а):
25 авг 2022, 16:40
2. Новый интерфейс к GPIO - через символьные устройства в /dev
Теперь относительно нового интерфейса, появившегося с версии ядра 4.8.
Состоит в том, что в /dev создаются 1 или несколько устройств вида: /dev/gpio* + для них реализованы в ядре куча IOCTL (кодов), на все случаи жизни: диагностика, чтение, запись, pool/select и т.д.

Orange Pi / Armbian:

Код: Выделить всё

olej@orangepione:~$  inxi -MSxxx
System:    Host: orangepione Kernel: 5.15.48-sunxi armv7l bits: 32 compiler: N/A Console: tty 6 dm: LightDM 1.26.0 
           Distro: Armbian GNU/Linux 10 (buster) 
Machine:   Type: ARM Device System: Xunlong Orange Pi One details: Allwinner sun8i Family rev: N/A serial: 02c000815fd5e717 

Код: Выделить всё

olej@orangepione:~$ ls -l /dev/gpio*
crw------- 1 root root 254, 0 авг 25 17:17 /dev/gpiochip0
crw------- 1 root root 254, 1 авг 25 17:17 /dev/gpiochip1
Rasberry Pi / Raspbian:

Код: Выделить всё

olej@raspberrypi:~ $ inxi -MSxxx
System:    Host: raspberrypi Kernel: 5.15.32-v7+ armv7l bits: 32 compiler: gcc v: 10.2.1 Console: tty 8 DM: LightDM 1.26.0 
           Distro: Raspbian GNU/Linux 11 (bullseye) 
Machine:   Type: ARM Device System: Raspberry Pi 2 Model B Rev 1.1 details: BCM2835 rev: a21041 serial: 00000000f57e2ca8 

Код: Выделить всё

olej@raspberrypi:~ $ ls -l /dev/gpio*
crw-rw---- 1 root gpio 254, 0 авг 25 14:14 /dev/gpiochip0
crw-rw---- 1 root gpio 245, 0 авг 25 14:14 /dev/gpiomem

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: GPIO в Linux

Непрочитанное сообщение Olej » 26 авг 2022, 01:00

Olej писал(а):
26 авг 2022, 00:56
Состоит в том, что в /dev создаются 1 или несколько устройств вида: /dev/gpio* + для них реализованы в ядре куча IOCTL (кодов), на все случаи жизни: диагностика, чтение, запись, pool/select и т.д.
Коды IOCTL и их использование более чем достаточно полно описаны в уже упоминавшейся статье: Control GPIO using the new Linux user space GPIO API
01/10/2020
На её основе я делаю своё 1-е приложение: info - чуть позже я его приложу.

Ответить

Вернуться в «Linux изнутри»

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и 6 гостей