Skip to content

Instantly share code, notes, and snippets.

@dmikushin
Created February 20, 2021 10:25
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 dmikushin/dc77da2abdc82d180834dde303cdabdc to your computer and use it in GitHub Desktop.
Save dmikushin/dc77da2abdc82d180834dde303cdabdc to your computer and use it in GitHub Desktop.
Intercept the U-boot sequence by casting ctrl+u programmatically as early as possible
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#define error_message(...) fprintf(stderr, __VA_ARGS__)
static int set_interface_attribs(int fd, int speed, int parity)
{
struct termios tty;
if (tcgetattr(fd, &tty) != 0)
{
error_message("error %d from tcgetattr\n", errno);
return -1;
}
cfsetospeed(&tty, speed);
cfsetispeed(&tty, speed);
tty.c_cflag =(tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
// disable IGNBRK for mismatched speed tests; otherwise receive break
// as \000 chars
tty.c_iflag &= ~IGNBRK; // disable break processing
tty.c_lflag = 0; // no signaling chars, no echo,
// no canonical processing
tty.c_oflag = 0; // no remapping, no delays
tty.c_cc[VMIN] = 0; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
tty.c_cflag |=(CLOCAL | CREAD);// ignore modem controls,
// enable reading
tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
tty.c_cflag |= parity;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CRTSCTS;
if (tcsetattr(fd, TCSANOW, &tty) != 0)
{
error_message("error %d from tcsetattr\n", errno);
return -1;
}
return 0;
}
static void set_blocking(int fd, int should_block)
{
struct termios tty;
memset(&tty, 0, sizeof tty);
if (tcgetattr(fd, &tty) != 0)
{
error_message("error %d from tggetattr\n", errno);
return;
}
tty.c_cc[VMIN] = should_block ? 1 : 0;
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
if (tcsetattr(fd, TCSANOW, &tty) != 0)
error_message("error %d setting term attributes\n", errno);
}
static const char *portname = "/dev/ttyUSB0";
// The value of ctrl+u key sequence, according to
// https://en.wikipedia.org/wiki/ASCII#Control_code_chart
static const char value = 21;
int main()
{
int fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
error_message("error %d opening %s: %s\n", errno, portname, strerror(errno));
return -1;
}
set_interface_attribs(fd, B115200, 0); // set speed to 115,200 bps, 8n1(no parity)
set_blocking(fd, 0); // set no blocking
while (1)
write(fd, &value, sizeof(value));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment