hi,
(on a linux system) i wrote the following code snippet to
1. write to a serial port
2. read the data that i have just written to the serial port.
the write is functioning, but the read is not.
if i use just the read (without "write", but by connecting a serial device), it is working fine.

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <string.h>  
#include <unistd.h>  
#include <fcntl.h>   
#include <errno.h>   
#include <termios.h>

int main(int argc, char *argv[])
{
char line[1024];
int chkin;
char input[1024];
int file= open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
 if(file == 0)
            {
                  perror("open_port: Unable to open       /dev/ttyS0 - ");
            }
            else
                  fcntl(file, F_SETFL, 0);
while(1)
{

printf("enter input data:\n");
scanf("%s",&input);

chkin=write(file,input,sizeof input);
if(chkin<0)
{
printf("cannot write to port\n");
}
fcntl(file, F_SETFL, FNDELAY);

chkin=read(file,line,sizeof line);
if(chkin<0)
{
printf("cannot read from port\n");
}
printf("line=%s\n",line);
/*CODE TO EXIT THE LOOP GOES HERE
*/
}
close(file);
return 0;
}

sample output:

enter input data:
fjhfgfg
cannot read from port
line=

i am using http://www.easysw.com/~mike/serial/serial.html#2_5_4 for reference.
where am i goofing up?
thanks!

Recommended Answers

All 4 Replies

Print the value of the file descriptor. When I printed the value I got -1.
One reason could be, as the article mentioned that I am unable to open the file due to lack of permissions.
Have you taken care of this issue ?

i have. i am the root user, so i had the required permissions.
in the other examples i came across, there are mentions of "configuring the port".
is this essential? reading or writing works fine separately. when i do both it isn't working.

Does the function ( read/write ) you first call in the program works and the following does not?

If so maybe you should do some procedure before attempting to do another work. I never programmed serial port before , it is just an idea :)

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.