Issue
I am making a simple shell script to write and read data to serial device. I am using these commands at terminal and they are responding correctly:
echo -en '\xAA\x04\xC2' > /dev/ttyUSB0
To read I am using read:
cat -v < /dev/ttyUSB0
but when I am including this in a shell script, it is not responding. I need help regarding this. Also I want to know that when I send the write command, It should give me output in hex format but it is giving me output in this format M--*^NM-^H Also need help in this.
Solution
I would expect that your cat
statement is blocking waiting for end-of-file. It may treat your input tty as a standard terminal device, in which case it will require an end-of-file character to terminate the input (e.g, Control-D) and it could apply other processing to the input and the output. You had best familiarize yourself with the stty
command and its options (see stty man page). Try doing stty -F /dev/ttyUSB0
to see what options are set.
The easiest way of reading the input might be to read a single character at a time. You could try with the following script. This will read a single character at a time from the input until a 'q' is entered.
stty -F /dev/ttyUSB0 raw
stty -F /dev/ttyUSB0 -echo
while read -rs -n 1 c && [[ $c != 'q' ]]
do
echo "read <$c>" # Replace this with code to handle the characters read
done < /dev/ttyUSB0
If -F does not work, redirect stdin to the device.
For your output problem, I think it is working but you are seeing the characters displayed as characters and not the hex-codes. To see the hex codes (for verification testing only - I don't think you want to send the hex codes to the terminal), try:
echo -en '\xAA\x04\xC2' | od -tx1
You may also want to have raw mode set when outputting to avoid the driver changing the output characters.
Answered By - rghome Answer Checked By - Mary Flores (WPSolving Volunteer)