Raspberry Pi IoT In C - gpiod |
Written by Harry Fairhead | |||||
Monday, 30 December 2024 | |||||
Page 2 of 4
Raw GPIO Character Device In C - ioctlYou don’t need anything special to work with a character device. All you need is the standard ioctl system call and for this you simply need to add: #include <sys/ioctl.h> The call varies according to the device it is being used with. Its general form is: ioctl(fd, request, pstruct) where fd is a file descriptor that returns the device being used and request is an unsigned long that specifies the request or operation to be performed. The third parameter is usually a pointer to a struct or an area of memory. Some ioctl calls have additional parameters. The request number was never formalized and driver writers tended to invent their own but there was an impromptu move to apply an organization and many request numbers follow a regular pattern. The most recent scheme is 2 direction bits (00: none, 01: write, 10: read, 11: read/write), followed by 14 size bits giving the size of the argument, followed by an 8-bit type (collecting the ioctls in groups for a common purpose or a common driver), and an 8-bit serial number. A set of macros is provided so that the request number can be built up from its parts: _IOR(type,nr,size) _IOW(type,nr,size) _IOWR(type,nr,size) and _IO(type,nr) These are optional in that if you know the request number you can simply use it in the call to ioctl(). The GPIO character device works entirely in terms of the ioctl system call and not by reading or writing the files. What you need to know to use the driver directly are the request codes and the structures that are passed. These are all defined in the gpio.h header: #include <linux/gpio.h> Working with the GPIO chip and the GPIO lines follows the same standard steps:
Getting Chip InfoAs a first simple example, let’s get some information about the GPIO chip. If you look through the header file you will find: GPIO_GET_CHIPINFO_IOCTL which is the request constant. You will also find: struct gpiochip_info { char name[32]; char label[32]; __u32 lines; }; which is the struct that is used to hold information about the GPIO chip. With this information we can open the file and make the ioctl call: #include <stdio.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/gpio.h> int main(int argc, char **argv) { int fd; struct gpiochip_info info; fd = open("/dev/gpiochip0", O_RDONLY); int ret = ioctl(fd, GPIO_GET_CHIPINFO_IOCTL, &info); close(fd); printf("label: %s\n name: As with all good, easy-to-understand examples, error handling has been omitted. If you run this program you will see: label: pinctrl-bcm2835 name: gpiochip0 number of lines: 54 If you run this on a Pi 5 change gpiochip0 to gpiochip4. |
|||||
Last Updated ( Monday, 30 December 2024 ) |