Showing posts with label Book. Show all posts
Showing posts with label Book. Show all posts

Sunday, April 3, 2016

I2C Communication

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.

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.

THE I2C-BUS CONCEPT
            The I2C-bus supports any IC fabrication process (NMOS, CMOS, bipolar). Two wires, serial data (SDA) and serial clock (SCL), carry information between the devices connected to the bus.  Each device is recognized by a unique address (whether it’s a microcontroller, LCD driver, memory


or keyboard interface) and can operate as either a transmitter or receiver, depending on the function of the device. Obviously an LCD driver is only a receiver, whereas a memory can both receive and transmit data. In addition to transmitters and receivers, devices can also be considered as masters or slaves when performing data transfers (see Table 1). A master is the device which initiates a data transfer on the bus and generates the clock signals to permit that transfer. At that time, any device addressed is considered a slave.

GENERAL CHARACTERISTICS
            Both SDA and SCL are bi-directional lines, connected to a positive supply voltage via a current-source or pull-up resistor (see Fig.3). When the bus is free, both lines are HIGH. The output stages of devices connected to the bus must have an open-drain or open-collector to perform the wired-AND function. Data on the I2C-bus can be transferred at rates of 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. The number of interfaces connected to the bus is solely dependent on the bus capacitance limit of 400 pF. For information on High-speed mode master devices, see Section 13.

BIT TRANSFER
            Due to the variety of different technology devices (CMOS, NMOS, bipolar) which can be connected to the I2C-bus, the levels of the logical ‘0’ (LOW) and ‘1’ (HIGH) are not fixed and depend on the associated level of. One clock pulse is generated for each data bit transferred.

Data validity

            The data on the SDA line must be stable during the HIGH period of the clock. The HIGH or LOW state of the data line can only change when the clock signal on the SCL line is LOW.




START and STOP conditions
            Within the procedure of the I2C-bus, unique situations arise which are defined as START (S) and STOP (P) conditions (see Fig.5). A HIGH to LOW transition on the SDA line while SCL is
HIGH is one such unique case. This situation indicates a START condition. A LOW to HIGH transition on the SDA line while SCL is HIGH defines a STOP condition. START and STOP conditions are always generated by the master. The bus is considered to be busy after the START condition. The bus is considered to be free again a certain time after the STOP condition. This bus free situation is specified in Section 15. The bus stays busy if a repeated START (Sr) is generated instead of a STOP condition. In this respect, the START (S) and repeated START (Sr) conditions are functionally identical (see Fig. 10). For the remainder of this document, therefore, the S symbol will be used as a generic term to represent both the START and repeated START conditions, unless Sr is particularly relevant. Detection of START and STOP conditions by devices connected to the bus is easy if they incorporate the necessary interfacing hardware. However, microcontrollers with no such interface have to sample the SDA line at least twice per clock period to sense the transition.



/*#################################################################################################*/
#define SCL_1() { pinMode(SCL_PIN,0); }
#define SCL_0() { pinMode(SCL_PIN,1); }
#define SDA_1() { pinMode(SDA_PIN,0); }
#define SDA_0() { pinMode(SDA_PIN,1); }

void i2c_start(void)
{
  RELEASE_I2C_BUS();
  delayMicroseconds(I2C_DELAY);
  SDA_0();
  delayMicroseconds(I2C_DELAY);
  SCL_0();
  delayMicroseconds(I2C_DELAY);

return;
}
/*#################################################################################################*/

void i2c_stop(void)
{
  SDA_0();
  SCL_1();
  delayMicroseconds(I2C_DELAY);
  SDA_1();
  delayMicroseconds(I2C_DELAY);
  SCL_0();
  delayMicroseconds(I2C_DELAY);

return;
}
/*#################################################################################################*/


TRANSFERRING DATA

Byte format
            Every byte put on the SDA line must be 8-bits long. The number of bytes that can be transmitted per transfer is unrestricted. Each byte has to be followed by an acknowledge bit. Data is transferred with the most significant bit (MSB) first (see Fig.6). If a slave can’t receive or transmit another complete byte of data until it has performed some other function, for example servicing an internal interrupt, it can hold the clock line SCL LOW to force the master into a wait state. Data transfer then continues when the slave is ready for another byte of data and releases clock line SCL. In some cases, it’s permitted to use a different format from the I2C-bus format (for CBUS compatible devices for example). A message which starts with such an address can be terminated by generation of a STOP condition, even during the transmission of a byte. In this case, no acknowledge is generated.





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.








