I'm trying to write a very simple app that sends & receives about 10 bytes
of data over a serial connection. This is to read the temperature from a
sensor connected to the serial port. I've done quite a bit of serial
programming in c/c++ on dos/windoze machines but this is my first foray into
doing it on a *nix platform. I'd like to write this in perl if possible,
but c/c++ is an alternative.
What I'm having trouble figuring out is how to set the speed, start bits,
stop bits, etc. of the serial port. This will be running on RedHat linux
6.2. I've looked at the setserial command but it doesn't seem to be quite
what I want (or is it?)... The device attached to the serial port is quite
dumb so I need to ensure the port is set at 2400/n/8/1. What's the
appropriate way of doing this, either from the linux configuration, from
c/c++, or from perl?
Thanks!
-Bruce
Hi Bruce. I've never done the type of programming you speak of here
myself, but `man ioctl` appears to provide a decent starting point.
Daniel Rall
Merry christmas...
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <syslog.h>
#define SETIOCTL
#include <stdio.h>
#include <stdlib.h>
#ifdef SETIOCTL
#include <termio.h>
#endif
#include <unistd.h>
#include <errno.h>
int open_com(char *devname, int speed) {
int fh;
struct termio ttyset;
printf("Opening garmin GPS device [%s] at speed %d bps\n", devname, speed);
if((fh=open(devname, O_RDWR|O_NOCTTY))==-1) {
fprintf(stderr, "Error %d opening %s\n", errno, devname);
return -1;
}
/* */
if (ioctl(fh, TCGETA, &ttyset) < 0) {
fprintf(stderr, "Can't get ttyset parameters from ioctl. errno %d\n", errno);
return (-1);
}
/* set baud rate for device */
switch(speed) {
case 9600 :
ttyset.c_cflag = CBAUD & B9600;
break;
default :
log(LOG_ERR, "open_comm: Unsupported serial speed %d bps\n", speed);
break;
}
/* set character size and allow to read data (added CLOCAL for no modem
control) */
ttyset.c_cflag |= (CSIZE & CS8) | CREAD | CLOCAL;
ttyset.c_iflag = ttyset.c_oflag = ttyset.c_lflag = (ushort)0;
ttyset.c_oflag = (ONLRET);
/* return if unable to set communication parameters */
if (ioctl(fh, TCSETAF, &ttyset) < 0) {
fprintf(stderr, "Unable to set comm parameters. errno %d\n", errno);
return (-1);
}
return fh;
}
--
I don't suffer from Insanity...
I enjoy every minute of it...