I love the Atmel AVR microcontrollers! Since building the Ghetto Development System described in this Instructable, I've had no end of fun experimenting with the AVR ATtiny2313 and the ATmega168 in particular. I even went so far as to write an Instructable on using switches as inputs, and extended the Ghetto Development System concept to CPLDs.

During a recent project, I needed several switches for setting control values. The AVRs did not have enough I/O pins, so I had to think of something. I could have tried a complex input system with a keyboard and display, but the ATtiny2313 would have run out of resources. Fortunately, Atmel has provided a way around this problem by including an interface that can link to additional chips (such as memory or I/O ports) with a simple two wire interface. That's right, by using just two I/O pins on an AVR we can access many additional I/O pins, and other resources as well.

This two wire interface is formally known as the Inter-Integrated Circuit bus, or just the I2C bus and was invented by NXP when it was still Philips Semiconductors. If you're reading this Instructable then you've probably heard of the I2C bus and may even have used it on a PIC or other microcontroller. While conceptually very simple, and supported by hardware resources on the AVRs, software drivers are still necessary to use the I2C bus. Atmel provides Application Notes (see the Resources later in this Instructable), but these are incomplete and don't show any examples beyond communicating with another AVR device.

It is not the purpose of this Instructable to teach anyone how to create I2C drivers for the AVRs. Rather, I'll provide expanded versions of the Atmel drivers for ATtiny2313 and ATmega168 devices, I'll explain the requirements and restrictions that apply when using these, and I'll show you working examples of I2C devices. After you work through this Instructable you'll be able to use the I2C bus successfully in your AVR projects. Obviously, you can ignore the drivers for either tiny or MEGA if you're only interested in one of them. For those interested in learning more about the I2C bus, I'll provide links to appropriate material.

Step 1: What's All this I2C stuff anyway?

The I2C bus is a simple, two-wire connection that can link multiple devices together and allow them to exchange data. In its simplest form there is one master device that communicates to multiple slave devices. All devices are connected in parallel to the two wires of the I2C bus. The two wires are known as SCL and SDA. SCL is the clock line and is controlled by the master device. SDA is the bi-directional data line. To transfer data, the master sends out a slave address combined with a one bit read/write flag. If a write is desired, the master will continue to send data to the addressed slave. If a read is requested, the slave will respond with data. To coordinate transactions, the SCL and SDA lines are manipulated by the master and the slave to signal several conditions. These include START, STOP, ACK (acknowledge) and NAK (no acknowledge). The details of these conditions are handled by the drivers. The true geeks among you can learn all the details in the links provided at the end of this Instructable.

The electrical requirements are pretty simple. The master and the slaves must use the same level for Vcc, the grounds must be connected, and the SCL and SDA lines must be pulled up to Vcc. The value of the pull-up resistors is precisely determined by a calculation based on the total capacitance on the bus, but practically can be pretty much any value between 1.8K and 10K. I start with 5.1K and use lower values until it works. This usually isn't an issue unless you have a lot of devices or long lengths of wire between devices.

The nominal data rate on the I2C bus is 100Kbits/second. Rates of 400Kbits/second, 1Mbits/second, and beyond are possible as well, but aren't supported by the drivers in this Instructable. All I2C devices will work at 100Kbits/second.

The ATtiny2313 and the ATmega168 each implement the I2C bus differently. ATtiny2313 uses the Universal Serial Interface (USI) hardware - which can also be used for the SPI bus. ATmega168 has dedicated hardware for the I2C bus known as the Two Wire Interface (TWI). Once the drivers are written, these differences are mostly transparent to the user. One significant difference is in the software: The ATmega168 I2C driver is interrupt driven while that for the ATtiny2313 is not. This means that an ATmega168 program does not have to wait for I2C data transfers to take place, but only needs to wait before initiating another transfer, or until data arrives from a read operation. The examples and discussion to follow should make this clear.

