2

I have a serial device on /dev/ttyAMA0. I have program written in C that communicates with this device. But apart from the C program I sometimes need to input some configuration data from terminal, for example: echo xxx >> /dev/ttyAMA0. Problem is that the device replies to this configuration input (something like parameter xxx set) but I do not read (because I don't need to) this reply so it buffers in the serial port's buffer. This causes problems in the C program because I need to read data from it but there is already this reply buffered that I do not care about.

So my question. How do I flush device's buffer from terminal? I know I can use tcflush(sfd, TCIOFLUSH); in C but I need to do it from terminal.

1
  • 1
    You are asking the wrong question. The right question to ask is what tool you can use to speak with your device properly, since echo clearly only does half the job.
    – JdeBP
    Feb 25, 2019 at 10:23

2 Answers 2

1

I know that this answer is several years late....but a command like this should work in bash:

read garbage </dev/ttyAMA0

This line uses the bash built-in "read" command to read a single line of ASCII characters from the serial receive buffer, and store it into a variable called "garbage". The "<" redirection operator tells "read" to get its input from the serial port device file, rather than from stdin, which is the default. If you need to read more than one line of characters from the buffer, this command could be placed in a loop.

5
  • read reads one byte at a time up to a non-escaped newline character though, so if there's no newline character to be read it will hang, and if there's more data past the first newline character, it will leave it there. May 25, 2023 at 19:07
  • Also note that read is a standard sh builtin, you don't need to install bash just for that. May 25, 2023 at 19:08
  • read always reads from stdin (unless you use the -u option as supported by a few implementation including bash's to read from a different fd). </dev/ttyAMA0 it to change read's stdin to that file open in read-only mode. May 25, 2023 at 19:09
  • All very good points and clarifications. Thanks Stephane!
    – Anonymous
    May 25, 2023 at 22:55
  • You could probably use timeout with read to just absorb as much as available within that time, e.g. timeout 10 bash -c 'read -N 999999 </dev/ttyAMA0', or more simply timeout 10 cat </dev/ttyAMA0 >/dev/null. Seems better to use tcflush() as in the other answer, though. May 26, 2023 at 8:11
1

perl has an interface to tcflush() in its POSIX module:

perl -MPOSIX -e 'tcflush(0, TCIFLUSH)' < /dev/ttyAMA0

See perldoc POSIX for details.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .