C program to write to the com port - RESOLVED

Paul Hamilton paulh at bdug.org.au
Thu Sep 8 17:23:15 PDT 2005


Hi,

Thanks to the patience and persistens of Giorgos, Garret and David, I now
have a *sample* program that will transmit 3 bytes of data (mini-ssc
protocol), via a serial port to a 8 channel servo controller board.  I will
continue to develop this as needed.  

DISCLAIMER:  This is being posted for archival purposes, and no doubt can
use a lot of improvement!

----------------------------------------------------------------------------
--------
/*  Name: testssc.c  
 *  compile with:  gcc testssc.c -o testssc
 *  
 *  Your serial cable should be plugged into com port 1.  
 *  You only need the pin 3 and pin 5 (DB9) plugged into the controller.
 *  The servo should be plugged into the first servo channel/port.
 *  This test program when run will move the servo from midrange, 
 *  to position 01.  This is for demonstrational use only.
 *  Tested with FreeBSD 5.4
 *  Paul Hamilton  8th Aug 2005
 */

    #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>
    // Use serial port 0  (com port 1) 
    static char *opt_comport="/dev/cuaa0";

int main(int argc, char **argv)
{
    int fd;
    struct termios options;
    unsigned char buf[4];

    // ok, lets try opening the com port
    printf("Opening Com port: %s\n\n", opt_comport);
    if((fd = open(opt_comport, O_RDWR | O_NOCTTY )) < 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(fd, &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(fd, TCSANOW, &options);

    // ok, lets transmit our 3 bytes through com port 1
    snprintf(buf,4,"%c%c%c%c",0xff,0x00,0x01,0);
    printf("buf=%x,%x,%x,%x\n", buf[0],buf[1],buf[2],buf[3]);

  if (write(fd, buf, 3) != 3)
    err(1, "write");

    close(fd);
};
----------------------------------------------------------------------------
--------

Cheers,

Paul Hamilton

PS.  I have three books on programming in C winging their way to Australia.
I have a lot to learn  :-)



More information about the freebsd-questions mailing list