[PLUG] Serial Communication Code.

Suraj Swami suraj.g.swami at gmail.com
Thu Jun 25 14:38:13 IST 2009


I am having problems in writing a simple serial communication code in linux.
I want to send single charector on the serial port which my hardware will
receive and execute.
Here is the code.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

#define BAUDRATE B9600
#define MODEMDEVICE "/dev/ttyS0"
#define _POSIX_SOURCE 1 /* POSIX compliant source */
#define FALSE 0
#define TRUE 1

volatile int STOP=FALSE;

        int fd,c, res;
        struct termios oldtio,newtio;
        char buf[255];

        fd = open(MODEMDEVICE, O_RDWR | O_NDELAY );
        if (fd <0) {perror(MODEMDEVICE); exit(-1); }

        tcgetattr(fd,&oldtio); /* save current port settings */

        bzero(&newtio, sizeof(newtio));
        newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
        newtio.c_iflag = IGNPAR;
        newtio.c_oflag = OPOST;

        /* set input mode (non-canonical, no echo,...) */
        newtio.c_lflag = 0;

        cfsetispeed(&newtio, B9600);
        cfsetospeed(&newtio, B9600);

        newtio.c_cc[VTIME]    = 0;   /* inter-character timer unused */
        newtio.c_cc[VMIN]     = 0;   /* blocking read until 5 chars received


    printf("1\n"); // This is to test where the code has reached.

    tcflow(fd, TCOON );
    tcflush(fd, TCIFLUSH);
    tcflush(fd, TCOFLUSH);


   strcpy(buf,"82345\n") ;



  printf("Work done\n");

 // I never got to see "work done" in the output. The terminal would hang .
If I removed write(fd,buf,1)  then work done would print but then my main
purpose of the program is lost. It even worked for  write(1,buf,1) . So I
guess the problem is with write(fd,buf,1)



I had one more observation. When I tried to open proc folder it would not

Please suggest. Am I missing in some configuration for the output.

I am using ret hat ver 5.0 its a pentium processor. The hyper-terminal is
working in windows very well.

Suraj Swami,
suraj.g.swami at gmail.com

More information about the Plug-mail mailing list