Two-wire Serial Interface

참조 : ATmega128 Datasheet, I2C protocol, etc blog data.. 

 

I2C : 어떤 IC들간에도 공통적으로 통할 있는 버스(2가닥)

오늘의 주제 :  ATmega128 에서의 TWI 사용법에 대해서... 




 

 

PD1 INT1/SDA(1) (External Interrupt1 Input or TWI Serial DAta)

 

PD0 INT0/SCL(1) (External Interrupt0 Input or TWI Serial CLock)

 

 

 

• INT1/SDA – Port D, Bit 1

INT1, External Interrupt source 1.

The PD1 pin can serve as an external interrupt source

to the MCU.

SDA, Two-wire Serial Interface Data: When the TWEN bit in TWCR is set (one) to enable the Two-wire Serial Interface, pin PD1 is disconnected from the port and

becomes the Serial Data I/O pin for the Two-wire Serial Interface. In this mode, there is a spike filter on the pin to suppress spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver with slew-rate limitation.

 

 

 

 

 

• INT0/SCL – Port D, Bit 0

INT0, External Interrupt source 0. The PD0 pin can serve as an external interrupt source to the MCU.

SCL, Two-wire Serial Interface Clock: When the TWEN bit in TWCR is set (one) to enable the Two-wire Serial Interface, pin PD0 is disconnected from the port and becomes the Serial Clock I/O pin for the Two-wire Serial Interface. In this mode, there is a spike filter on the pin to suppress spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver with slew-rate limitation. Table 37 and Table 38 relates the alternate functions of Port D to the overriding signals.

 

 

 

Features

 

Simple yet Powerful and Flexible Communication Interface, only Two Bus Lines Needed

Both Master and Slave Operation Supported

Device can Operate as Transmitter or Receiver

7-bit Address Space allows up to 128 Different Slave Addresses

Multi-master Arbitration Support

Up to 400 kHz Data Transfer Speed

Slew-rate Limited Output Drivers

Noise Suppression Circuitry Rejects Spikes on Bus Lines

Fully Programmable Slave Address with General Call Support

Address Recognition Causes Wake-up when AVR is in Sleep Mode

 

간단히 설명을 풀자면..

I2C는 필립스사에서 처음개발하였으며, 특징으로는 오직 2가닥의 WIRE만 필요하며 /  BUS에 연결되어 소프트웨어적으로 주소지정이 가능한 각각의 장치들은 고유의 주소값과 마스터/슬레이브 관계를 가진다. (보통 마스터는 MCU가 되며, 슬레이브는 각종센서류나 메모리,출력장치가 된다)

다수의 마스터가 BUS에 연결되어있어도 장치간 충돌을 감지할수있으며 2개이상의 마스터를 초기화하여도 데이터가 변조되지않으며 통신이 가능하다.  (이는 버스구조로 인하여..)

그리고 3가지 MODE가 존재하며

1. Standard : 100kbps

2. Fast : 400kbps

3. High-speed : 3.4Mbps

AVR은 2가지 1.2. MODE만 제공한다. 

단일 칩 필터링으로 노이즈를 제거한다.

버스의 커패시턴스가 400pF을 넘지않는 한도안에서 IC연결이 가능하며 아트메가는 128개까지 가능하다. 이는 주소비트가 7bit이기 때문이다.


Two-wire Serial Interface Bus Definition

 

The Two-wire Serial Interface (TWI) is ideally suited for typical microcontroller applications.

The TWI protocol allows the systems designer to interconnect up to 128 different devices using only two bi-directional bus lines, one for clock (SCL) and one for data (SDA). The only external hardware needed to implement the bus is a single pull-up resistor for each of the TWI bus lines. All devices connected to the bus have individual addresses, and mechanisms for resolving bus contention are inherent in the TWI protocol.

 

 

>Pull-up 저항은 필요한가?  (R1,R2)

신호가 없으면 항상 High값을 유지하기때문에 BUS가 high상태라면 현재 통신이 가능하다는 뜻이 되며 이는 장치간의 충돌을 미연에 방지하는 역할을 하게 된다. 

 

As depicted in Figure 86, both bus lines are connected to the positive supply voltage through pull-up resistors. The bus drivers of all TWI-compliant devices are open-drain or open-collector. This implements a wired-AND function which is essential to the operation of the interface. A low level on a TWI bus line is generated when one or more TWI devices output a zero. A high level is output when all TWI devices tri-state their outputs,allowing the pull-up resistors to pull the line high. Note that all AVR devices connected to the TWI bus must be powered in order to allow any bus operation.

The number of devices that can be connected to the bus is only limited by the bus capacitance limit of 400 pF and the 7-bit slave address space. A detailed specification of the electrical characteristics of the TWI is given in “Two-wire Serial Interface Characteristics” on page 324. Two different sets of specifications are presented there, one

relevant for bus speeds below 100 kHz, and one valid for bus speeds up to 400 kHz



 

 

Data Transfer and Frame Format

 

