/
main.cpp
109 lines (91 loc) · 2.64 KB
/
main.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
104
105
106
107
108
109
#include <Arduino.h>
#include <Wire.h>
#define I2C_SLAVE_ADDRESS 0x10
#define RGB_ADDRESS 0x00
#define R_ADDRESS 0x01
#define G_ADDRESS 0x02
#define B_ADDRESS 0x03
void setup() {
Wire.begin();
Serial.begin(115200);
delay(500);
}
uint8_t writeByte(char deviceAddress, char bufferAddress, char data) {
Wire.beginTransmission(deviceAddress);
Wire.write(bufferAddress);
Wire.write(data);
return Wire.endTransmission();
}
uint8_t read3bytesState() {
Wire.beginTransmission(I2C_SLAVE_ADDRESS);
Wire.write(R_ADDRESS);
uint8_t result = Wire.endTransmission();
if (result != 0) return result;
Wire.requestFrom(I2C_SLAVE_ADDRESS, 3);
delay(10);
Serial.print("read:");
while (Wire.available()) {
Serial.print(" ");
Serial.print(Wire.read(), HEX);
}
Serial.println("");
return 0;
}
void read1byteState() {
Wire.beginTransmission(I2C_SLAVE_ADDRESS);
Wire.write(RGB_ADDRESS);
Wire.endTransmission();
Wire.requestFrom(I2C_SLAVE_ADDRESS, 1);
delay(10);
Serial.print("read: ");
while (Wire.available()) {
Serial.print(Wire.read(), BIN);
}
Serial.println("");
}
void writeAndReadResults(char deviceAddress, char bufferAddress, char data) {
if (writeByte(deviceAddress, bufferAddress, data) != 0) {
Serial.println("Failed to write");
} else {
read3bytesState();
read1byteState();
}
}
void loop() {
Serial.println("turn R on");
writeAndReadResults(I2C_SLAVE_ADDRESS, R_ADDRESS, 1);
delay(1000);
Serial.println("turn G on");
writeAndReadResults(I2C_SLAVE_ADDRESS, G_ADDRESS, 1);
delay(1000);
Serial.println("turn B on");
writeAndReadResults(I2C_SLAVE_ADDRESS, B_ADDRESS, 1);
delay(1000);
Serial.println("turn R off");
writeAndReadResults(I2C_SLAVE_ADDRESS, R_ADDRESS, 0);
delay(1000);
Serial.println("turn G off");
writeAndReadResults(I2C_SLAVE_ADDRESS, G_ADDRESS, 0);
delay(1000);
Serial.println("turn B off");
writeAndReadResults(I2C_SLAVE_ADDRESS, B_ADDRESS, 0);
delay(1000);
Serial.println("R:off, G:off, B:on");
writeAndReadResults(I2C_SLAVE_ADDRESS, RGB_ADDRESS, 0b001);
delay(1000);
Serial.println("R:off, G:on, B:on");
writeAndReadResults(I2C_SLAVE_ADDRESS, RGB_ADDRESS, 0b011);
delay(1000);
Serial.println("R:on, G:on, B:on");
writeAndReadResults(I2C_SLAVE_ADDRESS, RGB_ADDRESS, 0b111);
delay(1000);
Serial.println("R:on, G:on, B:off");
writeAndReadResults(I2C_SLAVE_ADDRESS, RGB_ADDRESS, 0b110);
delay(1000);
Serial.println("R:on, G:off, B:off");
writeAndReadResults(I2C_SLAVE_ADDRESS, RGB_ADDRESS, 0b100);
delay(1000);
Serial.println("R:off, G:off, B:off");
writeAndReadResults(I2C_SLAVE_ADDRESS, RGB_ADDRESS, 0);
delay(1000);
}