sending hex bytes to serial in bash

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.

Answers


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"

Need Your Help

Get line number from file snippet

java eclipse rcp emf

I want to mark an EObject in a file with IMarker. All I can use is a unique identifier which occurs as part of a line.