From 20709c2c573cd27656aec31064aff7921a9b60f9 Mon Sep 17 00:00:00 2001 From: Cyprien Laplace Date: Sat, 5 Aug 2017 16:15:18 -0400 Subject: [PATCH] Flush serial port input first There can be few characters in the serial port buffer. Draining them before attempting synchronization avoids synchronization issues. --- isp_commands.c | 3 +++ isp_utils.c | 14 ++++++++++++++ isp_utils.h | 1 + 3 files changed, 18 insertions(+) diff --git a/isp_commands.c b/isp_commands.c index 00a4578..5168f36 100644 --- a/isp_commands.c +++ b/isp_commands.c @@ -117,6 +117,9 @@ int isp_connect(unsigned int crystal_freq, int quiet) snprintf(freq, 8, "%d\r\n", crystal_freq); + /* Flush input (previously buffered garbage) */ + isp_serial_flush_input(); + /* Send synchronize request */ if (isp_serial_write(SYNCHRO_START, strlen(SYNCHRO_START)) != strlen(SYNCHRO_START)) { printf("Unable to send synchronize request.\n"); diff --git a/isp_utils.c b/isp_utils.c index 7592a77..c5cc4e9 100644 --- a/isp_utils.c +++ b/isp_utils.c @@ -165,6 +165,20 @@ int isp_serial_write(const char* buf, unsigned int buf_size) return count; } +void isp_serial_flush_input() +{ + int nb; + char unused; + do { + nb = read(serial_fd, &unused, 1); + } while (nb > 0); + if (nb == 0) { + printf("serial_read: end of file !!!!\n"); + } else if ((errno != EAGAIN) && (errno != EWOULDBLOCK)) { + perror("Serial read error"); + } +} + static char next_read_char = 0; void isp_serial_empty_buffer() { diff --git a/isp_utils.h b/isp_utils.h index 21b08ea..6c488bd 100644 --- a/isp_utils.h +++ b/isp_utils.h @@ -45,6 +45,7 @@ void isp_dump(const unsigned char* buf, unsigned int buf_size); */ int isp_serial_open(int baudrate, char* serial_device); void isp_serial_close(void); +void isp_serial_flush_input(void); /* Simple write() wrapper, with trace if enabled */ int isp_serial_write(const char* buf, unsigned int buf_size); -- 2.43.0