1.11M Members

between write and read:serial port.

 
0
 

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!

 
0
 

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 ?

 
0
 

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.

 
0
 

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 :)

Question Answered as of 4 Years Ago by abhimanipal and Tellalca
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: