RobotCore
1.0
WPILib port to raspberry Pi
Toggle main menu visibility
Loading...
Searching...
No Matches
I2CInterface.java
1
package
robotCore;
2
3
import
java.io.IOException;
4
5
import
com.pi4j.context.Context;
6
import
com.pi4j.io.i2c.I2C;
7
import
com.pi4j.io.i2c.I2CConfig;
8
16
public
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
}
robotCore.I2CInterface.write
void write(byte[] data)
Definition
I2CInterface.java:70
robotCore.I2CInterface.writeRead
int writeRead(byte[] writeData, byte[] buffer, int offset, int length)
Definition
I2CInterface.java:92
robotCore.I2CInterface.read
int read(byte[] buffer, int offset, int length)
Definition
I2CInterface.java:52
robotCore
I2CInterface.java
Generated by
1.18.0