Project

General

Profile

RE: Write UART2 RS-485 API ยป gpio.cpp

Joe Hung, 03/27/2012 01:50 AM

 
1
/*
2
 * gpio.cpp
3
 *
4
 *  Created on: Mar 6, 2012
5
 *      Author: joe
6
 */
7
#include <fcntl.h>
8
#include <termios.h>
9
#include <stdio.h>
10
#include <string.h>
11
#include <unistd.h>
12
#include <errno.h>
13
#include "gpio.h"
14

    
15
#define GPIO_DIR_IN	    0
16
#define GPIO_DIR_OUT	1
17

    
18
int gpio_export(unsigned gpio)
19
{
20
	int fd, len;
21
	char buf[11];
22

    
23
	fd = open("/sys/class/gpio/export", O_WRONLY);
24
	if (fd < 0) {
25
		perror("gpio/export");
26
		return fd;
27
	}
28

    
29
	len = snprintf(buf, sizeof(buf), "%d", gpio);
30
	write(fd, buf, len);
31
	close(fd);
32

    
33
	return 0;
34
}
35

    
36
int gpio_unexport(unsigned gpio)
37
{
38
	int fd, len;
39
	char buf[11];
40

    
41
	fd = open("/sys/class/gpio/unexport", O_WRONLY);
42
	if (fd < 0) {
43
		perror("gpio/export");
44
		return fd;
45
	}
46

    
47
	len = snprintf(buf, sizeof(buf), "%d", gpio);
48
	write(fd, buf, len);
49
	close(fd);
50
	return 0;
51
}
52

    
53
static int gpio_dir(unsigned gpio, unsigned dir)
54
{
55
	int fd, len;
56
	char buf[60];
57

    
58
	len = snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/direction", gpio);
59

    
60
	fd = open(buf, O_WRONLY);
61
	if (fd < 0) {
62
		perror("gpio/direction");
63
		return fd;
64
	}
65

    
66
	if (dir == GPIO_DIR_OUT)
67
		write(fd, "out", 4);
68
	else
69
		write(fd, "in", 3);
70

    
71
	close(fd);
72
	return 0;
73
}
74

    
75
int gpio_dir_out(unsigned gpio)
76
{
77
	return gpio_dir(gpio, GPIO_DIR_OUT);
78
}
79

    
80
int gpio_dir_in(unsigned gpio)
81
{
82
	return gpio_dir(gpio, GPIO_DIR_IN);
83
}
84

    
85
int gpio_set_value(unsigned gpio, unsigned value)
86
{
87
	int fd, len;
88
	char buf[60];
89

    
90
	len = snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/value", gpio);
91

    
92
	fd = open(buf, O_WRONLY);
93
	if (fd < 0) {
94
		perror("gpio/value");
95
		return fd;
96
	}
97

    
98
	if (value)
99
		write(fd, "1", 2);
100
	else
101
		write(fd, "0", 2);
102

    
103
	close(fd);
104
	return 0;
105
}
106

    
107
int gpio_get_value(unsigned gpio, unsigned *value)
108
{
109
	int fd, len;
110
	char buf[60];
111

    
112
	len = snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/value", gpio);
113

    
114
	fd = open(buf, O_RDONLY);
115
	if (fd < 0) {
116
		perror("gpio/value");
117
		return fd;
118
	}
119

    
120
	read(fd, value, 1);
121

    
122
	if (*value == '1')
123
		*value = 1;
124
	else
125
		*value = 0;
126

    
127
	close(fd);
128
	return 0;
129
}
    (1-1/1)
    Go to top
    Add picture from clipboard (Maximum size: 1 GB)