]> kolegite.com Git - vmks.git/blob
faf31304fe15831f2213ca0b04f8b7399a45e378
[vmks.git] /
1 #include <Wire.h>
2
3 #define INT_SLAVE1_PIN 3
4 #define INT_SLAVE2_PIN 2
5
6 #define SLAVE1_ADDRESS 0x09
7 #define SLAVE2_ADDRESS 0x0A
8
9 size_t i2c_write(uint8_t address, void *data, size_t size);
10 size_t i2c_read(uint8_t address, void *data, size_t size);
11 void slave1_interrupt(void);
12 void slave2_interrupt(void);
13
14 volatile bool new_data1 = false;
15 volatile bool new_data2 = false;
16
17 void setup()
18 {
19 Wire.begin();
20 Serial.begin(9600);
21 pinMode(INT_SLAVE1_PIN, INPUT);
22 pinMode(INT_SLAVE2_PIN, INPUT);
23 attachInterrupt(digitalPinToInterrupt(INT_SLAVE1_PIN), slave1_interrupt, RISING);
24 attachInterrupt(digitalPinToInterrupt(INT_SLAVE2_PIN), slave2_interrupt, RISING);
25 }
26
27 void loop()
28 {
29 uint8_t dip_sw;
30
31 if (new_data1)
32 {
33 i2c_read(SLAVE1_ADDRESS, &dip_sw, sizeof(dip_sw));
34 Serial.print("From slave 1: ");
35 Serial.println(dip_sw);
36 new_data1 = false;
37 }
38 if (new_data2)
39 {
40 i2c_read(SLAVE2_ADDRESS, &dip_sw, sizeof(dip_sw));
41 Serial.print("From slave 2: ");
42 Serial.println(dip_sw);
43 new_data2 = false;
44 }
45 }
46
47 size_t i2c_write(uint8_t address, void *data, size_t size)
48 {
49 int error_code;
50 size_t bytes_written;
51
52 Wire.beginTransmission(address);
53 bytes_written = Wire.write((uint8_t *) data, size);
54 error_code = Wire.endTransmission();
55
56 return error_code ? 0: bytes_written;
57 }
58
59 size_t i2c_read(uint8_t address, void *data, size_t size)
60 {
61 size_t bytes_received = Wire.requestFrom(address, size);
62
63 if (bytes_received == size)
64 {
65 for (size_t i = 0; i < size; i++)
66 {
67 ((uint8_t *) data)[i] = Wire.read();
68 }
69 }
70
71 return bytes_received;
72 }
73
74 void slave1_interrupt(void)
75 {
76 new_data1 = true;
77 }
78
79 void slave2_interrupt(void)
80 {
81 new_data2 = true;
82 }