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언어 예제소스 





 

 

 

 

+ Recent posts