Transferring Bits

 

 

Each data bit transferred on the TWI bus is accompanied by a pulse on the clock line.The level of the data line must be stable when the clock line is high. The only exception to this rule is for generating start and stop conditions

 

데이터의 유효성 : SCL이 High이면 SDA신호는 일정값을 유지해야한다. (DATA값)

                                SCL이 LOW이면 SDA신호는 변경이 가능하다.


START and STOP Conditions

 



앞서 SCL이 HIGH일때 SDA신호는 일정해야 한다고 하였다.

만약 값이 변한다면?? 그때가 바로 시작과 중단신호를 의미한다. (참 잘만든 프로토콜인듯..)

SCL = HIGH상태  -> SDA가 Falling Edge = START condition

SCL = HIGH상태  -> SDA가 rising Edge   = STOP  condition

 

그래서 DATA는 시작신호 이후에 입력될수있다.


Address Packet Format

 


Data Packet Format 


 

시작조건이 발생되면 ( SCL = HIGH상태  -> SDA가 Falling Edge ) SDA은 SCL의 클럭신호에 맞추어 DATA가 전송되는데 이는 8BIT형식이다. 만약 SLAVE가 데이터를 다 받지 못했다면 SLAVE는 SCL신호를 LOW로 잡아둠으로써 나머지 DATA를 모두 전송할수가 있다. (풀업설계의 장점이기도 하다)


Acknowledge

 

Data transfer with acknowledge is obligatory. The acknowledge-related clock pulse is generated by the master. The transmitter releases the SDA line (HIGH) during the acknowledge clock pulse.

The receiver must pull down the SDA line during the acknowledge clock pulse so that it remains stable LOW during the HIGH period of this clock pulse (see Fig.7). Of course, set-up and hold times )

must also be taken into account.

Usually, a receiver which has been addressed is obliged to generate an acknowledge after each byte has been received, except when the message starts with a CBUS address

When a slave doesn’t acknowledge the slave address

 (for example, it’s unable to receive or transmit because it’s performing some real-time function),

the data line must be left HIGH by the slave. The master can then generate either a STOP condition to abort the transfer, or a repeated START condition to start a new transfer.

If a slave-receiver does acknowledge the slave address but, some time later in the transfer cannot receive any more data bytes, the master must again abort the transfer. This is indicated by the slave generating the not-acknowledge on the first byte to follow. The slave leaves the data line HIGH and the master generates a STOP or a repeated START condition.

If a master-receiver is involved in a transfer, it must signal the end of data to the slave- transmitter by not generating

an acknowledge on the last byte that was clocked out of the slave. The slave-transmitter must release the data line

to allow the master to generate a STOP or repeated START condition.

 


요약하면, DATA전송이 끝나면 SLAVE는 의무적으로 ACK를 발생시켜야 한다. 또한 이를 위해서 MASTER는 8번째 비트까지 DATA전송을 끝내고 9번재는 그냥 클럭신호만 보내줘야한다. 그래서 SLAVE는 DATA선을 LOW로 유지하여 (신호선이 풀업상태라서 LOW로 유지된다면 ACK가 전송됐다고 판단된다) ACK를 보낸다. 그럼 마스터는 이때 DATA신호를 확인하면 ACK를 확인할수가 있다.

만약 MASTER가 전달하면 DATA를 SLAVE에서 놓치게 된다면??

MASTER는 전송하던 DATA를 무시하고 다시 STOP,START condition을 발생시켜야한다.

이는 ACK를 통해서 알수있는 SLAVE 쪽에서 주소값이 일치하지 않으면 SDA를 HIGH로 만들면 된다.

(이는 MASTER가 송신, SLAVE가 수신하는 경우를 예로 든것이다)



  

 

 

Combining Address and Data Packets Into a Transmission




 


*출처 :  유명환강사님자료



위의 그림은 데이터송신에 대한 일련의 과정을 하나의 그림으로 나타낸것이다. 자세한 소스는 맨아래의 "AVR STUDIO용 C언어 예제"소스라는 그림을 참조하길 바란다.

 

Overview of the TWI Module

The TWI module is comprised of several submodules, as shown in Figure 94. All registers drawn in a thick line are accessible through the AVR data bus.


 



Scl and SDA Pins

These pins interface the AVR TWI with the rest of the MCU system. The output drivers contain a slew-rate limiter in order to conform to the TWI specification. The input stages contain a spike suppression unit removing spikes shorter than 50 ns. Note that the internal pull-ups in the AVR pads can be enabled by setting the PORT bits corresponding to

the SCL and SDA pins, as explained in the I/O Port section. The internal pull-ups can in some systems eliminate the need for external ones.

 

Bit Rate Generator Unit

 

마스터모드에서 SCL의 주기를 조절할때 사용한다. 이는 TWBR레지스터를 통해서 설정할수가 있다.

This unit controls the period of SCL when operating in a Master mode. The SCL period is controlled by settings in the TWI Bit Rate Register (TWBR) and the Prescaler bits in the TWI Status Register (TWSR). Slave operation does not depend on Bit Rate or Prescaler settings, but the CPU clock frequency in the slave must be at least 16 times higher

than the SCL frequency. Note that slaves may prolong the SCL low period, thereby reducing the average TWI bus clock period. The SCL frequency is generated according to the following equation:

 



 

• TWBR = Value of the TWI Bit Rate Register

• TWPS = Value of the prescaler bits in the TWI Status Register

Note: TWBR should be 10 or higher if the TWI operates in Master mode. If TWBR is lower than 10, the master may produce an incorrect output on SDA and SCL for the reminder of the byte. The problem occurs when operating the TWI in Master mode, sending Start + SLA  + R/W to a slave (a slave does not need to be connected to the bus for the condition to

happen).

 

 

 

 

 

Bus Interface Unit

 

This unit contains the Data and Address Shift Register (TWDR), a START/STOP Controller and Arbitration detection hardware. The TWDR contains the address or data bytes to be transmitted, or the address or data bytes received. In addition to the 8-bit TWDR, the Bus Interface Unit also contains a register containing the (N)ACK bit to be transmitted or received. This (N)ACK Register is not directly accessible by the application software. However, when receiving, it can be set or cleared by manipulating the TWI Control Register (TWCR). When in Transmitter mode, the value of the received (N)ACK bit can be determined by the value in the TWSR.

 The START/STOP Controller is responsible for generation and detection of START, REPEATED START, and STOP conditions. The START/STOP controller is able to detect START and STOP conditions even when the AVR MCU is in one of the sleep modes, enabling the MCU to wake up if addressed by a master.

If the TWI has initiated a transmission as master, the Arbitration Detection hardware continuously monitors the transmission trying to determine if arbitration is in process. If the TWI has lost an arbitration, the Control Unit is informed. Correct action can then be taken and appropriate status codes generated.

 

Address Match Unit  :  NOT needed in the MASTER MODE

 

mutil master mode에서는 반드시 TWAR레지스터가 필요하다.


The Address Match unit checks if received address bytes match the 7-bit address in the TWI Address Register (TWAR). If the TWI General Call Recognition Enable (TWGCE) bit in the TWAR is written to one, all incoming address bits will also be compared against the General Call address. Upon an address match, the Control Unit is informed,

allowing correct action to be taken. The TWI may or may not acknowledge its address, depending on settings in the TWCR. The Address Match unit is able to compare addresses even when the AVR MCU is in sleep mode, enabling the MCU to wake up if addressed by a master. If another interrupt (e.g., INT0) occurs during TWI Power-down

address match and wakes up the CPU, the TWI aborts operation and return to it’s idle state. If this cause any problems, ensure that TWI Address Match is the only enabled interrupt when entering Power-down.

 

 

Control Unit

 

The Control unit monitors the TWI bus and generates responses corresponding to settings in the TWI Control Register (TWCR). When an event requiring the attention of the application occurs on the TWI bus, the TWI Interrupt Flag (TWINT) is asserted. In the next clock cycle, the TWI Status Register (TWSR) is updated with a status code identifying

the event. The TWSR only contains relevant status information when the TWI Interrupt Flag is asserted. At all other times, the TWSR contains a special status code indicating that no relevant status information is available. As long as the TWINT flag is set, the SCL line is held low. This allows the application software to complete its tasks

before allowing the TWI transmission to continue.  The TWINT flag is set in the following situations:

 

 

• After the TWI has transmitted a START/REPEATED START condition

• After the TWI has transmitted SLA+R/W

• After the TWI has transmitted an address byte

• After the TWI has lost arbitration

• After the TWI has been addressed by own slave address or general call

• After the TWI has received a data byte

• After a STOP or REPEATED START has been received while still addressed as a slave

• When a bus error has occurred due to an illegal START or STOP condition

 

  

TWI Register Description



 







If set, this bit enables the recognition of a General Call given over the Two-wire Serial Bus


 

  

. Using the TWI

 

이부분은 인터럽트방식으로 TWI통신을 사용할때를 설명한것이다. 보통 인터럽트로 통신을 많이 사용하며, 앞서 설명한 부분들과 C언어예제들은 모두 폴링방식이다. 혼동하지 않길 바란다.


The AVR TWI is byte-oriented and interrupt based. Interrupts are issued after all bus events, like reception of a byte or transmission of a START condition. Because the TWI is interrupt-based, the application software is free to carry on other operations during a TWI byte transfer. Note that the TWI Interrupt Enable (TWIE) bit in TWCR together with

the Global Interrupt Enable bit in SREG allow the application to decide whether or not assertion of the TWINT flag should generate an interrupt request. If the TWIE bit is cleared, the application must poll the TWINT flag in order to detect actions on the TWI bus.

 When the TWINT flag is asserted, the TWI has finished an operation and awaits application response. In this case, the TWI Status Register (TWSR) contains a value indicating the current state of the TWI bus. The application software can then decide how the TWI should behave in the next TWI bus cycle by manipulating the TWCR and TWDR Registers.

 