I2C Interface Library for arduino:
Define your connections SCL SDA connections
//blog.circuits4you.com
//Dt. 24-3-2016
//===========================================================================
//Enter your hardware connections here
#define SDA_PIN     4         /* The SDA port pin */
#define SCL_PIN     5         /* The SCL port pin */
//===========================================================================

#define I2C_DELAY     5     //( (I2C_DELAY_TIME*(F_CPU/60000))/100 )  
#define I2C_TIMEOUT   1000  // ( (I2C_TIMEOUT_TIME*(F_CPU/60000))/100 ) 

#define I2C_READ  1
#define I2C_WRITE 0

#define I2C_QUIT  0
#define I2C_CONTINUE  1

#define I2C_NO_ERROR       0
#define I2C_ERROR_DEVICE_BUSY    1
#define I2C_ERROR_DEVICE_NOT_RESPONDING  2

/* Macro definitions */

#define I2C_START(ADDRESS)     { i2c_start(); i2c_transmit(ADDRESS); }
#define I2C_START_TX(ADDRESS)  I2C_START(ADDRESS)
#define I2C_START_RX(ADDRESS)  I2C_START(ADDRESS | I2C_READ)
//------------------------------------
#define SCL_1() { pinMode(SCL_PIN,0); }
#define SCL_0() { pinMode(SCL_PIN,1); }
#define SDA_1() { pinMode(SDA_PIN,0); }
#define SDA_0() { pinMode(SDA_PIN,1); }

#define RELEASE_I2C_BUS() { SCL_1(); SDA_1(); }


void i2c_start(void);
void i2c_init(void);
void i2c_stop(void);
unsigned char i2c_transmit(unsigned char data);
unsigned char i2c_receive(unsigned char ack);

/*#################################################################################################*/
void i2c_init(void)
{
  digitalWrite(SDA_PIN,0);
  digitalWrite(SCL_PIN,0);
  
  RELEASE_I2C_BUS();
  delayMicroseconds(I2C_TIMEOUT);
  i2c_start();
  delayMicroseconds(I2C_TIMEOUT);
  i2c_stop();
  delayMicroseconds(I2C_TIMEOUT);
return;
}
/*#################################################################################################*/

void i2c_start(void)
{
  RELEASE_I2C_BUS();
  delayMicroseconds(I2C_DELAY);
  SDA_0();
  delayMicroseconds(I2C_DELAY);
  SCL_0();
  delayMicroseconds(I2C_DELAY);

return;
}
/*#################################################################################################*/

void i2c_stop(void)
{
  SDA_0();
  SCL_1();
  delayMicroseconds(I2C_DELAY);
  SDA_1();
  delayMicroseconds(I2C_DELAY);
  SCL_0();
  delayMicroseconds(I2C_DELAY);

return;
}
/*#################################################################################################*/

unsigned char i2c_transmit(unsigned char data)
{
register unsigned char bit=0;

  for(bit=0; bit<=7; bit++)
    {
        if( data & 0x80 ) { SDA_1(); } else { SDA_0(); }
        SCL_1();
        delayMicroseconds(I2C_DELAY);
        SCL_0();
        delayMicroseconds(I2C_DELAY);
        data = (data<<1);
    }
  /* Look for AKNOWLEDGE */
  RELEASE_I2C_BUS();
  delayMicroseconds(I2C_DELAY);


  if(digitalRead(SDA_PIN)==0) //bit_is_clear(I2C_SDA_PIN_REG, SDA_PIN) )
   {
       SCL_0();
       delayMicroseconds(I2C_DELAY);
   }
  else{
     delayMicroseconds(I2C_TIMEOUT);
     if(digitalRead(SDA_PIN)==0)  //bit_is_clear(I2C_SDA_PIN_REG, SDA_PIN) )
      {
         SCL_0();
         delayMicroseconds(I2C_DELAY);
      }
     else { return(I2C_ERROR_DEVICE_NOT_RESPONDING); }
      }


  if(digitalRead(SDA_PIN)==0)   // bit_is_clear(I2C_SDA_PIN_REG, SDA_PIN) ) 
   { 
         delayMicroseconds(I2C_TIMEOUT);
         if(digitalRead(SDA_PIN)==0)  // bit_is_clear(I2C_SDA_PIN_REG, SDA_PIN) ) 
         { return(I2C_ERROR_DEVICE_BUSY); }
   }   

return(I2C_NO_ERROR);   
}
/*#################################################################################################*/

