Results 1 to 2 of 2
Hi!
I was trying to get my serial port to work by first building a simple program to write and then read data from the same port. The program will ...
- 07-18-2007 #1Just Joined!
- Join Date
- Jul 2007
- Posts
- 6
Serial programming in C
Hi!
I was trying to get my serial port to work by first building a simple program to write and then read data from the same port. The program will keep writing and reading data inside a while loop. However, a problem arises when I tried to put the initialisation of the file descriptors codes outside of the while loop. The serial port will only write and read once, and just blocks there. However, if i place the initialisation codes inside the while loop, and close() the fd whenever I write and read, the problem is gone. Nevertheless I felt that this is very inefficient and there must be something wrong with my codes (or my serial port configurations.)
Here's my codes:
Code:while(1){ int fd = open(PIC_BOARD_DEVICE_NAME, O_RDWR | O_NOCTTY | O_NDELAY); printf("----------------->PIC board fd: %d\n", fd); if (fd == -1) { printf("CANNOT OPEN FILE DESCRIPTOR.\n"); } else { fcntl(fd, F_SETFL, 0); // block serial read and write } // Initialize fd port struct termios options; tcgetattr(fd, &options); // Get the current options for the port. cfsetispeed(&options, B2400); // Set the baud rates to B2400. cfsetospeed(&options, B2400); options.c_cflag |= (CLOCAL | CREAD); // Enable the receiver and set local mode. options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; tcsetattr(fd, TCSANOW, &options); // Set the new options for the port. write(fd, &one,1); read(fd,&two,1); close(fd); }
- 07-28-2007 #2Linux User
- Join Date
- Jul 2004
- Location
- Poland
- Posts
- 368
Hello, some pointers that you might want to try:
1) What is the reason you do the F_SETFL to 0, I'm not sure if I understand your comment?
2) try using cfmakeraw() on the termios.
3) try memset'ing termios to 0 instead of calling tcgetattr
4) maybe your setup includes control lines, if so enable them (CRTSCTS)
5) for testing purposes don't enable non-blocking mode (O_NDELAY)
6) test the return values of the functions calls: write read tc* if some failed check errno.
7) try setting VTIME and VMIN options"I don't know what I'm running from
And I don't know where I'm running to
There's something deep and strange inside of me I see"


Reply With Quote