Skip to content

Instantly share code, notes, and snippets.

@m0n5t3r
Last active September 20, 2015 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m0n5t3r/f5fa4eab874e4b8e905b to your computer and use it in GitHub Desktop.
Save m0n5t3r/f5fa4eab874e4b8e905b to your computer and use it in GitHub Desktop.
Simpler way to do weird baud rate setting in C(++) on (whatever has asm/termbits.h - most likely just Linux) than the (non-working) method recommended by Stuck Overflow
/*
lifted from python's serial.serialposix.set_special_baudrate and made to look like C
compile with `g++ -o test_custom_baudrate test_custom_baudrate.cpp`
using 250000 to test because 3D printing people seem to love it
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <asm/termbits.h>
int main(void) {
struct termios2 options;
int rate = 250000;
int fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY);
if (ioctl(fd, TCGETS2, &options) < 0) {
printf("failed to get options\n");
return -1;
}
options.c_cflag &= ~CBAUD;
options.c_cflag |= BOTHER;
options.c_ispeed = rate;
options.c_ospeed = rate;
if (ioctl(fd, TCSETS2, &options) < 0) {
printf("unable to set baudrate %d\n", rate);
return -1;
}
printf("Success! (?)\n");
// attach a scope, see if the shortest pulse is ~ 4 us
for(int i=0; i<10; i++) {
sleep(1);
write(fd, "moo", 3);
}
close(fd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment