Friday, November 13, 2009

COM/Serial communication in C

This program will help you to understand how to do serial communication in C.
The C program will illustrate the basics of serial communication.


/////////////////////////////////////////////////
// Serial port interface program //
/////////////////////////////////////////////////

#include < stdio.h > // standard input / output functions
#include < string.h > // string function definitions
#include < unistd.h > // UNIX standard function definitions
#include < fcntl.h > // File control definitions
#include < errno.h > // Error number definitions
#include < termios.h > // POSIX terminal control definitionss
#include < time.h > // time calls
#include < stdlib.h >
#include < sys/types.h >
#include < netinet/in.h >
int fd;
int open_port(void)
{
int fd; // file description for the serial port

fd = open("COM2", O_RDWR);

if(fd == -1) // if open is unsucessful
{
perror("open_port: Unable to open /dev/ttyS0 - ");
}
else
{
printf("Opened %d\n",fd);
}

return(fd);
}

int configure_port(int fd) // configure the port
{
struct termios oldtio,port_settings; // structure to store the port settings in
tcgetattr(fd,&oldtio);
//cfsetispeed(&port_settings, B115200); // set baud rates
//cfsetospeed(&port_settings, B115200);

bzero (&port_settings, sizeof (port_settings));
port_settings.c_cflag = B115200 | CLOCAL | CREAD;
port_settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits 8N1
port_settings.c_cflag &= ~CSTOPB;
port_settings.c_cflag &= ~CSIZE;
port_settings.c_cflag |= CS8;
port_settings.c_iflag = IGNPAR | ICRNL;
port_settings.c_oflag = 0;
port_settings.c_lflag &= ~ICANON;
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&port_settings);
return(fd);
}

int query_modem(int fd) // query modem with an AT command
{

int k=0;
char str[5];
str[0]=2;
str[1]=str[2]='f';
str[3]=str[4]=3;
k=write(fd,str,strlen(str)); // send an AT command followed by a CR
printf("command %d\n",k);

}
int dsadas()
{
printf("In fm");
int bytesRead;
char *str;
char *buff;
//str=(char *)malloc(100*sizeof(char));
//buff=(char *)malloc(1024*sizeof(char));
while(1)
{

//printf("In while");
if(read(fd,str,10)>0)
{
printf("in if");
buff="";
printf("yesyeysyes %s\n",str);
//strcpy(buff,str);
do
{
//sleep(100);
//append
printf("Buffer = %s",buff);
strcat(buff,str);
bytesRead=read(fd,str,10);
}while(bytesRead>0);
//send bytes to ip
printf("Buffer = %s",buff);
}
}
}

int main(void)
{
pthread_t thread1,thread2;
fd = open_port();
configure_port(fd);
query_modem(fd);
int iret1, iret2;
//iret1 = pthread_create( &thread1, NULL, dsadas);
//pthread_join(thread1, NULL);
return(0);
}

No comments: