I'm developing a very small program with a weight sensor connected to S0. Here is how I initialize the serial port :
stty -F /dev/ttyS0 9600 min 60 time 1 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke parenb -ixon
I have tested several manners to write to the device and then read from it :
echo IDN? >> /dev/ttyS0
read -t1 output < /dev/ttyS0 # waits for ever here.
I've also tried :
echo IDN? >> /dev/ttyS0 && read -t1 output < /dev/ttyS0 # waits too
But unsuccess. In one line, it doesn't change anything.
until read -t1 < /dev/ttyS0; do
echo IDN? > /dev/ttyS0
done
identity=$(echo $REPLY | tr -d $'\r')
This works when the device is connected.
For my tests, I did this and it worked:
$ cat /dev/ttyS0 &
[1] 9188
$ echo IDN? >> /dev/ttyS0
HBM-xxxyyyzzz$
The three manners I've tried are unsuccessful. Maybe because the device answers quicker than the bash interprets ? If it's the case, how can I dodge this to have a perfect timed answer from the device ?
What I actually am searching for, is if the device doesn't answer within 1 second, then skip the read, but if it's reading at 200ms, then continue without waiting for the 800 last ms
Opening the device in read/write mode should work.
exec 3<> /dev/ttyS0
echo "IDN?" >&3
read -t1 output <&3
Opening the file with exec
like this means the file stays open across multiple commands, rather than being opened and closed by each command.