|
Serial port reads
Hi there,
You don't show the open or read code - but what you do show looks OK.
It's a while since I wrote any serial port stuff, but I've hacked up some code that works here - It too is based on the SerialPortHowTo examples.
I allow the read to return - even if it has nothing - but loop until it does.
One possibility is that your external device is not behaving as
you expect. If you have the hardware perhaps you could try this:
A serial cable connecting 5 to 5, 2 to 3 and 3 to 2.
Both connectors also have 7 & 8 linked - and 4 & 6 linked. (null modem)
First run two copies of minicom or GTKterm etc. You should be able to type in one and see the characters in the other.
Now replace one of the terminals with the code below.
It should show the characters typed and stop when you send ^C.
Finally replace the other terminal with your device and see if you
get anything from it.
Good luck!
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_PORTS 5
#define SERIAL_PORT1 "/dev/ttyS0"
#define SERIAL_PORT2 "/dev/ttyS1"
#define SERIAL_PORT3 "/dev/ttyS2"
#define SERIAL_PORT4 "/dev/ttyUSB0"
#define SERIAL_PORT5 "/dev/ttyUSB1"
#define BAUDRATE B1200
char *SerialDevices[] = { SERIAL_PORT1, SERIAL_PORT2, SERIAL_PORT3, SERIAL_PORT4, SERIAL_PORT5};
static struct termios orig, new;
int main(int argc, char * argv[])
{
int tmp, port;
int res;
int fd;
char buf[50];
char rxch, *ptr;
struct termios oldtio,newtio;
char *DeviceName;
if(argc < 2) {
printf("Usage %s n Serial port to use.\n", argv[0]) ;
exit(0);
}
tmp = atoi(argv[1]);
if((tmp >= NUM_PORTS) || (tmp < 0)) tmp = 0;
port = tmp;
DeviceName = SerialDevices[port];
printf("Using %s\n", DeviceName);
fd = open(DeviceName, O_RDWR | O_NOCTTY);
if(fd < 0) { printf("Can't open %s\n",DeviceName); exit(-1); }
tcgetattr(fd,&oldtio); /* save current port settings */
bzero(&newtio, sizeof(newtio));
newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
/* set input mode (non-canonical, no echo,...) */
newtio.c_lflag = 0;
newtio.c_cc[VTIME] = 0; /* inter-character timer unused. Non zero value t here means the rd returns after t * 100ms */
newtio.c_cc[VMIN] = 0; /* No minimum number of chars - the read may return with nothing */
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
// fcntl(fd, F_SETFL, FNDELAY);
printf("Port %s set up\n", DeviceName);
do {
res = read(fd,buf,1); /* returns # of chars input */
if(res > 0) {
printf("Got %d bytes\n", res);
ptr = buf;
}
if(res < 0) {
// printf("Serial port read error\n");
res = 0;
}
while(res)
{
rxch = *ptr++;
res--;
rxch &= 0x7f;
if(rxch == 3)
{
printf("\n Quiting\n");
tcsetattr(fd,TCSANOW,&oldtio); // Restore serial port settings
exit(0);
}
if((rxch >= ' ') && (rxch < 0x7f)) printf("%c\n", rxch);
}
} while(1);
}
|