11/* Wire Slave Receiver
22by Wi6Labs
33
4- Demonstrates use of the Wire library, particullary with STM32F1xx boards where
5- we can't use slave Tx & Rx mode in same time.
4+ Demonstrates use of the Wire library.
65Receives/sends data as an I2C/TWI slave device.
76Refer to the "Wire Master Reader Writer" example for use with this.
87
98Created 27 June 2017
9+ Updated 14 August 2017
10+ - this example is now common to all STM32 boards
1011
1112This example code is in the public domain.
1213*/
1314
1415#include < Wire.h>
1516
16- #define SLAVE_MODE_RX 0
17- #define SLAVE_MODE_TX 1
18-
1917#define I2C_ADDR 2
2018
21- int w_r_mode = SLAVE_MODE_TX;
22- bool switch_mode = false ;
23-
2419void setup ()
2520{
2621 Wire.begin (I2C_ADDR); // join i2c bus with address #4
2722 Wire.onRequest (requestEvent); // register event
23+ Wire.onReceive (receiveEvent); // register event
2824 Serial.begin (9600 ); // start serial for output
2925}
3026
3127void loop ()
3228{
33- if (switch_mode == true ) {
34- switch_mode = false ;
35- Wire.end ();
36- Wire.begin (I2C_ADDR);
37- if (w_r_mode == SLAVE_MODE_TX) {
38- Wire.onRequest (requestEvent); // register event
39- } else {
40- Wire.onReceive (receiveEvent); // register event
41- }
42- }
29+ // empty loop
4330}
4431
4532// function that executes whenever data is received from master
@@ -48,23 +35,17 @@ void receiveEvent(int howMany)
4835{
4936 while (1 < Wire.available ()) // loop through all but the last
5037 {
51- char c = Wire.read (); // receive byte as a character
52- Serial.print (c); // print the character
38+ char c = Wire.read (); // receive byte as a character
39+ Serial.print (c); // print the character
5340 }
54- int x = Wire.read (); // receive byte as an integer
55- Serial.println (x); // print the integer
56-
57- switch_mode = true ;
58- w_r_mode = SLAVE_MODE_TX;
41+ int x = Wire.read (); // receive byte as an integer
42+ Serial.println (x); // print the integer
5943}
6044
6145// function that executes whenever data is requested by master
6246// this function is registered as an event, see setup()
6347void requestEvent ()
6448{
65- Wire.write (" hello " ); // respond with message of 6 bytes
66- // as expected by master
67-
68- switch_mode = true ;
69- w_r_mode = SLAVE_MODE_RX;
49+ Wire.write (" hello\n " ); // respond with message of 6 bytes
50+ // as expected by master
7051}
0 commit comments