Sending floats over the I²C bus between two Arduinos — Part 1
I²C is a low speed 2-wire serial communication protocol for exchanging information betwwen one or more masters and multiple slave devices.
All the devices are connected via a common 2-wire bus and each device is uniquely addressable. As such no sperate address lines are required for selecting individual devices unlike in SPI or UART communication protocol.
Sparkfun has a very good introductory article on I²C protocol which I would strongly recommend reading.
Problem Statement
The Arduino I²C bus can be accessed using the Arduino Wire Library, which sends data as a stream of bytes over the I²C bus, using the function Wire.write().
This write function expects a single byte or an array of bytes to send data over the I²C bus.
As such sending or receiving a single byte data like a character or a stream of bytes like a string is very simple as shown by the examples
However sending/receiving floats and other datatypes require some extra steps to convert them into an array of bytes before sending and again converting them to their original datatype upon receiving.
Proposed Solution
One way of achieving this is to convert the float to its equivalent string represetntation by using the dtostrf() function of the C Standard Libary before transmission and again converting the received string to its float equivalent using toFloat() method of the Arduino Sting class.
Given below are the sample codes for Arduino Master & Slave devices which does whatever we have discussed till now.
Hope this post was useful. Have a nice Day!
Part 2 of this tutorial here.