Aircraft
Aircraft

Reputation: 295

Shell script to write and read data from serial communication

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:

To write I am using:

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.

Upvotes: 3

Views: 20518

Answers (2)

m00ny
m00ny

Reputation: 1

I've found another method I'd like to share:

echo "blabla" > /dev/ttyx & answer=$(head -n1 /dev/ttyx)

The & puts the transfer from echo to the port immediately in the background, while head waits until it gets one line as an answer, which is then put into a variable.

Upvotes: 0

rghome
rghome

Reputation: 8819

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.

Upvotes: 4

Related Questions