RobotCore 1.0
WPILib port to raspberry Pi
Loading...
Searching...
No Matches
I2CInterface.java
1package robotCore;
2
3import java.io.IOException;
4
5import com.pi4j.context.Context;
6import com.pi4j.io.i2c.I2C;
7import com.pi4j.io.i2c.I2CConfig;
8
16public class I2CInterface {
17 private static final int BUS = 1;
18
19 private final I2C m_device;
20
21 I2CInterface(int addr) {
22 Context pi4j = Pi4JContext.get();
23 String id = String.format("i2c-%d-0x%02x", BUS, addr);
24
25 I2C device = null;
26 try {
27 // Pi4J requires unique IDs, so reuse the device if it was already created.
28 if (pi4j.registry().exists(id)) {
29 device = pi4j.registry().get(id, I2C.class);
30 } else {
31 I2CConfig config = I2C.newConfigBuilder(pi4j)
32 .id(id)
33 .bus(BUS)
34 .device(addr)
35 .build();
36 device = pi4j.create(config);
37 }
38 } catch (RuntimeException e) {
39 e.printStackTrace();
40 }
41 m_device = device;
42 }
43
52 public int read(byte[] buffer, int offset, int length) throws IOException {
53 checkDevice();
54 try {
55 int count = m_device.read(buffer, offset, length);
56 if (count < 0) {
57 throw new IOException("I2C read failed: " + count);
58 }
59 return count;
60 } catch (RuntimeException e) {
61 throw new IOException("I2C read failed", e);
62 }
63 }
64
70 public void write(byte[] data) throws IOException {
71 checkDevice();
72 try {
73 int count = m_device.write(data);
74 if (count < 0) {
75 throw new IOException("I2C write failed: " + count);
76 }
77 } catch (RuntimeException e) {
78 throw new IOException("I2C write failed", e);
79 }
80 }
81
92 public int writeRead(byte[] writeData, byte[] buffer, int offset, int length) throws IOException {
93 checkDevice();
94 try {
95 int count = m_device.readRegister(writeData, buffer, offset, length);
96 if (count < 0) {
97 throw new IOException("I2C write/read failed: " + count);
98 }
99 return count;
100 } catch (RuntimeException e) {
101 throw new IOException("I2C write/read failed", e);
102 }
103 }
104
105 private void checkDevice() throws IOException {
106 if (m_device == null) {
107 throw new IOException("I2C device was not opened; see the earlier stack trace");
108 }
109 }
110}
void write(byte[] data)
int writeRead(byte[] writeData, byte[] buffer, int offset, int length)
int read(byte[] buffer, int offset, int length)