LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Programming COM port (https://www.linuxquestions.org/questions/programming-9/programming-com-port-391852/)

-=Che=- 12-12-2005 05:48 AM

Programming COM port
 
I got problem with programming COM port with POSIX. I have one device which communicate with PC through COM port (9600, space parity, 1 stop bit, no flow control). I have already write program which communicate with device under Win32 and under Linux using low level interface. Low level interface work normal with kernel version 2.4, but work with some errors under kernel 2.6. I try to turn off serial driver, but this don’t help.
But anyway the best solution will be interface which use POSIX, because in this case there are no need to unload serial driver, reconfigure kernel, …
I write this code:

#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <iostream>

using namespace std;
int main(void)
{
int n;
int fd; /* File descriptor for the port */
char buf[200];
struct termios options;

fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd == -1) perror("open_port: Unable to open /dev/ttyS0 - ");
else
{
fcntl(fd, F_SETFL, 0);
tcgetattr(fd, &options);
cfmakeraw(&options);

// c_cflag
options.c_cflag |= CS8;
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag |= CREAD; // Enable Receiver
options.c_cflag |= CLOCAL; // Ignore modem control lines.

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

tcsetattr(fd, TCSAFLUSH, &options);
tcflush(fd, TCIOFLUSH); /**/

// Main code
buf[0]=0xA;
n = write(fd, buf, 1);
usleep(150000);
cout << "Written:" << n << '\n';
usleep (150000);
read(fd,buf,1);
cout << "Readen:" << int(buf[0]) << '\n';
close(fd);
}
}

After compiling (with -O) program write one bite to device, but don’t read any byte… (At Win32 and low level Linux I/O it works)
I had already check it many times, read lots of documentation, forums, but can’t find an error or solution to this problem…

jim mcnamara 12-12-2005 02:59 PM

Try this link for the best guide for POSIX serial programming:

http://www.easysw.com/~mike/serial/

PS: I can't see an error either, but without code tags it's really hard to read.


All times are GMT -5. The time now is 09:31 AM.