-
Notifications
You must be signed in to change notification settings - Fork 8
/
I2C.cpp
103 lines (77 loc) · 1.82 KB
/
I2C.cpp
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
#include "I2C.h"
I2C::I2C()
{
Wire.begin();
Wire.setClock(400000UL); // Set I2C frequency to 400kHz
}
void I2C::setAdress( uint8_t address ){
devAddress = address;
}
uint8_t I2C::write(uint8_t address, uint8_t data)
{
uint8_t response = write(address, &data, 1); // Returns 0 on success
return response;
}
uint8_t I2C::write(uint8_t address, uint8_t *data, uint8_t length)
{
// Begin communication on the I2C address
Wire.beginTransmission(devAddress);
// First write (select) the register to update
Wire.write(address);
// Next write the data
Wire.write(data, length);
// End communication, returns 0 on success
return Wire.endTransmission();
}
uint8_t I2C::read(uint8_t address){
uint8_t data;
read(address, &data, 1);
return data;
}
uint8_t I2C::read(uint8_t address, uint8_t *data, uint8_t nbytes)
{
uint32_t timeOutTimer;
uint8_t response;
// Begin communication on the I2C address
Wire.beginTransmission(devAddress);
// First write (select) the register to read from
Wire.write(address);
response = Wire.endTransmission();
if (response) {
return response;
}
// Read n bytes from the I2C
Wire.beginTransmission(devAddress);
Wire.requestFrom(devAddress, nbytes, true);
for (uint8_t i = 0; i < nbytes; i++)
{
if (Wire.available())
{
data[i] = Wire.read();
}
else
{
timeOutTimer = micros();
while (((micros() - timeOutTimer) < timeout) && !Wire.available());
if (Wire.available())
data[i] = Wire.read();
else {
return 5; // This error value is not already taken by endTransmission
}
}
}
return 0; // Success
}
uint8_t I2C::writeBit(uint8_t address, uint8_t pos, bool state)
{
uint8_t value;
value = read(address);
if (state)
{
value |= (1 << pos);
} else
{
value &= ~(1 << pos);
}
return write(address, value);
}