Figure 95 is a simple example of how the application can interface to the TWI hardware.In this example, a master wishes to transmit a single data byte to a slave. This description is quite abstract, a more detailed explanation follows later in this section. A simple code example implementing the desired behavior is also presented.


  

1. The first step in a TWI transmission is to transmit a START condition. This is done by writing a specific value into TWCR, instructing the TWI hardware to transmit a START condition. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the START condition

 

2. When the START condition has been transmitted, the TWINT flag in TWCR is set, and TWSR is updated with a status code indicating that the START condition has successfully been sent.

 

3. The application software should now examine the value of TWSR, to make sure that the START condition was successfully transmitted. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must load SLA+W into TWDR. Remember that TWDR is used both for address and data. After TWDR has been loaded with the desired SLA+W, a specific value must be written to TWCR, instructing the TWI hardware to transmit the SLA+W present in TWDR. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the address packet.

 

4. When the address packet has been transmitted, the TWINT flag in TWCR is set, and TWSR is updated with a status code indicating that the address packet has successfully been sent. The status code will also reflect whether a slave acknowledged the packet or not.

 

 

5. The application software should now examine the value of TWSR, to make sure that the address packet was successfully transmitted, and that the value of the ACK bit was as expected. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must load a data packet into TWDR. Subsequently, a specific value must be written to TWCR, instructing the TWI hardware to transmit the data packet present in TWDR. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the data packet.

 

6. When the data packet has been transmitted, the TWINT flag in TWCR is set, and TWSR is updated with a status code indicating that the data packet has successfully been sent. The status code will also reflect whether a slave acknowledged the packet or not.

 

7. The application software should now examine the value of TWSR, to make sure that the data packet was

uccessfully transmitted, and that the value of the ACK bit was as expected. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must write a specific value to TWCR, instructing the TWI hardware to transmit a STOP condition. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the STOP

condition. Note that TWINT is NOT set after a STOP condition has been sent.

 

 

Even though this example is simple, it shows the principles involved in all TWI transmissions.

 

These can be summarized as follows:

• When the TWI has finished an operation and expects application response, the TWINT flag is set. The SCL line is pulled low until TWINT is cleared.

 

• When the TWINT flag is set, the user must update all TWI Registers with the value relevant for the next TWI bus cycle. As an example, TWDR must be loaded with the value to be transmitted in the next bus cycle.

 

• After all TWI Register updates and other pending application software tasks have been completed, TWCR is written. When writing TWCR, the TWINT bit should be set. Writing a one to TWINT clears the flag. The TWI will then commence executing whatever operation was specified by the TWCR setting.

In the following an assembly and C implementation of the example is given. Note that the code below assumes that several definitions have been made for example by using include-files.

 

  

 

AVR studio C언어 예제소스 





 

 

 

 

도움이 되실지 모르겠습니다. I2C로 EEPROM의 내용을 R/W하는 예제입니다.


//=======================================

// MAIN PROJECT FILE

//=======================================

//

#include <avr/io.h>

#include <stdio.h>


#include <util/twi.h>


#include "eeprom24lc32.h"

#include "lcd.h"

#include "button.h"


int main()

{

long data, saved_data;

short rtn;

char string[80];


EprmInit(400); // 400 kHz TWI 전송속도

LcdInit();


data = 0x12345678;


if((rtn=EprmWriteNByte(0x500, (char *)&data, sizeof(data)))<0)

{

sprintf(string, "write error: %d", (int) rtn);

LcdMove(0,0); LcdPuts(string);


while(1);

}


// verify


if((rtn=EprmReadNByte(0x500, (char *)&saved_data, sizeof(saved_data)))<0)

{

sprintf(string, "write error: %d", (int) rtn);

LcdMove(0,0); LcdPuts(string);


while(1);

}

else

{

LcdMove(0,0); LcdPuts("Saved Data = ");


sprintf(string, "0x%lx", saved_data);

LcdMove(1,0); LcdPuts(string);

}


while(1);

}



//=======================================

// EEPROM24LC32.H

//=======================================

//


#ifndef __EEPROM24LC32_H__

#define __EEPROM24LC32_H__


void  EprmInit(unsigned int kHz);

short EprmWriteByte(short addr, char data);

short EprmWriteNByte(short addr, char data[], int n);

short EprmReadNByte(short addr, char data[], int n);


#endif


//=======================================

// EEPROM24LC32.C

//=======================================

//

//===========================================
// eerpom24lc32.c
//
// EEPROM 24LC32 구동 프로그램
//===========================================
//
#include <avr/io.h>
#include <util/twi.h>
#include <util/delay.h>

#include "lcd.h"

#include "eeprom24lc32.h"

#define DEVICE 0x00 // Device Select Bit
#define SLA_W (0xA0 | (DEVICE << 1))
#define SLA_R (0xA0 | (DEVICE << 1) | 0x01)

static short setAddr(short addr);

