Showing posts with label protocol. Show all posts
Showing posts with label protocol. Show all posts

Friday, 15 August 2014

SOCKET PROGRAMMING

Generally a socket is an endpoint communication between two systems on a network.
A socket address is a combination of IP address and Port number.
Sockets are bi-directional.
The application that initiates the communication is called a Client and the other one is called Server.

TYPES OF SOCKETS:

1. Socket Stream- connection oriented,(i.e)the first the two parties establish a connection after which any data is passed through that connection.
2. Datagram Socket- connection less(i.e) either party sends datagrams as neede and waits for the other to respond.

PROTOCOL: 

1. Initialize Winsock in the server
2. create a socket for the server
3. bind the socket-Connection
4. listen on the socket for the client
5. Now,Initialize the winsock for the Client
6. Create a socket for the Client
7. Connect to the server 
8. Server must accept the connection from the client
9. send and receive data 
10. Disconnect the chat

SERVER SIDE

          1)Initialize Winsock in the server-Create a WSADATA object called wsaData.
                        
                WSADATA wsaData; -->The WSADATA structure contains information about the Windows Sockets implementation.
    
          2) Call WSAStartup and return its value as an integer and check for errors.The WSAStartup function is called to initiate use of WS2_32.dll.
             The WSADATA structure contains information about the Windows Sockets implementation. 
             The MAKEWORD(2,2) parameter of WSAStartup makes a request for version 2.2 of Winsock on the system,
             and sets the passed version as the highest version of Windows Sockets support that the caller can use.

              Result = WSAStartup(Version, &wsaData);             
              if (Result != ZERO)
     {
               printf("WSAStartup failed with error\n");
  free(sendbuf);
                   return 1;
              }  
       else 
     {
  printf("WSAStartup success\n");
     }

                     
3) After initialization, a SOCKET object must be instantiated for use by the client.
           Declare an addrinfo object that contains a sockaddr structure and initialize these values.
           For this application, the Internet address family is unspecified so that either an IPv6 or IPv4 address can be returned. 
           The application requests the socket type to be a stream socket for the TCP protocol.
                               

    struct addrinfo *result;
              struct addrinfo hints;

              memset(&hints, 0, sizeof(hints)); // making hints to zero
              hints.ai_family = AF_INET; // address family formats for IPv4
              hints.ai_socktype = SOCK_STREAM; // sock-stream,(reliable two way communication)
              hints.ai_protocol = IPPROTO_TCP;        // Transmission Control Protocol (TCP)
     hints.ai_flags = AI_PASSIVE; // the caller intends to use the returned socket address structure in a call to the bind function
             
         4) Call the getaddrinfo function requesting the IP address for the server name passed on the command line. 
            The TCP port on the server that the client will connect to is defined by DEFAULT_PORT as 27015 in this sample.
            The getaddrinfo function returns its value as an integer that is checked for errors. 


               Result = getaddrinfo(HOST_ADDRESS, DEFAULT_PORT, &hints, &result); // hold the address info
               if (Result != ZERO)
      {
                  printf("getaddrinfo failed\n");
 free(sendbuf);
                  return 1;
               }
     else
      {
printf("getaddrinfo success\n");
      }


5)  Create a SOCKET object called ConnectSocket.Call the socket function and return its value to the ConnectSocket variable. For this application,
            use the first IP address returned by the call to getaddrinfo that matched the address family, socket type, and protocol specified in the hints parameter.
            In this example, a TCP stream socket was specified with a socket type of SOCK_STREAM and a protocol of IPPROTO_TCP. 
            The address family was left unspecified (AF_UNSPEC), so the returned IP address could be either an IPv6 or IPv4 address for the server.
            If the client application wants to connect using only IPv6 or IPv4, then the address family needs to be set to AF_INET6 for IPv6 or AF_INET for IPv4 in the hints parameter.


ListenSocket = socket(result->ai_family,result->ai_socktype,result->ai_protocol); // Create a SOCKET to listen
                if (ListenSocket == INVALID_SOCKET)
       {
                   printf("socket not Created\n");
                   free(sendbuf);
                   return 1;
                }
       else
       {
  printf("Socket Created\n");
       }

        6)  Bind the socket

                Result = bind( ListenSocket, result->ai_addr, result->ai_addrlen); // Setup the TCP listening socket
                if (Result != ZERO)
       {
                    printf("bind failed\n");
                    free(sendbuf);
                    closesocket(ListenSocket);
                    return 1;
                }
       else
       {
    printf("bind success\n");
       }         
   

       7) Call the listen function, passing as parameters the created socket and a value for the backlog,
          maximum length of the queue of pending connections to accept.
          In this example, the backlog parameter was set to SOMAXCONN. 
          This value is a special constant that instructs the Winsock provider for this socket to allow a maximum reasonable number of pending connections in the queue.
          Check the return value for general errors.


Result = listen(ListenSocket,0);            // listening on the socket for the client
                if (Result != ZERO) 
       {
                   printf("listen failed\n");
  free(sendbuf);
                   closesocket(ListenSocket);
                   return 1;
                }
       else 
       {
  printf("Listen success\n");
       }

      8) Once the socket is listening for a connection, the program must handle connection requests on that socket.
         Create a temporary SOCKET object called ClientSocket for accepting connections from clients.


              ClientSocket = accept(ListenSocket, NULL, NULL);    // Accept a client socket
              if (ClientSocket == INVALID_SOCKET)
     {
                printf("accept failed\n");
free(sendbuf);
                closesocket(ListenSocket);
                return 1;
              }
     else
     {
printf("Accept success\n");
     }

      

CLIENT SIDE

    1) Similarly initialize winsock,like you did in server.After initialization, a SOCKET object must be instantiated for use by the client.
       create a socket.Declare an addrinfo object that contains a sockaddr structure and initialize these values.
       For this application, the Internet address family is unspecified so that either an IPv6 or IPv4 address can be returned. 
       The application requests the socket type to be a stream socket for the TCP protocol.


        WSADATA wsaData;                                  
                 Result = WSAStartup(Version, &wsaData); // Initialize Winsock
                 if (Result != 0)
        {
                    printf("WSAStartup failed\n");
   free(sendbuf);
                    return 1;
                 }
        else
        {
   printf("WSAStartup success\n");
        }

                struct addrinfo *result;                           
                struct addrinfo hints;                              

                memset(&hints, 0, sizeof(hints));        // making hints to zero
                hints.ai_family = AF_INET;       // address family formats for IPv4
                hints.ai_socktype = SOCK_STREAM;     // sock-stream,(reliable two way communication)
                hints.ai_protocol = IPPROTO_TCP;      // Transmission Control Protocol (TCP)


2) Call the getaddrinfo function requesting the IP address for the server name passed on the command line.
           The TCP port on the server that the client will connect to is defined by DEFAULT_PORT as 27015 in this sample. 
           The getaddrinfo function returns its value as an integer that is checked for errors.

                 Result = getaddrinfo(LOOP_ADDRESS,DEFAULT_PORT, &hints, &result);         // hold address information
                 if (Result != 0)  
        {
                     printf("getaddrinfo failed\n");
    free(sendbuf);                            
                     return 1;
                 }
        else
       {
    printf("getaddrinfo success\n");
       }

3) Call the socket function and return its value to the ConnectSocket variable.
           For this application, use the first IP address returned by the call to getaddrinfo that matched the address family, socket type, and protocol specified in the hints parameter.
           In this example, a TCP stream socket was specified with a socket type of SOCK_STREAM and a protocol of IPPROTO_TCP.The address family was left unspecified (AF_UNSPEC), 
           so the returned IP address could be either an IPv6 or IPv4 address for the server.If the client application wants to connect using only IPv6 or IPv4, 
           then the address family needs to be set to AF_INET6 for IPv6 or AF_INET for IPv4 in the hints parameter.


ConnectSocket=socket(result->ai_family,result->ai_socktype,result->ai_protocol); // Creating a SOCKET with necessary parameters
                if (ConnectSocket == INVALID_SOCKET)
       {
                   printf("socket creation failed\n");
  free(sendbuf);
                   return 1;
                }
       else
       {
  printf("socket created\n");
       }

4) Call the connect function, passing the created socket and the sockaddr structure as parameters. Check for general errors.

Result = connect(ConnectSocket, result->ai_addr,result->ai_addrlen);    // Connect to server
                         if(Result != ZERO)
                {
                           printf("Unable to connect to server!\n");
         _getch();
          closesocket(ConnectSocket);                                        // closing the created socket
          free(sendbuf);
          return 1;
                }
                           printf("server connected\n");



THAT'S ALL NOW HERE IS THE SNIPPET FOR SENDING AND RECEIVING-COMMON FOR BOTH

        printf("\n*** For Disconnecting the Chat don't type anything,just simply press 'ENTER' ***\n"); 
while(1)
{
printf("\nCLIENT: ");
fflush(stdin);     // clear the stdin buffer
gets(sendbuf); 
int string_len=strlen(sendbuf);
Send_Result = send(ConnectSocket,sendbuf,string_len,0);        
if(Send_Result==0)
{
break;
}
Recv_Result = recv(ConnectSocket,recvbuf,MAX_LEN,0);
if(Recv_Result==0)
{
break;
}
recvbuf[Recv_Result]='\0';                                          // appending a null character
printf("\nSERVER: %s\n",recvbuf);
}
free(sendbuf);
closesocket(ConnectSocket);   
return 0;
}
NOTE:the IP is LOOP BACK 127.0.0.1 if you r running it on the same computer


