-
Notifications
You must be signed in to change notification settings - Fork 0
/
iopi.go
331 lines (278 loc) · 7.41 KB
/
iopi.go
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package iopi
import (
"fmt"
"io"
"os"
"sync"
"golang.org/x/sys/unix"
)
type Port uint8
type Mode byte
type Polarity byte
type State uint8
const (
// As defined in the C implementation
IODIRA = 0x00
IODIRB = 0x01
IPOLA = 0x02
IPOLB = 0x03
IOCON = 0x0A
GPPUA = 0x0C
GPPUB = 0x0D
GPIOA = 0x12
GPIOB = 0x13
// As defined in /usr/include/linux/i2c-dev.h
I2C_SLAVE = 0x0703
)
const (
// A single bus is split into two ports: pins 1-8 and 9-16
PortA Port = iota
PortB
)
const (
PolarityNormal Polarity = 0x00
PolarityInverted = 0xFF
)
const (
Output Mode = 0x00
Input = 0xFF
)
const (
Low State = 0x00
High = 0xFF
)
const (
PullupDisabled Mode = 0x00
PullupEnabled = 0xFF
)
type Device struct {
Address byte // I2C device address
Path string // e.g. /dev/i2c-1
bus ReadWriteCloserSpecial
mutex *sync.Mutex // enables sharing a file descriptor with other devices
}
type ReadWriteCloserSpecial interface {
io.ReadWriteCloser
Fd() uintptr
Name() string
}
// Create a new device object.
// `bus` can be a string path to a file, or a pointer to a File so multiple
// devices can share the same file descriptor. (e.g. two i2c addresses on same i2c bus)
func NewDevice(file ReadWriteCloserSpecial, addr byte, mutex *sync.Mutex) *Device {
dev := Device{
Address: addr,
Path: file.Name(),
bus: file,
mutex: mutex,
}
return &dev
}
// Initialise device. This must be called once per device. You are expected
// to call `.Close()` to clean up resources when you're done.
func (dev *Device) Init() error {
file, err := os.OpenFile(dev.Path, os.O_RDWR, os.ModeCharDevice)
if err != nil {
return fmt.Errorf("failed to open i2c device at '%s': %s", dev.Path, err)
}
dev.bus = file
// Initialise the I2C bus
err = unix.IoctlSetInt(int(dev.bus.Fd()), I2C_SLAVE, int(dev.Address))
if err != nil {
return fmt.Errorf("failed to write to i2c device at address '%02b': %s",
dev.Address, err)
}
dev.driverInit()
return nil
}
func (dev *Device) driverInit() {
// Board initialisation
// TODO: Handle errors
dev.WriteByteData(IOCON, 0x22) // MCP23017 specific
dev.SetPortMode(PortA, Input)
dev.SetPortMode(PortB, Input)
dev.SetPortPullup(PortA, PullupDisabled)
dev.SetPortPullup(PortB, PullupDisabled)
dev.SetPortPolarity(PortA, PolarityNormal)
dev.SetPortPolarity(PortB, PolarityNormal)
}
// Clean up resources.
func (dev *Device) Close() error {
return dev.bus.Close()
}
// Read raw data from a register.
// This is a low-level interface. You probably want to use the higher level
// functions to manipulate the board.
func (dev *Device) ReadByteData(reg byte) (byte, error) {
buf := make([]byte, 1)
buf[0] = reg
dev.mutex.Lock()
defer dev.mutex.Unlock()
n, err := dev.bus.Write(buf)
if err != nil {
return 0x0, fmt.Errorf("failed to write to slave before read (wrote %v bytes): %s\n", n, err)
}
n, err = dev.bus.Read(buf)
if err != nil {
return 0x0, fmt.Errorf("failed to read from slave: %s\n", err)
}
//fmt.Printf("read 0x%X (%v bytes) <- 0x%X\n", buf, n, reg)
return buf[0], nil
}
// Write raw data to a register.
// This is a low-level interface. You probably want to use the higher level
// functions to manipulate the board.
func (dev *Device) WriteByteData(reg byte, value byte) error {
buf := []byte{reg, value}
//fmt.Printf("write 0x%08b to addr 0x%08b\n", value, reg)
dev.mutex.Lock()
defer dev.mutex.Unlock()
n, err := dev.bus.Write(buf)
if err != nil {
return fmt.Errorf("failed to write to slave (wrote %v bytes): %s\n", n, err)
}
return nil
}
// Collectively enable 100K pull-up resistors on all pins on a port.
func (dev *Device) SetPortPullup(port Port, state Mode) error {
switch port {
case PortA:
return dev.WriteByteData(GPPUA, byte(state))
case PortB:
return dev.WriteByteData(GPPUB, byte(state))
default:
return fmt.Errorf("invalid port: %v\n", port)
}
}
// Enable 100K pull-up resistor on a single pin
func (dev *Device) SetPinPullup(pin uint8, enabledState Mode) error {
pin, port := GetPinPort(pin)
var reg byte
if port == PortA {
reg = GPPUA
} else {
reg = GPPUB
}
state, err := dev.ReadByteData(reg)
if err != nil {
return fmt.Errorf("failed to set pin pullup: %s", err)
}
state = SetBit(state, pin, int(enabledState))
return dev.SetPortPullup(port, Mode(state))
}
// Collectively set the polarity of all pins on a port.
// Also known as normal and inverted logic.
func (dev *Device) SetPortPolarity(port Port, pol Polarity) error {
switch port {
case PortA:
return dev.WriteByteData(IPOLA, byte(pol))
case PortB:
return dev.WriteByteData(IPOLB, byte(pol))
default:
return fmt.Errorf("invalid port: %v\n", port)
}
}
// Set polarity of a single pin
func (dev *Device) SetPinPolarity(pin uint8, pol Polarity) error {
pin, port := GetPinPort(pin)
var reg byte
if port == PortA {
reg = IPOLA
} else {
reg = IPOLB
}
state, err := dev.ReadByteData(reg)
if err != nil {
return fmt.Errorf("failed to set pin polarity: %s", err)
}
return dev.WriteByteData(reg, SetBit(state, pin, int(pol)))
}
// Collectively set all pins on a port to specific mode.
func (dev *Device) SetPortMode(port Port, mode Mode) error {
switch port {
case PortA:
return dev.WriteByteData(IODIRA, byte(mode))
case PortB:
return dev.WriteByteData(IODIRB, byte(mode))
default:
return fmt.Errorf("invalid port: %v\n", port)
}
}
// Set direction of a single pin
func (dev *Device) SetPinMode(pin uint8, mode Mode) error {
pin, port := GetPinPort(pin)
var reg byte
if port == PortA {
reg = IODIRA
} else {
reg = IODIRB
}
state, err := dev.ReadByteData(reg)
if err != nil {
return fmt.Errorf("failed to set pin direction: %s", err)
}
return dev.WriteByteData(reg, SetBit(state, pin, int(mode)))
}
// Collectively set all pins on the port to a specific state.
func (dev *Device) WritePort(port Port, state byte) error {
switch port {
case PortA:
return dev.WriteByteData(GPIOA, state)
case PortB:
return dev.WriteByteData(GPIOB, state)
default:
return fmt.Errorf("invalid port: %v\n", port)
}
}
// Return a byte describing the state of all pins on the selected port.
// Returns a zero byte if error != nil.
func (dev *Device) ReadPort(port Port) (byte, error) {
switch port {
case PortA:
return dev.ReadByteData(GPIOA)
case PortB:
return dev.ReadByteData(GPIOB)
default:
return 0x00, fmt.Errorf("invalid port: %v\n", port)
}
}
// Set single pin to a specific state.
func (dev *Device) WritePin(pin uint8, state State) error {
pin, port := GetPinPort(pin)
portState, err := dev.ReadPort(port)
if err != nil {
return fmt.Errorf("failed to write to pin %v: %s\n", pin, err)
}
newState := SetBit(portState, pin, int(state))
return dev.WritePort(port, newState)
}
// Translate a pin number 1-16 into 0-index pin on a specific port.
func GetPinPort(pin uint8) (uint8, Port) {
if pin > 8 {
return pin - 1 - 8, PortB
} else {
return pin - 1, PortA
}
}
// Return the state of a single pin.
func (dev *Device) ReadPin(pin uint8) (State, error) {
pin, port := GetPinPort(pin)
portState, err := dev.ReadPort(port)
return State(GetBit(portState, pin)), err
}
// Set a single bit in a byte. All values except 0 is considered 1.
func SetBit(byt byte, bit uint8, value int) byte {
if value == 0 {
return (byt &^ (1 << bit)) // clear bit
} else {
return (byt | (1 << bit)) // set bit
}
}
// Get a single bit in a byte.
func GetBit(byt byte, bit uint8) uint8 {
if byt&(1<<bit) > 0 {
return 1
} else {
return 0
}
}