-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspi.h
172 lines (68 loc) · 2.14 KB
/
spi.h
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#ifndef __SPI__
#define __SPI__
#include "header.h"
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
static const char *DEVICE = "/dev/spidev0.0";
static uint8_t MODE = 0;
static uint8_t BITS = 8;
static uint32_t CLOCK = 1000000;
static uint16_t DELAY = 5;
static int prepare(int fd) {
if (ioctl(fd, SPI_IOC_WR_MODE, &MODE) == -1) {
perror("Can't set MODE");
return -1;
}
if (ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &BITS) == -1) {
perror("Can't set number of BITS");
return -1;
}
if (ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &CLOCK) == -1) {
perror("Can't set write CLOCK");
return -1;
}
if (ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &CLOCK) == -1) {
perror("Can't set read CLOCK");
return -1;
}
return 0;
}
uint8_t control_bits_differential(uint8_t channel) {
return (channel & 7) << 4;
}
uint8_t control_bits(uint8_t channel) {
return 0x8 | control_bits_differential(channel);
}
int readadc(int fd, uint8_t channel) {
uint8_t tx[] = {1, control_bits(channel), 0};
uint8_t rx[3];
struct spi_ioc_transfer tr = {
.tx_buf = (unsigned long)tx,
.rx_buf = (unsigned long)rx,
.len = ARRAY_SIZE(tx),
.delay_usecs = DELAY,
.speed_hz = CLOCK,
.bits_per_word = BITS,
};
if (ioctl(fd, SPI_IOC_MESSAGE(1), &tr) == 1) {
perror("IO Error");
abort();
}
return ((rx[1] << 8) & 0x300) | (rx[2] & 0xFF);
}
int SPI_init()
{
int fd = open(DEVICE, O_RDWR);
if (fd <= 0) {
perror("Device open error");
return -1;
}
if (prepare(fd) == -1) {
perror("Device prepare error");
return -1;
}
return fd;
}
//printf("value: %d\n", readadc(fd, 0)); //0번 채널의 값을 불러들임 (B의 값)
//printf("value: %d\n", readadc(fd, 1)); //1번 채널의 값을 불러들임 (X의 값)
//printf("value: %d\n", readadc(fd, 2)); //2번 채널의 값을 불러들임 (Y의 값)
#endif