Skip to content

Instantly share code, notes, and snippets.

@akostadinov
Created April 14, 2025 23:18
Show Gist options
  • Save akostadinov/7691130547671150e1d74a80f1a793a0 to your computer and use it in GitHub Desktop.
Save akostadinov/7691130547671150e1d74a80f1a793a0 to your computer and use it in GitHub Desktop.
Open Serial port and select DTR/RTS pins high/low
# LICENSE: MIT
# WARN: AI tool assisted
# INFO: seems like on my USB controller both are high while port open, then low.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
int main(int argc, char *argv[]) {
if (argc != 4) {
fprintf(stderr, "Usage: %s <device> <RTS|DTR> <on|off>\n", argv[0]);
return EXIT_FAILURE;
}
// Determine control line
int line;
if (strcmp(argv[2], "RTS") == 0) {
line = TIOCM_RTS;
} else if (strcmp(argv[2], "DTR") == 0) {
line = TIOCM_DTR;
} else {
fprintf(stderr, "Invalid control line\n");
return EXIT_FAILURE;
}
// Determine operation
unsigned int cmd;
if (strcmp(argv[3], "on") == 0) {
cmd = TIOCMBIS;
} else if (strcmp(argv[3], "off") == 0) {
cmd = TIOCMBIC;
} else {
fprintf(stderr, "Invalid state\n");
return EXIT_FAILURE;
}
// Open device
int fd = open(argv[1], O_RDWR | O_NOCTTY);
if (fd == -1) {
perror("Open failed");
return EXIT_FAILURE;
}
// Execute control operation
if (ioctl(fd, cmd, &line) == -1) {
perror("Control failed");
fprintf(stderr, "See https://tldp.org/HOWTO/Serial-HOWTO-16.html");
close(fd);
return EXIT_FAILURE;
}
usleep(200000000);
close(fd);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment