In this section, you'll look at using the I2C interface to send and receive serial data for interfacing with sensors and other devices.

Transcript

Now that you've learned about spire communication, let's take a look at another popular form of serial communication known as the I2C. I2C stands for Inter Integrated Circuit and is widely used for serial communication between devices. It's slower than SPI but has the advantage of requiring only two pins for communication, clock and data. It allows for multiple master devices on a single bus and rather than hardware lines for accessing slave devices, each device on a bus has a unique address, usually seven bits which is transferred along the data line to select the appropriate device.

Because I2C shares the data line for both transmitting and receiving data it is known as a half-duplex protocol as data can be transmitted and received but not at the same time. The I2C communication protocol is slightly more complicated than SPI due to the extra layer of protocol required for the shared data line and it is also slower than SPI however the ability to control hundreds of devices using only two lines is quite advantageous in many situations. Like the previous section I've included some diagrams of the communication structure so the I2C data however the library will be taken care of most of the heavy lifting for us. Read and write bits are sent along with the data to determine whether the master wishes to read or write information with an expected acknowledge bit or act for short to determine whether the bite was successfully received by the other device or not. We can control a I2C device from an Arduino using the wire library which makes I2C communication incredibly straightforward. Like SPI it is possible to emulate the communication using software functions however again this leads to some burdensome software overheads, so if you're using I2C ensure that your chip has a hardware I2C port. For the first I2C example I'll be connecting two Arduino boards up to exchange data via the bus and print it out on the serial monitor. It allows us to use the wire library directly and get an understanding of the control sequence. After that we'll connect up a real-time clock module by I2C  and use a specific RTC library to control which handles the I2C communication behind-the-scenes, so connect up your Arduino boards as shown in the wiring diagram in the workshop page and we'll run through the code.

 Alrighty so here I've got loaded up the master reader code, now there are two sections of codes that are important to this example because we're using two Arduino boards so if you go to the workshop page you can see that I’ve got the source code to the master reader Arduino demo and this is taken from the Arduino reference site because it's such a good example of demonstrating their while library and then we got the slave sender Arduino code. What that means is that the master is going to request some data from the slave, the slave will send it and the master will then print that data up to the serial monitor so we can see what's going on. So, take the master reader code into your Arduino and now we're going to upload that to one of our boards now you'll notice I’ve got the 5 volt line connected between the Arduino here and that's just because I'm only using one USB cable which means I need to get data across to them and you can use this 5 volt line to power another Arduino only if you are sure that it is a clean regulated 5 volts and is unlikely to spike. Given that it’s coming from the other Arduino regulator directly it's a pretty safe bet that it's going to be usable so I'm just using that to allow us to run two Arduino boards with only one USB cable however you can use two USB cables as well that's perfectly fine. So, take your cable clock, so I’ve connected that up and this one's going to be my master reader. So, I'm going to select the appropriate comport for that guy and upload and while that's uploading I'll grab the slave sender code here, so that's successfully uploaded and we'll copy the slave sender in here I'll go through the code line by line in a moment and we'll take a look at how it works.

You can see that when I connect that one up that's the lights on this one turn on as well because it's sharing that 5-volt line. We’ll select our new comport, upload that. To make a bit more sense of it I'll go to the workshop page where you can see the code against each other, so the master reader is quite simple we're including the wire dot H library in our setup we're initializing the wire library much in the same way that we had to initialize the SPI library we use “wire.begin” then you fill the slave device in the bracket so you would put your address. So, “serial.begin” initializing the serial interface, then here we're using “wire.requestFrom” and we're requesting some data from address number 8 on the bus and we're requesting 6 bytes of data then it waits and while there is a “wire.available” so similar to the “serial.available” it says if there's data available from the I2C our incoming data, then let's read that sequentially, get each character that's coming in and print it out to the serial terminal, so that's the master section there.

Now for the slave, there's a little bit more to it we've got the wire library again now we're initializing the wire libraries, with address number “8” and then we are creating a handling function here so, “wire.onRequest (requestEvent)” what this does is it creates a separate function which can be accessed whenever the on request is sent. So request event is a function that executes whenever data is requested by the master and so whenever our master says “hey slave I want some data” it will run this function and it says “wire.write (“Hello”)” so it pushes the characters or the actual letters themselves h-e-l-l-o along the I2C bus to the master and that is how both of these are going to work. I'm going to take the USB cable put it back into my master device so that I can read from the terminal, now if I select the write comport, go to serum monitor, I can see Hello is being transferred every second over and over again because that is the data that our slave is trying to send.

