forked from jheising/node.pcduino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwiring_digital.c
executable file
·149 lines (131 loc) · 3.13 KB
/
wiring_digital.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include "Arduino.h"
#include "wiring_private.h"
static int write_to_file(int fd, char *str, int len)
{
int ret = -1;
lseek(fd, 0, SEEK_SET);
ret = write(fd, str, len);
if ( ret <= 0 )
{
fprintf(stderr, "write %d failed\n", fd);
return -1;
}
return ret;
}
void hw_pinMode(uint8_t pin, uint8_t mode)
{
int fd;
char buf[4];
int ret = -1;
if ( (pin >= 0 && pin <= MAX_GPIO_NUM) && (mode <= MAX_GPIO_MODE_NUM) )
{
memset((void *)buf, 0, sizeof(buf));
sprintf(buf, "%d", mode);
ret = write_to_file(gpio_mode_fd[pin], buf, sizeof(buf));
if ( ret <= 0 )
{
fprintf(stderr, "write gpio %d mode failed\n", pin);
exit(-1);
}
}
else
{
fprintf(stderr, "%s ERROR: invalid pin or mode, pin=%d, mode=%d\n",
__FUNCTION__, pin, mode);
exit(-1);
}
}
void pinMode(uint8_t pin, uint8_t mode)
{
switch (pin)
{
case 3:
case 9:
case 10:
case 11:
{
int ret = -1;
int fd = -1;
unsigned long val = pin;
fd = open("/dev/pwmtimer", O_RDONLY);
if ( fd < 0 )
pabort("open pwm device fail");
ret = ioctl(fd, 0x102, &val); //PWMTMR_STOP
if (ret < 0)
pabort("can't set PWMTMR_STOP");
if(fd)
close(fd);
}
break;
default:
break;
}
switch (mode)
{
case INPUT:
case OUTPUT:
hw_pinMode(pin, mode);
break;
case INPUT_PULLUP:
hw_pinMode(pin, 8);
break;
default:
break;
}
}
void digitalWrite(uint8_t pin, uint8_t value)
{
char buf[4];
int ret = -1;
if ( (pin >= 0 && pin <= MAX_GPIO_NUM) && (value == HIGH || value == LOW) )
{
memset((void *)buf, 0, sizeof(buf));
sprintf(buf, "%d", value);
ret = write_to_file(gpio_pin_fd[pin], buf, sizeof(buf));
if ( ret <= 0 )
{
fprintf(stderr, "write gpio %d failed\n", pin);
exit(-1);
}
}
else
{
fprintf(stderr, "%s ERROR: invalid pin or mode, pin=%d, value=%d\n",
__FUNCTION__, pin, value);
exit(-1);
}
}
int digitalRead(uint8_t pin)
{
char path[128];
char buf[4];
int ret = -1;
int fd = -1;
if ( pin >= 0 && pin <= MAX_GPIO_NUM )
{
memset((void *)buf, 0, sizeof(buf));
lseek(gpio_pin_fd[pin], 0, SEEK_SET);
ret = read(gpio_pin_fd[pin], buf, sizeof(buf));
if ( ret <= 0 )
{
fprintf(stderr, "read gpio %d failed\n", pin);
exit(-1);
}
ret = buf[0] - '0';
switch( ret )
{
case LOW:
case HIGH:
break;
default:
ret = -1;
break;
}
}
else
{
fprintf(stderr, "%s ERROR: invalid pin, pin=%d\n", __FUNCTION__, pin);
exit(-1);
}
return ret;
}