//====================================================
// TWI 버스를 초기화한다.
//====================================================
//
void EprmInit(unsigned int kHz)
{
TWSR = 1<<TWPS0; // 비트율 프리스케일러값을 16으로 한다.

// 비트율 설정
TWBR = (unsigned char) ((F_CPU/(kHz*1000L) - 16L)/(2L*4L));
}

//===================================================
// 1바이트 데이터를 24LC32A EEPROM에 쓴다.
//
// addr : 데이터를 쓸 EEPROM 주소
// 0x00 ~ 0xFFF
//  data : 쓸 데이터
//
// return :
// 0 - 성공
//   -1 - 쓰기 실패
//===================================================
//
short EprmWriteByte(short addr, char data)
{
short rtn;

//-----------------------------------
//  데이터를 쓸 EEPROM 주소를 보낸다.
//-----------------------------------
if((rtn=setAddr(addr)) < 0)
return rtn;

//-----------------------------------
// 데이터 전송
//-----------------------------------
TWDR = data;
TWCR = (1<<TWINT) | (1<<TWEN);

while(!(TWCR & (1<<TWINT))); // DATA가 보내질 때까지 기다린다.
if((TWSR & TW_STATUS_MASK) != TW_MT_DATA_ACK) // DATA 전송후 슬레이브로 부터 ACK를 받았는 지 검사
return -3;

//----------------------------------
// STOP 조건을 보낸다.
//----------------------------------
TWCR = (1<<TWINT) | (1<<TWSTO) | (1<<TWEN);
while((TWCR & (1<<TWSTO))); // STOP조건이 보내질 때까지 기다린다.

return 0;
}

//===================================================
// n 바이트 데이터를 EEPROM에 쓴다.
//
// addr : EEPROM 주소 
// 0x00 ~ 0xFFF
//  data : 쓸 데이터를 저장한 버퍼주소
//  n : 쓸 데이터 개수
//
// return :
// 양수 - 다음 쓸 EEPROM 주소
//   -1 - 쓰기 실패
//===================================================
//

short EprmWriteNByte(short addr, char *data, int n)
{
int i, rtn;

for(i=0; i<n; i++)
{
if((rtn=EprmWriteByte(addr, *data))<0)
return rtn;
addr++;
data++;
}

return addr;
}

//===================================================
// n 바이트 데이터를 EEPROM으로부터 읽어들인다.
//
// addr : EEPROM 주소 
// 0x00 ~ 0xFFF
//  data : 읽은 데이터를 저장할 버퍼
//  n : 읽을 데이터 개수
//
// return :
//    0 - 성공
//   -1 - 읽기 실패 
//===================================================
//
short EprmReadNByte(short addr, char data[], int n)
{
int i;

//----------------------------------------
// 읽을 데이터의 주소를 보낸다.
//----------------------------------------
if(setAddr(addr) < 0)
return -5;

//---------------------------------------
// REPEATED START
//---------------------------------------
TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN); // START 조건을 보낸다.
while(!(TWCR & (1<<TWINT))); // START조건이 보내질 때까지 기다린다.
if((TWSR & TW_STATUS_MASK) != TW_REP_START) // 정상적으로 REPEATED START조건이 보내졌는 지 검사한다.
return -6;


//--------------------------------------
// SLA_R를 보낸다.
//--------------------------------------
TWDR = SLA_R;
TWCR = (1<<TWINT) | (1<<TWEN);

while(!(TWCR & (1<<TWINT))); // SLA_R이 보내질 때까지 기다린다.
if((TWSR & TW_STATUS_MASK) != TW_MR_SLA_ACK) // SLA_R 전송후 슬레이브로 부터 ACK를 받았는 지 검사
return -7;

//----------------------
// 데이터 읽기
//----------------------
for(i=0; i<n-1; i++)
{
TWCR = (1<<TWINT) | (1<<TWEA) | (1<<TWEN); // TWI동작을 시작한다.  데이터를 받으면 ACK를 보낸다.
while(!(TWCR & (1<<TWINT))); // 데이터를 받을 때까지 기다린다.
if((TWSR & TW_STATUS_MASK) != TW_MR_DATA_ACK)
return -8;
data[i] = TWDR; // 데이터를 읽는다.
}

// 마지막 바이트를 받으면 ACK를 보내지 않는다.

TWCR = (1<<TWINT) | (1<<TWEN); // TWI동작을 시작한다. 데이터를 받으면 ACK를 보내지 않는다.
while(!(TWCR & (1<<TWINT))); // 데이터를 받을 때까지 기다린다.
if((TWSR & TW_STATUS_MASK) != TW_MR_DATA_NACK)
return -9;
data[i] = TWDR; // 마지막 데이터를 읽는다.

//-----------------------------
// STOP 조건을 보낸다.
//-----------------------------

TWCR = (1<<TWINT) | (1<<TWSTO) | (1<<TWEN);
while(TWCR & (1<<TWSTO)); // STOP조건이 보내질 때까지 기다란다.
return 0;
}


