Linux 에서 GPIO 컨트롤하기

2018. 1. 26. 15:03IT

반응형

이번 보드는.... 485 usb 포트가 FTDI 칩을 통해 ARTIK cpu에 연결되어있다. 

(4개의 포트가 뽑혀있고,.. 목적은 4개의 센서를 사용하려는 목적)


이 usb 포트를 사용하려면 HIGH/LOW 로 조절해가며 데이터를 쏴야하는데.... 


이를 사용하려면 어느 GPIO 에 맵핑되어있는지 알아야 HIGH LOW로 컨트롤 할 수 있다...


USB랑 485랑 호환해주는 어떤 커넥터가 있는데... 한쪽은 485 Tx/Rx/GND등이 있는 연결부위가 있고 한쪽은 컴터에 연결하는 USB포트가 있다.


보드의 485 포트와 CPU의 USB포트사이에 데이터가 오고 가는 것을 확인해야하는것이다. ( 깨지지 않고..)


그러러면..양쪽의 Baud rate 등 다른 설정값도 모두 세팅을 잘 해줘야함.


그니까 !!!!



이런식으로 연결 되어있는거임. 


왼쪽이 아틱 보드인데, 보드쪽에서 할 일은. 

1. minicom 을 install 하고, minicom으로 485 port 열어놓고...

2. ssh 로 보드에 (ip로) 접속해서 여기서는 GPIO high/low 컨트롤 하기.


오른쪽 CPU에서는 

1. 해당 usb 포트 com 포트를 테라텀으로 띄운다.


***** 보드쪽 

1. 이 보드에는 페도라가 올라가있어서, 페도라로 install 해줘야한다. dnf인가... dnf install minicom....

그리고... minicom -s 로 configuration setting을 해준다. 

(활성화된 usb포트를 볼 수 있으면 좋은데 걍 4개다 되어있는듯...;)

그리고 minicom을 구동시켜놓고...


2. ssh 로 보드에 따로 접속을 한다. 여기서는 485 usb 포트에 해당하는 GPIO number를 echo로 생성 및 control 한다.


예를 들어.... GPIO number가 64번이라면... 


echo 64 > /sys/class/gpio/export


로 해당 GPIO 폴더를 생성한다.

그러면 gpio64 디렉토리가 생긴다.

gpio 디렉토리에는 direction , value 라는 게 있는데, 

direction은 HIGH / LOW를 설정해줄 수 있다. (out == low)


ex _) echo out > /sys/class/gpio/gpio64/direction

       echo "high" > /sys/class/gpio/gpio64/direction


이런식으로...


그리고 HIGH 이때 상태는 데이터를 전송할 수 있는 상태인데, 이때 value를 0 (LOW), 1 (HIGH)로 왔다갔다 해본다,

실제 HIGH LOW로 바뀌는 지 알아보려면, 멀티미터로 (젼류측정기) 찍어봐야한다. (이런건 핀맵보고 해야함)


ex _) echo 1 > /sys/class/gpio/gpio64/value

       echo 0 > /sys/class/gpio/gpio64/value


요런식으로..... ㅎㅎ


그리고 테스트가 다 끝나고 gpio를 안쓰고싶다면


echo 64 > /sys/class/gpio/unexport


를 입력하면 된다. 


=================================GPIO Sysfs Interface for Userspace ===========================

GPIO Sysfs Interface for Userspace
==================================

Platforms which use the "gpiolib" implementors framework may choose to
configure a sysfs user interface to GPIOs. This is different from the
debugfs interface, since it provides control over GPIO direction and
value instead of just showing a gpio state summary. Plus, it could be
present on production systems without debugging support.

Given appropriate hardware documentation for the system, userspace could
know for example that GPIO #23 controls the write protect line used to
protect boot loader segments in flash memory. System upgrade procedures
may need to temporarily remove that protection, first importing a GPIO,
then changing its output state, then updating the code before re-enabling
the write protection. In normal use, GPIO #23 would never be touched,
and the kernel would have no need to know about it.

Again depending on appropriate hardware documentation, on some systems
userspace GPIO can be used to determine system configuration data that
standard kernels won't know about. And for some tasks, simple userspace
GPIO drivers could be all that the system really needs.

DO NOT ABUSE SYSFS TO CONTROL HARDWARE THAT HAS PROPER KERNEL DRIVERS.
PLEASE READ THE DOCUMENT NAMED "drivers-on-gpio.txt" IN THIS DOCUMENTATION
DIRECTORY TO AVOID REINVENTING KERNEL WHEELS IN USERSPACE. I MEAN IT.
REALLY.

Paths in Sysfs
--------------
There are three kinds of entries in /sys/class/gpio:

   -	Control interfaces used to get userspace control over GPIOs;

   -	GPIOs themselves; and

   -	GPIO controllers ("gpio_chip" instances).

That's in addition to standard files including the "device" symlink.