OUTPUTS:

---->>1st run the server





----->client is trying to connect





NOW the client is connected you can chat



Author
Aravind A
Project Engineer

   

Saturday, 12 July 2014

Interfacing RTC DS1307 with Atmel AVR Microcontroller

Interfacing RTC DS1307 with Atmel AVR Microcontroller

         In this tutorial, the steps involved in interfacing the real time clock chip DS1307 with Atmel AVR microcontroller has been explained. Before getting into detail,

What is this RTC??

A real-time clock(RTC) basically as the name suggests are clock modules that keeps track of the current time. These RTCs are present in almost any embedded device which needs to keep accurate time. The main advantage of RTC is that they have a battery backup which keeps the clock running even in case of power failure.There are many RTC chips available in the market, but DS1307 is the one most commonly used.

Features of DS1307: 
DS1307 is serial real time clock which is I2C compatible. So before continuing this blog have a quick look at our previous post about I2C Communication to get a clear picture visit our page
This provides seconds, minutes, hour, day, date, month and year information. The end of the month is automatically adjusted which are fewer than 31 days including leap year.
The clock inside the chip supports both 24 hr and 12 hr format with AM/PM indicator.
The chip has an in-built power sense circuit which senses the power failure and switches to battery backup power.
Steps involved in Interfacing RTC with AVR controller:
The RTC DS1307 has a set of internal time keeping registers which is used to set and read time from them. They also have 58 bytes of non-volatile RAM to store information such as an alarm, event reminder something like that.


Note: As said on the DS1307 datasheet, because the initial power-on state of this bit is not defined, it is important to clear the Clock Halt (CH=0) bit in the seconds register(00H).

    2) Once the registers been properly set, we can read the time directly. One important thing is these registers don’t store the values as binary. Instead it stores all its values in Binary Coded Decimal (BCD) format. So care should be taken while writing the time into these registers.

     3) As I have already explained the protocol used in this interface is I2C.

·        RTC DS1307 à acts as I2C Slave
·        AVR controller à acts as I2C Master

     4) Writing the time into the Slave’s corresponding registers:


  • ·        In any communication normally there has to be a sender and recipient, and both should have an initial pairing only then the communication will be effective.
  • ·        This initial pairing has to be done by the master by specifying the slave address which it wants to communicate. In our case the slave address for DS1307 is a 7 bit address 1101000.

  • ·        Once the slave address is given, we have to specify whether it is a read/write operation(in our case, Write=0).
  • ·        After getting the ACK, specify the register address from where the write operation has to start.
  • ·        For every ACK, send a data to the slave. It automatically increments the address pointer so there is no need for specifying the register address each time.
      5) Reading the time from the Slave’s corresponding registers:

  • ·        For read operation, when we don’t specify the address pointer from which it has to be read, the data will start reading from the last pointed address which might not be valid.
  • ·        Hence it is advisable to specify the address pointer first before the start of any read operation.

  • ·        This could be done by writing the register address(in write mode) in order to point the address pointer to the location we need and then switching it to read mode(Read=1) by performing the repeated start operation.
  • ·        The process is same as the write operation. One thing to be noted is that the last data has to be negative acknowledged NACK in read mode.
  • ·        That’s all, the interfacing part of RTC is completed now. You can view this real time clock running in your display.
For any doubts either conceptually or in the coding side, you can contact us at embeddedunderoneroof@gmail.com

Author
Karthik

Embedded Project Engineer

Wednesday, 2 July 2014

I2C COMMUNICATION (Explanation With Diagrams)

I2C is primarily used for communication between two Integrated Chips. I2C protocol was designed by Philips. This post will help you to easily interface two IC’s using I2C protocol.
I2C is a two wire communication system where master controls the slave. The two wires are SDA and SCL. These two wires are pulled up using resistors, which forms wired AND connection between Master and Slaves.
IMPORTANT TERMS: 
SDA- Serial Data Line.
SCL- Serial Clock Line.
Master- Master is a device which take care of data transfer between IC’s by providing proper clock signal
Slave- Slave is a device where the data can be written and read.
Clock- Clock is a Periodic signal generated by the Master, the state of the clock plays a major role in STARTING, TERMINATING and SAMPLING the data.
Data- Data is also a signal where the data, either 1 or 0 is represented.
COMMUNICATION: 
What is I2C Connection?
i2c-diagram
In-order to start a communication between two IC’s they should be connected as per the I2C Protocol.
What Determines the number of Slaves in a line? 
ADDRESS LINES, based on the number of address lines number of devices can be calculated, using the formula 2 ^address lines. In this post I will explain about 7 bit addressing.
How to Initiate a Communication? 
Communication is initiated by first addressing the desired IC. The desired IC is addressed by using the device address, normally the device address will be mentioned by the manufacturer, for example Device Address of a RTC (DS1307) will be 1101000. Once identifying the device address the following procedure has to be followed.
STEPS: 
  1. Transmit the Start Bit
  2. Transmit the Device address(specifying the read or write mode).
  3. Receive the acknowledgement.
  4. Transmit the Register Address(optional).
  5. Receive the acknowledgement.
  6. Transmit the Data as per your wish.(for each byte receive an acknowledgement)
  7. Transmit the Stop Bit.
