-
Notifications
You must be signed in to change notification settings - Fork 3
/
gpio.c
98 lines (82 loc) · 1.66 KB
/
gpio.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
#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "cube.h"
#include "gpio.h"
static volatile uint32_t *gpio_region = MAP_FAILED;
unsigned pi_model, pi_rev;
void
gpio_set_mode(unsigned gpio, unsigned mode)
{
int reg, shift;
reg = gpio/10;
shift = (gpio % 10) * 3;
gpio_region[reg] = (gpio_region[reg] & ~(7 << shift)) | (mode << shift);
}
#if 0
inline void
gpio_write(unsigned gpio, unsigned level)
{
if (level == 0)
*(gpio_region + GPCLR0 + PI_BANK(gpio)) = PI_BIT(gpio);
else
*(gpio_region + GPSET0 + PI_BANK(gpio)) = PI_BIT(gpio);
}
inline void
gpio_toggle_high(unsigned gpio)
{
*(gpio_region + GPSET0 + PI_BANK(gpio)) = PI_BIT(gpio);
*(gpio_region + GPCLR0 + PI_BANK(gpio)) = PI_BIT(gpio);
}
#else
void
gpio_write(unsigned gpio, unsigned level)
{
if (level == 0)
*(gpio_region + GPCLR0) = PI_BIT(gpio);
else
*(gpio_region + GPSET0) = PI_BIT(gpio);
}
void
gpio_toggle_high(unsigned gpio)
{
*(gpio_region + GPSET0) = PI_BIT(gpio);
*(gpio_region + GPCLR0) = PI_BIT(gpio);
}
#endif
void
gpio_clear_bank0(unsigned bits)
{
*(gpio_region + GPCLR0) = bits;
}
// Only works for pins in bank 0
void
gpio_set_bank0(unsigned bits)
{
*(gpio_region + GPSET0) = bits;
}
int
gpio_init(void)
{
int fd;
fd = open("/dev/gpiomem", O_RDWR | O_SYNC) ;
if (fd < 0)
{
fprintf(stderr, "failed to open /dev/gpiomem\n");
return -1;
}
gpio_region = (uint32_t *)mmap(NULL, 0xB4,
PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
if (gpio_region == MAP_FAILED)
{
fprintf(stderr, "Bad, mmap failed\n");
return -1;
}
return 0;
}