I2C addresses are 7 bits long, so up to 127 devices can be on the bus if each has a unique address. As shown in the figure, this 7 bit address is shifted left one bit and the least significant bit is used to flag a read or write of the device at the address. Thus the complete slave address is an 8 bit byte. The actual address is partially determined internally to the device and can't be changed (4 most significant bits), and partially determined by bits that may be connected to device pins (3 least significant bits) that can be tied high or low to set a specific address.

Sounds confusing, but an example will make this clear. The PCA8574A data sheet shows that the four most significant bits of the I2C address will always be 0111. The next three bits are determined by the settings on pins AD0, AD1 and AD2. These pins can be tied to ground or to the positive voltage supply (5 volts) to represent 0 or 1 respectively. So the range of possible addresses is 38 to 3F hexadecimal, as shown in the other figure from the PCA8574 data sheet. So by changing the address bit settings, up to 8 PCA8574As can be on the I2C bus at the same time. Each will respond to its specific slave address only. If even more I/O ports are needed, the PCA8574 can be used. The only difference between the PCA8574 and the PCA8574A is that the I2C slave address range of the PCA8574 is 20 to 27 hexadecimal.

Determining the address of a given device can be confusing since some data sheets consider the read/write bit to be part of the address. Read the data sheet carefully and keep in mind that the slave address will be 7 bits long. The read/write bit should be treated separately. Again, an example will help. The data sheet for the 24C16 EEPROM we'll experiment with says the first (most significant) four bits of the slave address are 1010. The next three bits can be determined by A0, A1 and A2; but note the data sheet also covers 24C01 through 24C08 which are smaller sized EEPROMs. The figure from the data sheet shows that the settings of these address bits are ignored as the size increases and are completely ignored for the 24C16. That is, the last three bits don't matter and the 24C16 really uses all I2C slave addresses 50 through 57 hexadecimal. The range of slave addresses will actually address different sections within the 24C16. The first 256 bytes are at address 50h, the next 256 at 51h, and so on up to the last 256 at 57h - for a total of 2K bytes. Since the address of the PCF8570 RAM we also experiment with is in this range, the 24C16 and the PCF8570 can't be used together.
<p>for attiny 85 plz help me</p>
<p>Thanks for your interest in this project! Let's see if I can help you.</p><p>Note that the ATTINY85 has the same USI as the ATTINY2313, so the code should work with it. What problems are you having and what have you tried?</p><p>Note that there is now support for the ATTINY85 in Arduino. That might be a simple way to get things going and experiment. Have a look here:</p><p><a href="http://highlowtech.org/?p=1695" rel="nofollow">http://highlowtech.org/?p=1695</a></p><p>HTH!</p>
<p>very useful and explained well.</p><p>As you mentioned,the USI I2c code is developed based on System clock 1MHz..</p><p>What are the changes in other clock values.</p><p>I want to use this code for 11.0592Mhz.</p><p>I think these are the section for this change.But How?</p><p><strong>// Defines controlling timing limits - SCL &lt;= 100KHz.</strong></p><p><strong>#define SYS_CLK 1000.0 // [kHz]Default for ATtiny2313</strong></p><p><strong>// For use with _delay_us()</strong></p><p><strong>#define T2_TWI 5 // &gt;4,7us</strong></p><p><strong>#define T4_TWI 4 // &gt;4,0us</strong></p>
I have only used the default clock, so I don't know the exact answer to your question. Here's how I would proceed. First, define SYS_CLK as 11059.2 // KHz - your clock rate. Then use any spare pin and write a loop to pulse it on and off using _delay_us() with values of 5 and 4. Look at the results on a scope and tune as needed to get the proper delays.<br><br>HTH
<p>very useful to understand some of the lower level details.</p><p>I have a question about vcc. You mentioned that the slave and master vcc has to be the same. The only reason I can think for this is the high value of the sda and scl pin will be 5v at the master and 3.6 v at the slave. Is this the reason or am I missing something?</p><p>Is there something that can be done in the driver to overcome this problem since I'm using the TWI over USI(I'm using attiny85. Please correct me if I am wrong)</p>
<p>You are correct. The pull up for both lines must be to the same voltage.There are voltage translators you can use but I don't have those details at my fingertips. Google is your friend ;&gt;)}}.</p>
Thanks Doctek for the rapid fast response. Is it possible to update the TWI driver so I can overcome this issue. Perhaps I can use analogwrite in the driver and that way I can level the output at SDA and SCL lines to 3.6 Volts.<br><br>As an FYI. My Vcc at the slave is 3.6 Volts. My pull-up resistors are connected to 3.6 Volts as well. However, since my master is at 5 volts, the pins on the master that drive SDA and SCL go between 0 Volts and 5 Volts(a). So what I was wondering was if I use analogWrite to drive the Master pins I could reduce the voltage at those pins to 3.6 Volts perhaps?
<p>Sorry for the delay. I wanted to research this a bit. Keep in mind that the IIC lines are bidirectional, so just pulling up one way won't help. Further, I don't know if you can use the analogwrite function to work with IIC.</p><p>The simple way is to check your slave device and see if its IOs are 5 volt tolerant. If so, you can just pull the I2C lines up to 5V and call it good.</p><p>If the slave IOs are *not* 5V tolerant, then you need some sort of buffer. Have a look at Philips AN97055.pdf for use of a MOSFET to do this (maybe NXP instead of Philips now?). Also look at the TI I2C Guide (sszc003e.pdf) for details on a suitable buffer chip (and a whole lot more).</p><p>HTH.</p>
First, thanks for providing sources which compile with avr-gcc! <br> <br>I'm trying to use the random read function and it makes sense but for one step: <br>in USI_TWI_Start_Transceiver_With_Data, when you wrote the start address (in write mode) and you re-set the buffer, go back into address mode, it seems like you're also missing setting USI_TWI_state.masterWriteDataMode to false. Without that, I ran through the loop and I can't see how you'd ever end up in the &quot;read&quot; section. <br> <br>What am *I* missing? <br> <br>Thanks, <br>Dan.
Glad you find this of interest, Dan! <br> <br>You ask a good question. You are obviously interested in understanding the code, not just using it. The only thing you are &quot;missing&quot; is how the masterWriteDataMode bit gets cleared - not your fault since the naming and commenting are not clear. Let me try to explain how it works. <br> <br>The statement <br>USI_TWI_state.errorState = 0; <br>clears the masterWriteDataMode bit (line 217). That's why the addressMode bit must be reset at line 218. <br>(This is not well documented. USI_TWI_state.errorState is a union that includes the mode bits. Setting the uchar errorState to 0 sets all the bits in the union to 0 also. This behavior is documented by a comment in the USI_TWI_Start_Read_Write routine and should have been duplicated everywhere it's done.) <br> <br>The operation of the loop should make sense now. <br> <br>Let me know if it's still not clear or if you have other questions.
Worked perfectly! Thanks doctek. Used it to talk with the DS1307 RTC to make a Word Clock. http://no8hacks.com/blog/2012/8/16/led-word-clock
Glad you found my code useful. And that's a very cool clock you built - I'm proud to be a part of it.
One more (dumb) question:<br><br>How do I get my AVR Studio 4 to build your code? In other words, how do I get AVR Studio to process your makefile?<br><br>Newbie here, I know.
I used WinAVR to build the examples in the Ible. I haven't used AVR Studio recently, but as I recall it doesn't need a Makefile. (More correctly, it creates its own invisibly.) Just start a new C project and cut and paste the code into files in AVR Studio, then Make the project. That should do it. You probably need to be sure the processor choice, clock rate, etc. is correct.<br>
Curious: I am trying to use I2C to communicate between two ATtiny44's. Question for you: how do I know what address each has? This is missing from the data sheet. <br><br>Also, is there a way using I2C to be both a master and slave? I'm thinking of having one be the master, and the slave toggling a GPIO when it wants to communicate...initiating a read, for example. <br><br>Any code that would help me with that? I am relatively new to this. :-(
Being fully programmable devices, the address is left up to the programmer: pick your favorite. If you have other devices on the I2C bus, pick something that doesn't conflict.<br><br>I2C devices are either Master or Slave, not both. Slaves do not speak unless spoken to (by the Master). The correct way to have a Slave communicate is for it to be continuously polled by the Master. Respond with a meaningless value if there is no valid response ready. If you have a device that frequently needs to send bursts of data, then make it the Master and have the receiving device be the Slave and just listen.<br><br>If you have only programmable devices on the bus, it is possible for them to switch roles as Master and Slave, but they must do this independently of the I2C Bus when no one is using the bus. Do this only if you're sure other ways won't work since you'll be on your own developing the code.<br><br>Have fun with your I2C experiments!
Thanks! Question though: Where do I define the I2C address? Sorry, newbie here. Maybe this is a #define already in your code?<br><br>Others have mentioned that there is a TWAR register...but I searched the ATtiny44 datasheet for such a register and none exists.<br><br>Thanks again for the great advice!
I2C is implemented differently in the ATTiny parts (as I discuss in the Ible) - more done in software, less hardware support. So there is no TWAR register. You must implement the slave address decoding in software. This Ible did not discuss making a Slave device using an AVR. Have a look at the Atmel site and you'll find app notes on doing this. Note that the Atmel app notes implement the Slave address decoding in a non-standard way, but the approach works.<br><br>This becomes an advanced amateur project. You'll learn a lot making this work, but expect to spend some time learning. Good luck and have fun.
Hi... I'm interested in using an ATTiny85... will it work? If not, what changes do I have to make
The ATTiny85 has a USI port, so the I2C should work like the ATTiny2313. You should compare the data sheets and be sure you have the pin numbering correct. Also verify that the register naming is the same. It should be similar is not identical.<br><br>Good Luck!
Great tutorial!, <br> <br>I'm making a turntable for modeltrains which uses a lot of I/O and only has 2 wires available (along with supply of course) to control all functions on the rotating part of the bridge. <br>Because of the fact that the controller (ATMEGA8) does have to do all the controll-functions (motor / locks / position sensors etc.) as well as the reception and feedback of the loconet signals (protocol for controlling aceccories on a model rail layout) I'm bound to run the ATMEGA8 at the full 16MHz. Will that be possible with your TWI library? When yes, what do i have to modify? Or are there other options. Thanks in advance!
Sounds like a fun project!<br><br>To use the TWI at 16MHz, all you need to do is adjust the SCL frequency. This is described in the data sheet under the TWI port, Bit Rate Generator Unit. If you change the value of TWI_TWBR from 0x0C to 0x48, that should do it. TWI_TWBR is defined in TWI_Master.h.<br><br>Here's the calculation:<br><br>SCLfreq = Processor Clock /(16 + 2*(TWBR)*4^TWPS)<br>SCLfreq=16MHz/(16 + 2(72)*4^0) = 16MHz/160 = 100KHz<br><br>HTH. Let me know if this doesn't make sense.
You might want to change your eeprom link, just to be complete. The company was sold. Unfortunately, there are 679 devices listed &amp; I haven't a clue as to which one(s) are applicable. Here is the page: <br>http://www.onsemi.com/PowerSolutions/parametrics.do?id=2311&amp;lctn=home<br><br>This is a print, study, &amp; keep Instructable. Thanks for all the information.
Where are the downloads?? I get a page not found!!<br><br>Great article.<br><br>Ralph
Got the download from the web download link, the link in the .pdf is broke!!<br><br>Ralph
I really appreciate the author spending the time to write this tutorial.&nbsp; I have built the ATTINY2313 and PCA8574 I/O expander circuit. However, I have one question on the schematic.&nbsp; The LEDs on the PCA 8574 seems to be backward. They will never turn on. Maybe the common&nbsp; VCC connection is wrong and it should be GND instead? Can the author clarify it?&nbsp; Thanks.<br />
Nice catch! The LEDs on the I/O expander schematic are indeed backwards and would never turn on. Reversing them makes things work correctly. Do not connect the common connection to ground unless you want the LEDs to default to on instead of off. The PCA8574's outputs are initially high, not low. So the circuit is intended to turn the LEDs on when an output is taken low. Thus, the common connection is to VCC.<br /> <br /> Thanks for your attention to detail!<br />
<em>Atmel claims it's possible to use AVR port pull-ups for the I2C bus pull-ups. I haven't figured out a way to make that approach work.<br /> </em><br /> Have you tried setting the pin and then twiddling the DDR instead of the actual pin. ISTR that being the usual way to do open collector-ish lines.<br />
Not all avr's have TWI, though. It would be nice to see some great writeup on developing a bitbang driver. That'd be useful for other controllers as well.<br />
I used this great instructable and referenced it a couple times in my instructable <a href="https://www.instructables.com/id/I2C-Controlled-7-Segment-LED-Display/" rel="nofollow">I2C Controlled 7 Segment LED Display</a>.&nbsp; I used the LED display as part of a digital thermometer.&nbsp; I&nbsp;really like I2C.&nbsp; I also used external 4.7k pullup resistors on each I2C line rather than relying on the AVR internal ones.<br />
Nice job with your Instructable! I'm glad you found mine useful and I appreciate the shout-out. The external pull-ups are shown in my schematic for the 2313 and are discussed in the second paragraph of step one. The value you found useful (4.7K) is right in the range I suggest: 1.8 to 5.1K, so I'm glad that worked for you. The internal pull-ups are fine for switches, but I just didn't quite trust them for this application.<br /> <br /> Your comments remind me that I need to update this Instructable with my latest code that now handles addresses longer than two bytes. (See discussion with p2otoole.)<br />
Too cool.&nbsp; The project I'm working on right now will have an AVR&nbsp;as an I2C slave to put a 16x2 LCD character display on an I2C bus.&nbsp; To try and make an LCD module that's super easy to add to a project.&nbsp; I'm going off the slave versions of the Atmel app. notes you used for this project.<br />
Sounds like a great project! I'm eager to see the Instructable. Of course there are already some I2C 16x2 displays out there, but that shouldn't keep you from making a better one!<br /> <br /> If you use the code from Atmel for the slave, be aware that they handle addressing in a non-standard way. Have a look at the data sheets for the standard approach. The data sheets for the parts (EEPROM and Port Expander) I used are a good place to start. You could also have a look at some of the I2C displays that exist to see what they do. Or invent your own scheme. It's your project after all.<br />
Yeah, the one I plan on making is considerably cheaper than any I could find and I&nbsp;plan on making the user interface easier too.&nbsp; And as I'm sure you understand, I'm as much interested in learning and teaching how to make a slave I2C device as I am in making a better I2C LCD display.&nbsp; I think the I2C protocol is so versatile and&nbsp; over 100 devices with only 2 pins is hard to beat.<br />
&nbsp;Do you have a &quot;twi slave&quot; code for for ATTINY2313? I want to control multiple of those from a master ARDUINO...<br /> <br />
Hey my friends i need make the arduino send a a message to the nxt please how do i make it.I want to program the nxt to use nxc connceted to the arduino,the arduino will be connected to the rfid reader.the rfid tag will be read and the arduino compares with the tags olready stored in its memory,if it corresponds it sends the msg to the nxt,plz help is vry vry agent
Dear Developer of this source code,<br /> <br /> I have a question about the source code.<br /> <br /> I went over the code written for ATtiny2313. You select External, positive edge for the Shift register and Software clock strobe (USITC) for 4-bit Counter (USICS1=1, USICS0=0, USICLK=1). In the function unsigned char USI_TWI_Start_Transceiver_With_Data() you define the constant&nbsp;below.<br /> <br /> &nbsp; unsigned char const tempUSISR_8bit = (1&lt;&lt;USISIF)|(1&lt;&lt;USIOIF)|(1&lt;&lt;USIPF)|(1&lt;&lt;USIDC)|&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Prepare register value to: Clear flags, and<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (0x0&lt;&lt;USICNT0);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // set USI to shift 8 bits i.e. count 16 clock edges.<br /> <br /> Why the program has to count 16 clock edges for 8-bit transfer? I thought the programhas to count 16 clock edges for 8-bit transfer when USICS1=1, USICS0=0, USICLK=0 or when USICS1=1, USICS0=1, USICLK=0.<br /> <br /> Please explain.<br /> <br /> Thank you so much,<br />
This part of the code (as I point out) is from Atmel. Have a look at the Apps Notes and data sheets I reference in Step 7. Frankly, the code worked fine for me and I was satisfied with that. If this question is of real concern to you and the resources I mention don't help, then you might post your question at the AVR Freaks site. <br />
Great experiment, if I can only get it to compile in AVR Studio4! Does anyone have any tips on opening this project in AVR Studio 4? Even though Studio4 allows me to manually open the USI_I2C_Port.c file, when made into a project file, it complains: >Coordinator: None of the available object file readers can read the specified >object file. Please check the format of the object file. >Error loading object file I:\My Documents\AVR\Programs\I2C\USI I2C\I_O >Port\USI_I2C_Port.c and stops. Suggestions? Thanks, -fab
Ok, I got it compiled. Apparently the USI_TWI_Master.c has to be put into the source files area in the project, then there were a few minor version related changes, but the code is now in the tn2313! -fab
I tried using the program TWI_I2C_EEPROM.c, with the circuit hooked up according to the schematic, of course, and got <strong>(1) waring: return type of 'main' is not 'int'. </strong> <strong>(2) error: 'CLKPR' undeclared (first use in this function)</strong><br/>Other than that, this program was what I have been looking for, and I know its gonna work for me,<br/><strong>Thank you</strong><br/>
The warning about main seems to come with the gcc compiler. I think there's a way to get rid of it, but I haven't been successful at doing so. Hints I've found about how to do it haven't worked. It can be safely ignored, however. CLKPR is the register for the ATmega168. What processor are you compiling for? You may have to change the name.
I was trying to upload to an atmega8, which has the same pin layout and number of pins as an at-168. Also the EEPROM ckt that I have is a 24LC512; two strikes against me right there, I reckon. But I do have an atmega168 that I could use. I don't have the other ckts. that you discussed in this tutorial (port extender, etc) I would really like to get this program going, as it is one that I have been searching for; it will fit right into my plan. Thank you
The parts you are interested in should work, but there's a couple of details you should know about. I downloaded the data sheets and here's what I found.<br/><br/>The ATmega8 does not have a CLKPR register. To set the clock prescaler to give you a 4MHz clock you have to blow fuse bits. With that done, the TWI looks like it would work the same.<br/><br/>The 24LC512 lives in the I2C address block from 50h to 57h. You pick the exact address by tying A0-A2 high or low to select the three least significant bits. That is, all lo = 50h, A0 hi, rest lo = 51h, etc.<br/><br/>But there's an additional wrinkle (isn't there always? ;)} The 24LC512 uses two address bytes to address the 64K memory space. Mostly not a problem, you just put in an extra address byte and make the buffer 1 byte bigger. Skip one additional byte when you try to read from the buffer as well. The block read and write size is 128 bytes, so that needs to change if you want to take advantage of that capability. Finally, the TWi_Start_Random_Read read routine must be modified since you have to send two address bytes instead of one address byte before sending the second START signal.<br/><br/>Unfortunately I don't have a 24LC512 to experiment with so I can't guarantee this will work, but I <em>think</em> all that needs to be done is to pass in an additional argument to the function telling it how long the address is. Right now that value is always 2, but if you add the argument then you could pass in either 2 or 3. If you want to contact me privately I'll send you modified code to try out. If it works, we could post it as an update.<br/>
Impressive. Well written!

About This Instructable




More by doctek:Cheap, One Chip Arduino Easy Oogoo Miixing with Printed Auger Build a Dual Extruder for 3D Printing 
Add instructable to: