

The number of bytes and also the slave address are specified in this function.

# include // Include the Wire library for I2C communication Use the following code to identify any slave device’s address present on the I2C bus. Luckily, Arduino offers a scanner library that simplifies the process of identifying slave addresses, eliminating the need to sift through lengthy sensor data sheets and confusing online documentation. To read values from components added to an I2C bus in such a project, it is important that you include the correct slave address when coding. You can customize this code to suit whichever sensors you may have in your project, or even display the sensor values on a display module to make your own room thermometer and humidity meter. write(temperature) // Send temperature data to master readTemperature() // Read temperature from DHT sensor # define DHTTYPE DHT11 // DHT sensor typeĭelay( 2000) // Wait for 2 seconds for DHT to stabilize # define DHTPIN 4 // Pin connected to DHT sensor read() // Read temperature data from slaveĭelay( 2000) // Wait for 2 seconds before requesting temperature again

requestFrom( 8, 1) // Request temperature data from slaveīyte temperature = Wire.

write( "hello ") // respond with message of 6 bytes as expected by master onReceive(receiveEvent) // call receiveEvent when data is received begin( 8) // join the I2C bus with address 8 In the above code, the Wire.available() function checks if data is available, and the Wire.read() function reads the data sent by the master device. The Wire.onReceive() function is used to specify what to do when the slave receives data from the master device. Then use the Wire.read() function to get data from the slave device. Use the Wire.requestFrom() function to specify the address of the slave device that we want to communicate with. Setting Up the Arduino Boards as I2C Master and Slave Devices
