sending hex bytes to serial in bash

Pavan K picture Pavan K · Mar 19, 2014 · Viewed 29.7k times · Source

I am able to send hec bytes to a serial port using

stty -F /dev/ttyUSB0 speed 115200 cs8 -cstopb -parenb -echo
echo -en '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' > /dev/ttyUSB0

But when I try to do this in a loop reading test from a file, it doesnt want to work

#!/bin/bash
stty -F /dev/ttyUSB0 speed 115200 cs8 -cstopb -parenb -echo
while read line
do
    name=$line
    echo -en $name | tr -d ' ' > /dev/ttyUSB0
    sleep 0.04
done < $1

I call the script like this

./sendData.sh file.txt

file.txt has some simple content like this

Try 1

\\ xFF\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00\\ x00

Try 2

\xFF\xF2\x00\xFF\xF2\x00\xFF\xF2\x00\xFF\xF2\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF

Could someone point to me what is missing.

Answer

that other guy picture that other guy · Mar 19, 2014

The problem is that read interprets escape sequences by default, effectively removing your backslashes. Make your file contain e.g. \x01\x02\x03 and use read -r:

while read -r line
do
  echo -en "$line" > /dev/ttyUSB0
done < "$1"