unsigned char i2c_receive(unsigned char ack)
{
register unsigned char bit=0, data=0;

  SDA_1();
  for(bit=0; bit<=7; bit++)
    {
        SCL_1();
        delayMicroseconds(I2C_DELAY);
        data = (data<<1);
        if(digitalRead(SDA_PIN)==1)  //bit_is_set(I2C_SDA_PIN_REG, SDA_PIN) ) 
        { data++; }
        SCL_0();
        delayMicroseconds(I2C_DELAY);
    }
  
  /* if CONTINUE then send AKNOWLEDGE else if QUIT do not send AKNOWLEDGE (send Nack) */       
  if(ack==I2C_CONTINUE) { SDA_0(); }  else { SDA_1(); }
  SCL_1();
  delayMicroseconds(I2C_DELAY);
  SCL_0();
  delayMicroseconds(I2C_DELAY);

return data;
}
/*#################################################################################################*/


Please comment for any questions and query.


Introduction RS232 Communication

The Serial Port is harder to interface than the Parallel Port. In most cases, any device you connect to the serial port will need the serial transmission converted back to parallel so that it can be used. This can be done using a UART. On the software side of things, there are many more registers that you have to attend to than on a Standard Parallel Port.

So what are the advantages of using serial data transfer rather than parallel?

1. Serial Cables can be longer than Parallel cables. The serial port transmits a '1' as -3 to -25 volts and a '0' as +3 to +25 volts where as a parallel port transmits a '0' as 0v and a '1' as 5v. Therefore the serial port can have a maximum swing of 50V compared to the parallel port which has a maximum swing of 5 Volts. Therefore cable loss is not going to be as much of a problem for serial cables than they are for parallel.

2. You don't need as many wires than parallel transmission. If your device needs to be mounted a far distance away from the computer then 3 core cable (Null Modem Configuration) is going to be a lot cheaper that running 19 or 25 core cable. However you must take into account the cost of the interfacing at each end.

3. Infra Red devices have proven quite popular recently. You may of seen many electronic diaries and palmtop computers which have infra red capabilities build in. However could you imagine transmitting 8 bits of data at the one time across the room and being able to (from the devices point of view) decipher which bits are which? Therefore serial transmission is used where one bit is sent at a time. IrDA-1 (The first infra red specifications) was capable of 115.2k baud and was interfaced into a UART. The pulse length however was cut down to 3/16th of a RS232 bit length to conserve power considering these devices are mainly used on diaries, laptops and palmtops.

4. Microcontroller's have also proven to be quite popular recently. Many of these have in built SCI (Serial Communications Interfaces) which can be used to talk to the outside world. Serial Communication reduces the pin count of these MPU's. Only two pins are commonly used, Transmit Data (TXD) and Receive Data (RXD) compared with at least 8 pins if you use a 8 bit Parallel method (You may also require a Strobe).

Hardware Properties
            Devices which use serial cables for their communication are split into two categories. These are DCE (Data Communications Equipment) and DTE (Data Terminal Equipment.) Data Communications Equipment are devices such as your modem, TA adapter, plotter etc while Data Terminal Equipment is your Computer or Terminal. The electrical specifications of the serial port is contained in the EIA (Electronics Industry Association) RS232C standard. It states many parameters such as -