So, now that we've looked at a basic I2C example let's look at using this coming a little more practical. For this example I'll be interfacing in Arduino with an I2C real-time clock module or RTC which allows an Arduino or other board to get an accurate timestamp regardless of whether or not power has been disconnected, thanks to the coin cell battery on the RTC which powers the module after power off. The easiest way to use the RTC module is to use Adafruit’s library for it which I’ve included a link to in the section resources. Again, take a look at the wiring diagram in the section resources and we'll dive into the code which is an example of web borrowing from the Adafruit library. Alright, so I've got my breadboard all set up and it's quite simple with I2C only requiring two lines of data and clock, clock being on the furthermost pin and data just inside it and then of course power and ground, so let's take a look at the code for that one. Now as I mentioned this is an Adafruit branded module which is fantastic, it's outside of the Sparkfun inventors kit we've been using but it's such a valuable module and Adafruit have fantastic software resources and support available for it, it seems a shame not to use their example.

Let's take a look, at the very top we can see the include “#include <wire.h>” and then we're including the RTC library. Now we don't have the RTC library, so we need to go and download it and we'll look at a more practical real-world example of downloading a library including in our Arduino IDE.  So, in section resources here, it will take us to the Adafruit tutorial page for this particular module, we can download the RTC library. We can just include that directly as a zip file, I'll go to downloads see that guy there, so we include that and will now include the RTC library in our sketch, which is fantastic. Then we're saying the type of chip on board the RTC module that we're going to be using which is the DS3231 so we've got there, then we're creating a character array now this is actually a special type of array known as a two-dimensional array, you can see that unlike a standard array we've got two sets of indexing here. Now what this says, it's a two dimensional array so you think about the fact that it has one dimension that way and one dimension that way or in other words you can reference both a line or a row and a column, so the maximum number of individual elements that we're going to have is 7 because they're seven days of the week, then the maximum number of letters to use in any one of these words is 12 so we use the maximum there so that each word has enough space and then if we were to reference days of the week as 01 then we would go to element 0 and it would go to 1 or the second part of the second letter of that particular element which would be a “U” which is really cool, so that is how we can use two-dimensional arrays and it just creates a day of the week that we can refer to and it just has some references in case you're using a special type of chip. The ESP8266 which we are not, so if it doesn’t do that then it just initializes the serial port, wait for the console to open and then it checks to see if there is an RTC on there so if it can't begin RTC function if it returns not true then it says hang on we can't find an RTC you need to connect it up.

Then if it's lost power, then it will go through the calibration process and after that it will print out the correct time, date and year according to the serial print structure that we have here and waits for 3 seconds and prints it out again. We'll go ahead and upload that to our board, now it’ll go through and compile and it will base the time that it uses for calibration of the Arduino IDE. So, in a moment it's going to print out to our serial monitor. So, as you can see it's not giving us the correct date obviously because it hasn't had a chance to calibrate itself but we can see here that it is working perfectly once it's given a second, once it's initialized and now we're getting the time so 1600 hours which is 24 hours speak for 4 o'clock in the afternoon, which it is and it is the 9th of the 3rd 2017 or backwards if you're one of our American friends and just like that it will keep our time up to date.

If we power off, just to show that this isn’t some sort of Arduino trickery, power that off makes it back up and open our serial monitor up again it will keep that time which is really cool so it should show that it's for 16:01. So, that is the real time clock module and it's really easy to use in fact it's so easy because Adafruit created such a fantastic library and some really good examples so you can take that same concept where all it's doing is saying date time now is equal to RTC now and RTC now is a function of the RTC library which grabs the current date and time and print it out and you can use that for it whatever you want is extremely accurate and this module is actually really cool especially because it has on board crystal on the chip which makes it so chunky. Now the crystal timing or the oscillation which keeps the clock running can deviate slightly according to the temperature. Now inside this it has an internal temperature sensor which can detect the temperature and use a scaling function to actually adjust the clock on the fly so it is extremely accurate which is really cool, I love using this module for real-time projects and that is all about the I2C interface.

Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.