//=========================================-------===================
// eeprom에 데이터를 쓰기/읽기를 위한 제어 및 주소 바이트를 보낸다.
//
//  addr : 데이터를 쓰기/읽기를 할 주소
//
// return :
// 0   - 성공
//   음수 - 전송 실패
//===================================================================
//
static short setAddr(short addr)
{
while(1)
{
TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN); // START 조건을 보낸다.
while(!(TWCR & (1<<TWINT))); // START조건이 보내질 때까지 기다린다.
if((TWSR & TW_STATUS_MASK) != TW_START) // 정상적으로 START조건이 보내졌는 지 검사한다.
return -10;

TWDR = SLA_W;
TWCR = (1<<TWINT) | (1<<TWEN); // SLA_W를 보낸다.
while(!(TWCR & (1<<TWINT))); // SLA_W가 보내질 때까지 기다린다.

if((TWSR & TW_STATUS_MASK) == TW_MT_SLA_ACK)
break;
else // eeprom이 준비되지 않았음
{
TWCR = (1<<TWINT) | (1<<TWSTO) | (1<<TWEN); // STOP 조건을 보낸다.
while(TWCR & (1<<TWSTO)); // STOP조건이 보내질 때까지 기다란다.
}
};

//--------------------------------------------------------
// eeprom 주소를 상위바이트, 하위바이트 순으로 보낸다.
//--------------------------------------------------------

TWDR = (unsigned char) (addr >> 8);
TWCR = (1<<TWINT) | (1<<TWEN); // 상위바이트 전송
while(!(TWCR & (1<<TWINT))); // DATA가 보내질 때까지 기다린다.

// DATA 전송후 슬레이브로 부터 ACK를 받았는 지 검사
if((TWSR & TW_STATUS_MASK) != TW_MT_DATA_ACK)
return -12;

TWDR = (unsigned char) addr; // 하위바이트 전송
TWCR = (1<<TWINT) | (1<<TWEN);
while(!(TWCR & (1<<TWINT))); // DATA가 보내질 때까지 기다린다.

// DATA 전송후 슬레이브로 부터 ACK를 받았는 지 검사
if((TWSR & TW_STATUS_MASK) != TW_MT_DATA_ACK)
return -13;

return 0;
}


9 FORMATS WITH 7-BIT ADDRESSES


Data transfers follow the format shown in Fig.10. After the START condition (S), a slave address is sent. This address is 7 bits long followed by an eighth bit which is a data direction bit (R/W) - a ‘zero’ indicates a transmission (WRITE), a ‘one’ ndicates a request for data (READ). A data transfer is always terminated by a STOP condition (P) generated by the master. However, if a master still wishes to communicate on the bus, it can generate a repeated START condition (Sr) and address another slave without first generating a STOP condition. Various combinations of read/write formats are then possible within such a transfer





Possible data transfer formats are:

· Master-transmitter transmits to slave-receiver. The transfer direction is not changed (see Fig.11).

· Master reads slave immediately after first byte (see Fig.12). At the moment of the first acknowledge, the master- transmitter becomes a master- receiver and the slave-receiver becomes a slave-transmitter. This first acknowledge is still generated by the slave. The STOP condition is generated by the master, which has previously sent a not-acknowledge (A).

· Combined format (see Fig.13). During a change of direction within a transfer, the START condition and the slave address are both repeated, but with the R/W bit reversed. If a master receiver sends a repeated START condition, it has previously sent a not-acknowledge (A).

NOTES:

1. Combined formats can be used, for example, to control a serial memory. During the first data byte, the internal memory location has to be written. After the START condition and slave address is repeated, data can be transferred.

2. All decisions on auto-increment or decrement of previously accessed memory locations etc. are taken by the designer of the device.

3. Each byte is followed by an acknowledgment bit as indicated by the A or A blocks in the sequence.

4. I2C-bus compatible devices must reset their bus logic on receipt of a START or repeated START condition such that they all anticipate the sending of a slaveaddress, even if these START conditions are not positioned according to the proper format.

5. A START condition immediately followed by a STOP , condition (void message) is an illegal format.






위의 Fig11,12,13 의 형태로 데이터를 전송합니다.


-> 요약하면, DATA는 반드시 8bit 크기로 보내어진다. 그리고 Slave가 data를 다 수신하지 못했다면 slave는 SCL신호를 LOW로 유지함으로써 Data를 모두 전달 받을수가 있다. (그래서 신호선이 풀업저항설계가 되어있는 것.) //


[통신의 송수신 순서]

1. SDA,SCL 둘다 HIGH 상태인가?  - 그렇다면 Bus는 비어있다.

2. 시작비트를 보낸다. (SCL: : HIGH, SDA : LOW)

3. 7bit의 주소값을 보내고 1bit의 R/W를 보낸다.

4. ACK를 수신하기 위해서 SDA방향을 마스터기준으로 INPUT으로 변경하고 SCL만 출력한다 (클럭신호만 아웃)