1. A "Space" (logic 0) will be between +3 and +25 Volts.
2. A "Mark" (Logic 1) will be between -3 and -25 Volts.
3. The region between +3 and -3 volts is undefined.
4. An open circuit voltage should never exceed 25 volts. (In Reference to GND)
5. A short circuit current should not exceed 500mA. The driver should be able to handle this without damage. (Take note of this one!)

            Above is no where near a complete list of the EIA standard. Line Capacitance, Maximum Baud Rates etc are also included. It is interesting to note however, that the RS232C standard specifies a maximum baud rate of 20,000 BPS!, which is rather slow by today's standards. Revised standards, EIA-232D & EIA-232E were released, in 1987 & 1991 respectively. Serial Ports come in two "sizes", There are the D-Type 25 pin connector and the D-Type 9 pin connector both of which 
are male on the back of the PC, thus you will require a female connector on your device. Below is a table of pin connections for the 9 pin and 25 pin D-Type connectors.


Serial Pinouts (D25 and D9 Connectors)

D-Type-25 PinNo.  D-Type-9 Pin No.                     Abbreviation Full Name
       Pin 2                     Pin 3                                        TxD Transmit Data
       Pin 3                     Pin 2                                        RxD Receive Data
       Pin 4                     Pin 7                                        RTS Request To Send
       Pin 5                     Pin 8                                        CTS Clear To Send
       Pin 6                     Pin 6                                        DSR Data Set Ready
       Pin 7                     Pin 5                                        SG Signal Ground
       Pin 8                     Pin 1                                        CD Carrier Detect
       Pin 20                   Pin 4                                        DTR Data Terminal Ready

       Pin 22                   Pin 9                                        RI Ring Indicator

Pin Functions
Abbreviation
 Full Name
 Function
TD
Transmit Data
Serial Data Output (TXD)
RD
Receive Data
Serial Data Input (RXD)
CTS
Clear to Send
This line indicates that the Modem is ready to exchange data.
DCD
Data Carrier Detect
When the modem detects a "Carrier" from the modem at the other end of the phone line, this Line becomes active.
DSR
Data Set Ready
 This tells the UART that the modem is ready to establish a link.
DTR
Data Terminal Ready
This is the opposite to DSR. This tells the Modem that the UART is ready to link.
RTS
Request To Send
 This line informs the Modem that the UART is ready to exchange data.
RI
Ring Indicator
 Goes active when modem detects a ringing signal from the PSTN.


Null Modems
            A Null Modem is used to connect two DTE's together. This is commonly used as a cheap way to network games or to transfer files between computers using Zmodem Protocol, Xmodem Protocol etc. This can also be used with many Microprocessor Development Systems.

DB9                                            DB9
3    TxD -------------------->  RxD       2
2    RxD -------------------->  TxD       3
5    GND<------------------>  GND     5


Above is my preferred method of wiring a Null Modem. It only requires 3 wires (TD, RD & SG) to be wired straight through thus is more cost effective to use with long cable runs. The theory of operation is reasonably easy. The aim is to make to computer think it is talking to a modem rather than another computer. Any data transmitted from the first computer must be received by the second thus TD is connected to RD. The second computer must have the same set-up thus RD is connected to TD. Signal Ground (SG) must also be connected so both grounds are common to each computer.
            The Data Terminal Ready is looped back to Data Set Ready and Carrier Detect on both
computers. When the Data Terminal Ready is asserted active, then the Data Set Ready and Carrier
Detect immediately become active. At this point the computer thinks the Virtual Modem to which it is connected is ready and has detected the carrier of the other modem.
            All left to worry about now is the Request to Send and Clear To Send. As both computers
communicate together at the same speed, flow control is not needed thus these two lines are also linked together on each computer. When the computer wishes to send data, it asserts the Request to Send high and as it's hooked together with the Clear to Send, It immediately gets a reply that it is ok to send and does so.
            Notice that the ring indicator is not connected to anything of each end. This line is only used to tell the computer that there is a ringing signal on the phone line. As we don't have a modem connected to the phone line this is left disconnected.