The control interfaces are write-only:

    /sys/class/gpio/

    	"export" ... Userspace may ask the kernel to export control of
		a GPIO to userspace by writing its number to this file.

		Example:  "echo 19 > export" will create a "gpio19" node
		for GPIO #19, if that's not requested by kernel code.

    	"unexport" ... Reverses the effect of exporting to userspace.

		Example:  "echo 19 > unexport" will remove a "gpio19"
		node exported using the "export" file.

GPIO signals have paths like /sys/class/gpio/gpio42/ (for GPIO #42)
and have the following read/write attributes:

    /sys/class/gpio/gpioN/

	"direction" ... reads as either "in" or "out". This value may
		normally be written. Writing as "out" defaults to
		initializing the value as low. To ensure glitch free
		operation, values "low" and "high" may be written to
		configure the GPIO as an output with that initial value.

		Note that this attribute *will not exist* if the kernel
		doesn't support changing the direction of a GPIO, or
		it was exported by kernel code that didn't explicitly
		allow userspace to reconfigure this GPIO's direction.

	"value" ... reads as either 0 (low) or 1 (high). If the GPIO
		is configured as an output, this value may be written;
		any nonzero value is treated as high.

		If the pin can be configured as interrupt-generating interrupt
		and if it has been configured to generate interrupts (see the
		description of "edge"), you can poll(2) on that file and
		poll(2) will return whenever the interrupt was triggered. If
		you use poll(2), set the events POLLPRI and POLLERR. If you
		use select(2), set the file descriptor in exceptfds. After
		poll(2) returns, either lseek(2) to the beginning of the sysfs
		file and read the new value or close the file and re-open it
		to read the value.

	"edge" ... reads as either "none", "rising", "falling", or
		"both". Write these strings to select the signal edge(s)
		that will make poll(2) on the "value" file return.

		This file exists only if the pin can be configured as an
		interrupt generating input pin.

	"active_low" ... reads as either 0 (false) or 1 (true). Write
		any nonzero value to invert the value attribute both
		for reading and writing. Existing and subsequent
		poll(2) support configuration via the edge attribute
		for "rising" and "falling" edges will follow this
		setting.

GPIO controllers have paths like /sys/class/gpio/gpiochip42/ (for the
controller implementing GPIOs starting at #42) and have the following
read-only attributes:

    /sys/class/gpio/gpiochipN/

    	"base" ... same as N, the first GPIO managed by this chip

    	"label" ... provided for diagnostics (not always unique)

        "ngpio" ... how many GPIOs this manages (N to N + ngpio - 1)

Board documentation should in most cases cover what GPIOs are used for
what purposes. However, those numbers are not always stable; GPIOs on
a daughtercard might be different depending on the base board being used,
or other cards in the stack. In such cases, you may need to use the
gpiochip nodes (possibly in conjunction with schematics) to determine
the correct GPIO number to use for a given signal.


Exporting from Kernel code
--------------------------
Kernel code can explicitly manage exports of GPIOs which have already been
requested using gpio_request():

	/* export the GPIO to userspace */
	int gpiod_export(struct gpio_desc *desc, bool direction_may_change);

	/* reverse gpio_export() */
	void gpiod_unexport(struct gpio_desc *desc);

	/* create a sysfs link to an exported GPIO node */
	int gpiod_export_link(struct device *dev, const char *name,
		      struct gpio_desc *desc);

After a kernel driver requests a GPIO, it may only be made available in
the sysfs interface by gpiod_export(). The driver can control whether the
signal direction may change. This helps drivers prevent userspace code
from accidentally clobbering important system state.

This explicit exporting can help with debugging (by making some kinds
of experiments easier), or can provide an always-there interface that's
suitable for documenting as part of a board support package.

After the GPIO has been exported, gpiod_export_link() allows creating
symlinks from elsewhere in sysfs to the GPIO sysfs node. Drivers can
use this to provide the interface under their own device in sysfs with
a descriptive name.

========================================================================================



ls -alF 뭐 이런식으로 ...리스트를 보면....활성화되어있는거 ?? 볼수 있음....



이렇게 다 세팅이 되면 !!!!!! 미니콤 콘솔에서 입력하면 CPU 콘솔(테라텀)에 찍혀야하고, 반대로 테라텀에 입력하면 미니콤에 찍혀야한다. 


(High로 바꾸고 한번 해보고, Low로 바꾸고 텍스트 찍어보고...)


이게 확인 되면......... 완료 된것이다... 



+ 이 소스는 174번 gpio port를 연 후에 1초에 한번씩 값을 변경하면서 10회 반복하는 코드이다. 




참조 사이트 :


http://blog.naver.com/PostView.nhn?blogId=jjong_w&logNo=60178946778




728x90
반응형

'IT' 카테고리의 다른 글

리눅스 커널  (0) 2018.03.09
CPU temperature check on linux  (0) 2018.02.14
Fedora install  (0) 2018.01.26
crc16 bit .....  (0) 2018.01.04
Ubuntu install in HPE Proliant Server  (0) 2017.12.13