5. ACk왔다면 실어보낼 데이터를 전송한다. (1byte)

6. ACK를 수신하기 위해서 SDA의 방향을 마스터기준으로 INPUT으로 또다시 변경하고 SCL만을 출력

7. 더이상 전송할 데이터가 없다면 SDA와 SCL을 HIGH상태로 변경시킨다.

8. 정지비트를 보낸다.



[인터넷에 있는 데이터 송수신 예제입니다. ] : southlife님의 블로그참조 http://southlife.tistory.com/49 







The I2C-bus specification


1 PREFACE (서문)


1.1 Version 1.0 - 1992

This version of the 1992 I2C-bus specification includes the following modifications:

· Programming of a slave address by software has been omitted.

  The realization of this feature is rather complicated and has not been used.

· The “low-speed mode” has been omitted. This mode is, in fact, a subset of the total I2C-bus specification and need not be specified explicitly.

· The Fast-mode is added. This allows a fourfold increase of the bit rate up to 400 kbit/s. Fast-mode devices are downwards compatible i.e. they can be used in a 0 to 100 kbit/s I2C-bus system.

· 10-bit addressing is added. This allows 1024 additional slave addresses.

· Slope control and input filtering for Fast-mode devices is specified to improve the EMC behaviour.

NOTE: Neither the 100 kbit/s I2C-bus system nor the 100 kbit/s devices have been changed.


1.2 Version 2.0 - 1998

The I2C-bus has become a de facto world standard that is now implemented in over 1000 different ICs and licensed to more than 50 companies. Many of today’s applications, however, require higher bus speeds and lower supply voltages. This updated version of the I2C-bus specification meets those requirements and includes the following modifications:

· The High-speed mode (Hs-mode) is added. This allows an increase in the bit rate up to 3.4 Mbit/s. Hs-mode devices can be mixed with Fast- and Standard-mode devices on the one I2C-bus system with bit rates from 0 to 3.4 Mbit/s.

· The low output level and hysteresis of devices with a supply voltage of 2 V and below has been adapted to meet the required noise margins and to remain compatible with higher supply voltage devices.

· The 0.6 V at 6 mA requirement for the output stages of Fast-mode devices has been omitted.

· The fixed input levels for new devices are replaced by bus voltage-related levels. 

· Application information for bi-directional level shifter is added.


1.3 Version 2.1 - 2000

Version 2.1 of the I2C-bus specification includes the following minor modifications:

· After a repeated START condition in Hs-mode, it is possible to stretch the clock signal SCLH (see Section 13.2 and Figs 22, 25 and 32). · Some timing parameters in Hs-mode have been relaxed (see Tables 6 and 7).




2 THE I2C-BUS BENEFITS DESIGNERS AND MANUFACTURERS


In consumer electronics, telecommunications and industrial electronics, there are often many similarities between seemingly unrelated designs. For example, nearly every system includes:

· Some intelligent control, usually a single-chip microcontroller

· General-purpose circuits like LCD drivers, remote I/O ports, RAM, EEPROM, or data converters

· Application-oriented circuits such as digital tuning and signal processing circuits for radio and video systems, or DTMF generators for telephones with tone dialling. To exploit these similarities to the benefit of both systems designers and quipment manufacturers, as well as to maximize hardware efficiency and circuit simplicity, Philips developed a simple bi-directional 2-wire bus for efficient inter-IC control. This bus is called the Inter IC or I2C-bus.

At present, Philips’ IC range includes more than 150 CMOS and bipolar I2C-bus compatible types for performing functions in all three of the previously mentioned categories. All I2C-bus compatible devices incorporate an on-chip interface which allows them to communicate directly with each other via the I2C-bus. This design concept solves the many interfacing problems encountered when designing digital control circuits. 

Here are some of the features of the I2C-bus:

· Only two bus lines are required; a serial data line (SDA) and a serial clock line (SCL)

· Each device connected to the bus is software addressable by a unique address and simple master/slave relationships exist at all times; masters can operate as master-transmitters or as master-receivers

· It’s a true multi-master bus including collision detection and arbitration to prevent data corruption if two or more masters simultaneously initiate data transfer · Serial, 8-bit oriented, bi-directional data transfers can be made at up to 100 kbit/s in the Standard-mode, up to 400 kbit/s in the Fast-mode, or up to 3.4 Mbit/s in the High-speed mode

· On-chip filtering rejects spikes on the bus data line to preserve data integrity

· The number of ICs that can be connected to the same bus is limited only by a maximum bus capacitance of 400 pF.

Figure 1 shows two examples of I2C-bus applications.


 2.1 Designer benefits

I2C-bus compatible ICs allow a system design to rapidly progress directly from a functional block diagram to a prototype. Moreover, since they ‘clip’ directly onto the I2C-bus without any additional external interfacing, they allow a prototype system to be modified or upgraded simply by ‘clipping’ or ‘unclipping’ ICs to or from the bus.

Here are some of the features of I2C-bus compatible ICs which are particularly attractive to designers:

· Functional blocks on the block diagram correspond with the actual ICs; designs proceed rapidly from block

diagram to final schematic.

· No need to design bus interfaces because the I2C-bus interface is already integrated on-chip.

· Integrated addressing and data-transfer protocol allow systems to be completely software-defined

· The same IC types can often be used in many different applications

· Design-time reduces as designers quickly become familiar with the frequently used functional blocks represented by I2C-bus compatible ICs

· ICs can be added to or removed from a system without affecting any other circuits on the bus

· Fault diagnosis and debugging are simple; malfunctions can be immediately traced

· Software development time can be reduced by assembling a library of reusable software modules.

In addition to these advantages, the CMOS ICs in the I2C-bus compatible range offer designers special features which are particularly attractive for portable equipment and battery-backed systems.

They all have:

· Extremely low current consumption

· High noise immunity

· Wide supply voltage range

· Wide operating temperature range.


2.2 Manufacturer benefits


I2C-bus compatible ICs don’t only assist designers, they also give a wide range of benefits to equipment

manufacturers because:

· The simple 2-wire serial I2C-bus minimizes interconnections so ICs have fewer pins and there are

not so many PCB tracks; result - smaller and less expensive PCBs

· The completely integrated I2C-bus protocol eliminates the need for address decoders and other ‘glue logic’

· The multi-master capability of the I2C-bus allows rapid testing and alignment of end-user equipment via external connections to an assembly-line

· The availability of I2C-bus compatible ICs in SO (smalloutline), VSO (very small outline) as well as DIL packages reduces space requirements even more.

These are just some of the benefits. In addition, I2C-bus compatible ICs increase system design flexibility by allowing simple construction of equipment variants and easy upgrading to keep designs up-to-date. In this way, an entire family of equipment can be developed around abasic model. Upgrades for new equipment, or enhanced-feature models (i.e. extended memory, remote control, etc.) can then be produced simply by clipping the appropriate ICs onto the bus. If a larger ROM is needed,

it’s simply a matter of selecting a micro-controller with a larger ROM from our comprehensive range. As new ICs supersede older ones, it’s easy to add new features to equipment or to increase its performance by simply unclipping the outdated IC from the bus and clipping on its successor.


3 INTRODUCTION TO THE I2C-BUS SPECIFICATION

For 8-bit oriented digital control applications, such as those requiring microcontrollers, certain design criteria can be

established:

· A complete system usually consists of at least one microcontroller and other peripheral devices such as memories and I/O expanders

· The cost of connecting the various devices within the system must be minimized 

· A system that performs a control function doesn’t require high-speed data transfer 

· Overall efficiency depends on the devices chosen and the nature of the interconnecting bus structure.

To produce a system to satisfy these criteria, a serial bus structure is needed. Although serial buses don’t have the

throughput capability of parallel buses, they do require less wiring and fewer IC connecting pins. However, a bus is not merely an interconnecting wire, it embodies all the formats and procedures for communication within the system.

Devices communicating with each other on a serial bus must have some form of protocol which avoids all possibilities of confusion, data loss and blockage of information. Fast devices must be able to communicate with slow devices. The system must not be dependent on the devices connected to it, otherwise modifications or improvements would be impossible. 

A procedure has also to be devised to decide which device will be in control of the bus and when. And, if different devices with different clock speeds are connected to the bus, the bus clock source must be defined. All these criteria are involved in

the specification of the I2C-bus.


결론적으로 2000년도에 발표된 2.1버전의 특징만 아시면 됩니다.

간단하게 요약하자면 ,

-오직 2가닥의 와이어만 필요합니다 (SDA-Serial Data Line, SCL-Serial Clock Line) 또한 인터페이스는 칩에 내장되어있기에 별다른 디자인이 필요하지 않습니다.

-SCL은 마스터에서 클럭소스를 OUT하는 선이며 SDA는 SCL의 클럭에 완벽히 동기화되어 실제 data가 송수신됩니다.

-Bus에 연결된 master와 slave는 소프트웨어적으로 adress접근이 가능하다면 완벽하게 연결되며 제어가 됩니다.

-다수의 마스터가 연결될수가 있으며 장치간 충돌이 있어도 감지가 가능합니다. 또한 2개이상의 마스터를 초기화해도 통신이 가능합니다.

-시리얼 8비트 데이터통신은 일반모드에서 100kbps의 속도를 FAST모드에서 200kbps, Highspeed모드에서 3.4Mbps의 속도를 가집니다.

-단일칩 필러터링으로 버스에서 발생할수있는 노이즈를 차단할수있습니다

-최대 연결이 가능한 버스는 커패시턴스가 400pF이 넘지않는다면 IC를 계속 연결할수있습니다. ATmega를 예로들면 최대 연결이 가능한 IC는 128개로 제한하고 있습니다. 이는 주소값이 7bit 가지므로 2^7=128 의 이론값에서 나온것입니다.


일단 이정도 하시면 사용에 문제는 없습니다.

+ Recent posts