C program to write to the com port

Paul Hamilton paulh at bdug.org.au
Sun Jul 31 14:50:29 GMT 2005


I am trying to write a C program that will send 3 bytes to the cuaa0 com
port at 9600 baud, 8n1.  I am trying to control a Northlight 8 Channel Servo
motor controller:

Most of the code came from this page:

Here is what I have so far:-

    #include <sys/time.h>
    #include <sys/ioctl.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <termios.h> /*Originally it was termio.h*/
    #include <stdio.h>
    #include <unistd.h>
    static char *opt_comport="/dev/cuaa0";

int main(int argc, char **argv)
    int n;
    int dcf_dev;
    int sdata =  0xFF0090;  // sync byte, address, servo value to be sent to
the Servo Controller
    struct termios options;

    // ok, lets try opening the com port
    printf("Opening Com port: %s\n\n", opt_comport);
    if((dcf_dev = open(opt_comport, O_RDWR | O_NOCTTY | O_NDELAY)) < 0) 
         printf("Problems opening %s\n", opt_comport);
         return (-1);
    // set the required com port parrameters
    options.c_cflag &= ~CSIZE;  /* Mask the character size bits */
    options.c_cflag |= CS8;     /* Select 8 data bits */
    options.c_cflag &= ~PARENB; // set no parity
    options.c_cflag &= ~CSTOPB; // set 1 stop bit
    options.c_oflag &= ~OPOST;  // Raw output

    tcgetattr(dcf_dev, &options);

     * Set the baud rates to 9600...
    cfsetispeed(&options, B9600);
    cfsetospeed(&options, B9600);

     * Enable the receiver and set local mode...
    options.c_cflag |= (CLOCAL | CREAD);

     * Set the new options for the port...
    tcsetattr(dcf_dev, TCSANOW, &options);

    // ok, lets transmit our 3 bytes to com port 1
    n = write(dcf_dev, &sdata, 3);
    if (n < 0)
    fputs("write() of 3 bytes failed!\n", stderr);
    printf("Output status: %d bytes written out\n", n);


Now I am just a beginner at C code, so I feel pretty good getting this far
(hey, it compiles :-)  However, a miss is as good as a mile, and so it
doesn't work :-(   Having said that, I have a serial port LED breakout
device watching, and I can see a blip on the TX line when I run the compiled
program.  This is just meant to be test code, i.e.. Get it working before
cleaning it up etc :-)

I have tried connecting the computers serial port to another one, running:
'cu -s 9600 -l cuaa0' but I don't see anything.  Having said that, I don't
see anything if I run the same on the other PC (yes, the TX-RX lines are
swapped over), so maybe that is a problem with my serial cable between the
two computers.

The Servo Controller only needs two wires:  signal ground and TX  so not
much to go wrong there, and as I said above, I do see a blip on the TX LED
when I run the program.


1. Am I really sending the data correctly at 9600baud, 8n1?

2. Am I really sending the hex bytes:  FF 00 90  out (or am I sending an
pointer address)?

3. What am I missing?



Paul Hamilton

More information about the freebsd-questions mailing list