Flow Control
            So if our DTE to DCE speed is several times faster than our DCE to DCE speed the PC can send data to your modem at 115,200 BPS. Sooner or later data is going to get lost as buffers overflow, thus flow control is used. Flow control has two basic varieties, Hardware or Software.
            Software flow control, sometimes expressed as Xon/Xoff uses two characters Xon and Xoff. Xon is normally indicated by the ASCII 17 character where as the ASCII 19 character is used for Xoff. The modem will only have a small buffer so when the computer fills it up the modem sends a Xoff character to tell the computer to stop sending data. Once the modem has room for more data it then sends a Xon character and the computer sends more data. This type of flow control has the advantage that it doesn't require any more wires as the characters are sent via the TD/RD lines. However on slow links each character requires 10 bits which can slow communications down.
            Hardware flow control is also known as RTS/CTS flow control. It uses two wires in your serial cable rather than extra characters transmitted in your data lines. Thus hardware flow control will not slow down transmission times like Xon-Xoff does. When the computer wishes to send data it takes active the Request to Send line. If the modem has room for this data, then the modem will reply by taking active the Clear to Send line and the computer starts sending data. If the modem does not have the room then it will not send a Clear to Send.

RS-232 Waveforms
            So far we have introduced RS-232 Communications in relation to the PC. RS-232 communication is asynchronous. That is a clock signal is not sent with the data. Each word is synchronized using it's start bit, and an internal clock on each side, keeps tabs on the timing.



The diagram above, shows the expected waveform from the UART when using the common 8N1 format. 8N1 signifies 8 Data bits, No Parity and 1 Stop Bit. The RS-232 line, when idle is in the Mark State (Logic 1). A transmission starts with a start bit which is (Logic 0). Then each bit is sent down the line, one at a time. The LSB (Least Significant Bit) is sent first. A Stop Bit (Logic 1) is then appended to the signal to make up the transmission.
            The diagram, shows the next bit after the Stop Bit to be Logic 0. This must mean another word is following, and this is it's Start Bit. If there is no more data coming then the receive line will stay in it's idle state(logic 1). We have encountered something called a "Break" Signal. This is when the data line is held in a Logic 0 state for a time long enough to send an entire word. Therefore if you don't put the line back into an idle state, then the receiving end will interpret this as a break signal.
            The data sent using this method, is said to be framed. That is the data is framed between a Start and Stop Bit. Should the Stop Bit be received as a Logic 0, then a framing error will occur. This is common, when both sides are communicating at different speeds.
            The above diagram is only relevant for the signal immediately at the UART. RS-232 logic levels uses +3 to +25 volts to signify a "Space" (Logic 0) and -3 to -25 volts for a "Mark" (logic 1). Any voltage in between these regions (ie between +3 and -3 Volts) is undefined. Therefore this signal is putthrough a "RS-232 Level Converter". This is the signal present on the RS-232 Port of your computer, shown below.


The above waveform applies to the Transmit and Receive lines on the RS-232 port. These lines carry serial data, hence the name Serial Port. There are other lines on the RS-232 port which, in essence are Parallel lines. These lines (RTS, CTS, DCD, DSR, DTR, RTS and RI) are also at RS-232 Logic Levels.

RS-232 Level Converters
            Almost all digital devices which we use require either TTL or CMOS logic levels. Therefore the first step to connecting a device to the RS-232 port is to transform the RS-232 levels back into 0 and 5 Volts. As we have already covered, this is done by RS-232 Level Converters.
            Two common RS-232 Level Converters are the 1488 RS-232 Driver and the 1489 RS-232 Receiver. Each package contains 4 inverters of the one type, either Drivers or Receivers. The driver requires two supply rails, +7.5 to +15v and -7.5 to -15v. As you could imagine this may posea problem in many instances where only a single supply of +5V is present. However the advantages of these I.C's are they are cheap.

Another device is the MAX-232. It includes a Charge Pump, which generates +10V and -10V
from a single 5v supply. This I.C. also includes two receivers and two transmitters in the same package.
            This is handy in many cases when you only want to use the Transmit and Receive data Lines. You don't need to use two chips, one for the receive line and one for the transmit. However all this convenience comes at a price, but compared with the price of designing a new power supply it is very cheap.
            There are also many variations of these devices. The large value of capacitors are not only bulky, but also expensive. Therefore other devices are available which use smaller capacitors and even some with inbuilt capacitors. (Note : Some MAX-232's can use 1 micro farad Capacitors). However the MAX-232 is the most common, and thus we will use this RS-232 Level Converter in our examples.