1) Transmitting the Start Bits and Stop Bits: 
Start Bit: A State know as Start Bit is generated when the data line is pulled from HIGH to LOW when the Clock is HIGH
Stop Bit: A State know as Stop Bit is generated when the data line is pulled from LOW to HIGH when the Clock is HIGH
i2c-tutorial-star-stop                                        .
note: From the above Diagram it can be inferred that it is not advisable to change the state of SDA when the clock is HIGH as it either starts or ends the connection. 
2)Transmitting the Device Address: 
Once the Start Bit is transmitted it must be followed by the device address along with the read/write bit. well, here we shall take RTC as an example. RTC mentioned above has 7bit address this seven bit address has to be transmitted serially bit by bit through SDA line.
IMPORTANT WHILE TRANSMITTING THE DATA:( The data can be device address, register address or the byte which has to be stored in the register)
  • The MSB of the byte must be sent first.
  • The state of SDA line must not be changed when the Clock signal is HIGH.
  • The State of SDA should be changed only if the state of the Clock is LOW
Once the 7 bit of address is transmitted then READ/WRITE bit has to be send. This bit determines whether the data is read from the slave or written from the slave.
  • READ - 
  • WRITE - 0 
ACKNOWLEDGEMENT: 
Once the device address is transmitted the slave has to acknowledge the user by sending the acknowledgement bit. Transmitting the device address will take 8 clock pulse , therefore in the 9th clock pulse acknowledgement must be received by the master. The Slave device will pull the SDA line to LOW to Acknowledge the data transmitted.
  • POSITIVE ACKNOWLEDGEMENT: Bit 0 is sent.
  • NEGATIVE ACKNOWLEDGEMENT: Bit 1 is sent.
3)Transmitting the Register Address: 
It is similar to the transmission of device address but it doesn`t include the READ/WRITE bit. Here the eight bit address has to be transmitted serially bit by bit through SDA line.
After transmitting it acknowledgement is received by the master.
4) Transmitting the Data as per your wish: 
The data is sent similar to the address and an acknowledgement is received after 8 bits. We can transmit N number of data and  finally conclude it with a stop bit . The register address need not be mentioned every time, the slave device can increment the address automatically. But if you need to write in a specific address or if the slave device does not increment the address you have to mention the register address.
Thus the  data is written to the slave device. then Stop Bit has to be sent as mentioned above.
READING THE DATA FROM THE IC 
  1. Transmit the Start Bit
  2. Transmit the Device address(specifying the write mode).
  3. Receive the acknowledgement.
  4. Transmit the Register Address.
  5. Receive the acknowledgement.
  6. Transmit the Start Bit again. (Repeated Start)
  7. Transmit the Device address.(specifying the read mode).
  8. Read the Data as per your wish.(Master should send acknowledgement for each byte it read)
  9. Perform the steps 1 to 6 to read the desired registers.
  10. once the reading is done master should send negative acknowledgement to the IC.
  11. Transmit the Stop Bit.
NOTE: Transmitting the start bits, stop bits, device address, register address  explained above can be used for reading the data from the IC. 
Reading the data from the IC: 
The data is read from the IC bit by bit and an acknowledgement is sent by the master to the IC after 8 bits. We can read N number of data and  finally conclude it by sending a NEGATIVE ACKNOWLEDGEMENT. The register address need not be mentioned every time, the slave device can increment the address automatically. But if you need to read from a specific address or if the slave device does not increment the address you have to mention the register address.  Thus the  data is read from the slave device. Then Stop Bit has to be sent as mentioned above to stop the communication.


The above diagram shows the start bit, transmission of device address(0xA0,WRITE mode), transmission of register address(0×0000), then transmitting the data(0×41) and finally the stop bits of EEPROM 24C256
CLOCK STRETCHING: 
While reading data from the slave, the slave might take some extra time than the one prescribed in the data sheet. In such a case the slave has the ability to hold the clock low until It puts the data in the SDA line. this process is known as CLOCK STRETCHING.
AUTHOR
Hari Prasath
Project Engineer