NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » Serial port config (unix)

April 05, 2010
by Hexorg
Hexorg's Avatar

Hello. I'm trying to write a program in c++ that would send some data (a bmp image) to the microcontroller. Should I worry about stuff like baud rate? Or do I just open /dev/ttyUSB0 and put chars in it?

April 05, 2010
by mrobbins
(NerdKits Staff)

mrobbins's Avatar

Hi Hexorg,

You definitely need to make sure the baud rate is correct before opening /dev/ttyUSB0. Check out these posts for use of the "stty" command (at least for Linux / OS X), and also some C code to set baud rates. Hopefully that will get you going in the right direction for C++. Three earlier forum threads:

  • #1 shows a OSX C program that sets baud rates
  • #2 shows a Perl script, as well as stty
  • #3 shows stty

Please post back with results!

Mike

April 06, 2010
by Hexorg
Hexorg's Avatar

I've found this little function from here:

int initport(int fd) {
    struct termios options;
    // Get the current options for the port...
    tcgetattr(fd, &options);
    // Set the baud rates to 19200...
    cfsetispeed(&options, B9600);
    cfsetospeed(&options, B9600);
    // Enable the receiver and set local mode...
    options.c_cflag |= (CLOCAL | CREAD);

    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    // Set the new options for the port...
    tcsetattr(fd, TCSANOW, &options);
    return 1;
}

You'd have to #include <termios.h>

B9600, according to the termios.h file however equals to 9600, not 19200. And it is of a type speed_t, so I think I should be able to set it to 112500 without too much hassle.

Post a Reply

Please log in to post a reply.

Did you know that you can build an analog amplifier with one transistor and a few resistors? Learn more...