# Manage the GPIO lines in Python3 and C with libgpiod 

<abstract>
Since linux 4.8 the GPIO sysfs interface is deprecated. User space should use the character 
device instead. libgpiod encapsulates the ioctl calls and data structures behind a straightforward API.
</abstract>

## Manage the GPIO using Python 3 language

On Debian distribution install the Python3 libgpiod libraries by typing:

	sudo apt update
	sudo apt install python3-libgpiod
	
### Output example - A blinking led

	# GPIO used PA17
	
	import gpiod
	import time
	
	chip=gpiod.Chip('gpiochip0')
	line = gpiod.find_line("PA17")
	lines = chip.get_lines([line.offset()])
	lines.request(consumer='foobar', type=gpiod.LINE_REQ_DIR_OUT, default_vals=[0])
	
	while True:
	    lines.set_values([1])
	    time.sleep(1)
	    lines.set_values([0])
	    time.sleep(1)

### How fast is it ?

With this loop is possible to generate a 42kHz square signal on a GPIO line using a [Roadrunner SOM](/roadrunner) @ 500mHz

	while True:
		lines.set_values([1])
		lines.set_values([0])


### Input example - Reading a GPIO line

	# GPIO used PD30
	
	import gpiod
	import time
	
	chip = gpiod.Chip('gpiochip0')
	line = gpiod.find_line("PD30")
	lines = chip.get_lines([line.offset()])
	lines.request(consumer='foobar', type=gpiod.LINE_REQ_DIR_IN)
	
	while True:
	    print(lines.get_values())
	    time.sleep(1)
	    print(lines.get_values())
	    time.sleep(1)

## Where to find the Python3 gpiod API documentation

Lauch the python3 interpreter

	python3
	
then type:

	>>> import gpiod
	>>> help(gpiod)


## Manage the GPIO using the C language

On Debian distribution install the libgpiod libraries and build essential tools by typing:

	sudo apt update
	sudo apt install libgpiod-dev build-essential

Install git

	sudo apt git
	
Then clone where you can find some lite examples (https://github.com/starnight/libgpiod-example):

	git clone https://github.com/starnight/libgpiod-example


### How fast is it ?

With this loop is possible to generate a 300kHz square signal on a GPIO line using a [Roadrunner SOM](/roadrunner) @ 500mHz

	val = 0;
	for (i = 10000; i > 0; i--) {
		ret = gpiod_line_set_value(line, val);
		val = !val;
	}

	
## Links

* @article='gpiod'
* [Code examples in Python](https://github.com/brgl/libgpiod/tree/master/bindings/python/examples)
* [libgpiod public API](https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/tree/include/gpiod.h)
* [libgpiod documentation](https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/tree/README)
* [New GPIO interface for linux user space](https://ostconf.com/system/attachments/files/000/001/532/original/Linux_Piter_2018_-_New_GPIO_interface_for_linux_userspace.pdf?1541021776)
* [libgpiod-example](https://github.com/starnight/libgpiod-example)
* [libgpiod introduction video](https://www.youtube.com/watch?v=76j3TIqTPTI)

@include='adv_main'

