LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Enterprise (http://www.linuxquestions.org/questions/linux-enterprise-47/)
-   -   Unable to read data from Serial port (http://www.linuxquestions.org/questions/linux-enterprise-47/unable-to-read-data-from-serial-port-907837/)

tanu1985 10-12-2011 05:28 PM

Unable to read data from Serial port
 
I am new to the linux.I have written a program in c/C++ to communicate with a device through serial port.This program is not able to read data from serial port.
I tried to connect the device using minicom and it seems to working fine.

Here is the program:-

#include <stdio.h>

#include <iostream>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
using namespace std;
int fd1;
int fd2;
string string_f;
//char *buff,*buffer,*bufptr;
char *buff;
int wr,rd,nbytes,tries;
const int MAXDATASIZE = 512;
// std::vector<char> m_vRequestBuf;
char buffer[MAXDATASIZE];
int totalBytes = 0;
//struct termios port_settings;
int configure_port(int fd);
int main()
{
fd1=open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd1 == -1 )
{
perror("open_port: Unable to open /dev/ttyS0 – ");
}
else
{
fcntl(fd1, F_SETFL,0);
printf("Port 1 has been successfully opened and %d is the file description\n",fd1);
fd1 = configure_port(fd1);
printf("Port Configured \n");// apply the settings to the port
}
printf("Start Writing... \n");
wr = write(fd1,"SFC\r",4);
if (wr < 0)
printf("no bytes written \n");
else
printf("bytes written %d \n" ,wr );
fcntl(fd1, F_SETFL, FNDELAY);
for(int i=0;i<10;i++)
{
rd=read(fd1,buffer,MAXDATASIZE);
if(rd > 0)
{
string_f+= buffer;
cout << "charsRead" << rd << endl;
//Sleep for some time and read again
}
usleep(100);
}

close(fd1);
return 0;
}
int configure_port(int fd) // configure the port
{
struct termios port_settings; // structure to store the port settings in
tcgetattr(fd, &port_settings);
cfsetispeed(&port_settings, B9600); // set baud rates
cfsetospeed(&port_settings, B9600);
port_settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits
port_settings.c_cflag &= ~CSTOPB;
port_settings.c_cflag &= ~CSIZE;
port_settings.c_cflag |= CS8;
port_settings.c_cflag &= ~CRTSCTS;
port_settings.c_cflag |= (CLOCAL | CREAD);
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &port_settings);
return(fd);
} //configure_port

harry edwards 10-12-2011 05:44 PM

What result do you get from running the program? Also, have you tried flushing the port after the write to ensure the data is sent, as I've have problems with data being held in local data buffers until the port if flushed?

tanu1985 10-12-2011 06:05 PM

I increased the sleep time and now it's working fine.


All times are GMT -5. The time now is 12:19 PM.