2 * Author: Thomas Ingleby <thomas.c.ingleby@intel.com>
3 * Copyright (c) 2014 Intel Corporation.
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, sublicense, and/or sell copies of the Software, and to
10 * permit persons to whom the Software is furnished to do so, subject to
11 * the following conditions:
13 * The above copyright notice and this permission notice shall be
14 * included in all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 gpio_get_valfp(gpio_t *gpio)
40 sprintf(bu, "/sys/class/gpio/gpio%d/value", gpio->pin);
42 if((gpio->value_fp = fopen(bu, "r+b")) == NULL) {
49 gpio_init(gpio_t *gpio, int pin)
53 if((export_f = fopen("/sys/class/gpio/export", "w")) == NULL) {
54 fprintf(stderr, "Failed to open export for writing!\n");
56 fprintf(export_f, "%d", pin);
70 gpio_mode(gpio_t *gpio, gpio_mode_t mode)
76 gpio_dir(gpio_t *gpio, gpio_dir_t dir)
78 if(gpio->value_fp != NULL) {
79 gpio->value_fp = NULL;
82 snprintf(filepath, 64, "/sys/class/gpio/gpio%d/direction", gpio->pin);
85 if((direction = fopen(filepath, "w")) == NULL) {
86 fprintf(stderr, "Failed to open direction for writing!\n");
88 fprintf(direction, dir);
90 gpio->value_fp = NULL;
95 gpio_read(gpio_t *gpio)
97 if(gpio->value_fp == NULL) {
100 fseek(gpio->value_fp, SEEK_SET, 0);
102 fread(buffer, 2, 1, gpio->value_fp);
103 fseek(gpio->value_fp, SEEK_SET, 0);
108 gpio_write(gpio_t *gpio, int value)
110 if(gpio->value_fp == NULL) {
111 gpio_get_valfp(gpio);
113 fseek(gpio->value_fp, SEEK_SET, 0);
114 fprintf(gpio->value_fp, "%d", value);
115 fseek(gpio->value_fp, SEEK_SET, 0);
120 gpio_close(gpio_t *gpio)
124 if((unexport_f = fopen("/sys/class/gpio/unexport", "w")) == NULL) {
125 fprintf(stderr, "Failed to open unexport for writing!\n");
127 fprintf(unexport_f, "%d", gpio->pin);