serial port problem is occuring,,, pls guide on the same as i new to this,,,

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
int main()
{
int fd;
int wd=0;
unsigned char buff[] = { 0x02, 0xFA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x23, 0x01, 0x21, 0x03};

fd = open("/dev/ttyS0", O_RDONLY | O_NOCTTY | O_NDELAY );
if (fd == -1)
{printf("error opening");}
else
{
printf("%d", fd);    //i get fd value to be 3
fcntl(fd, F_SETFL, 0);
wd=write(fd, buff, 13 );
}
printf("%d", wd);    //i get wd to be -1, so what is the problem??
close(fd);
}

You will have to check the value of errno to find the exact problem. From the man pages of write :

ERRORS
       EBADF  fd is not a valid file descriptor or is not open for writing.

       EINVAL fd is attached to an object which is unsuitable for writing.

       EFAULT buf is outside your accessible address space.

       EFBIG  An  attempt was made to write a file that exceeds the implemen-
              tation-defined maximum file size  or  the  process’  file  size
              limit,  or to write at a position past than the maximum allowed
              offset.

       EPIPE  fd is connected to a  pipe  or  socket  whose  reading  end  is
              closed.   When  this  happens  the  writing  process  will also
              receive a SIGPIPE signal.  (Thus, the  write  return  value  is
              seen  only  if the program catches, blocks or ignores this sig-
              nal.)

       EAGAIN Non-blocking I/O has been selected  using  O_NONBLOCK  and  the
              write would block.

       EINTR  The  call was interrupted by a signal before any data was writ-
              ten.

       ENOSPC The device containing the file referred to by fd  has  no  room
              for the data.

       EIO    A low-level I/O error occurred while modifying the inode.

       Other errors may occur, depending on the object connected to fd.

Are you opening this port as a privileged user?

@ gerad4143
yeah i m openin as a root user

guys thanks,,, it was my fault,,, i opened the port in read only mode,,,
i changed the code piece n now it doin fyn,,,,

thanks for ur kind replies,,,

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.