【发布时间】:2017-06-01 10:22:08
【问题描述】:
我有问题。我有 2 个硬件(类似于 pi),我正在尝试通过它们之间的串行电缆测试通信。两者都是基于 linux 的,但工具有限。我写了一个脚本来发送和接收文件。当我发送一个带有一些文本的 txt 文件时,一切正常。当我尝试发送二进制文件时,数据不一样,有时我得到更大的文件,有时更小,有时只是改变了一些字节。我想了好几个小时为什么会发生这种情况,我将设备设置为raw 模式(用于二进制文件)...
这是我写的脚本:
#!/bin/bash
FILE=$2
send()
{
if [ ! -f $FILE ]; then
echo "File $2 doesn not exist, please introduce a valid file"
fi
content=`cat "$FILE"` #Dump the file content into variable
echo -E "$content" > /dev/ttyO5 #send the whole content to the other device
}
receive()
{
if [ -f $FILE ]; then
echo "The file already exists. Do you want to overwrite it? (y/n
read opc
if [ "$opc" == "n" ]; then
exit 1
fi
rm "$FILE"
fi
while read -t 5 -r -n 1 c; do # read char by char -r to avoid backslashes to be scaped
echo -E -n "$c" >> $FILE # append char on file -n(to avoid creation of new lines and -E to avoid interpretation of backslashes.
done < /dev/ttyO5
}
case $1 in
's')
send
;;
'r')
receive
;;
*)
echo "Usage $0 [s | r] [FILE]"
;;
esac
要将设备置于raw 模式,我使用stty -F /dev/ttyO5 raw,这是设备的选项:
speed 9600 baud;stty: /dev/ttyO5
line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>;
eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;
werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 hupcl -cstopb cread clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon
-ixoff -iuclc -ixany -imaxbel -iutf8
-opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0
ff0
-isig -icanon iexten -echo -echoe echok -echonl -noflsh -xcase -tostop -echoprt
echoctl echoke
我的想法告诉我,在解释某些字符时存在问题,并且可能会通过更改上述某些选项来解决问题。我尝试了几个,但我无法让它工作。如果有人看到我没有看到的东西,我将不胜感激。
问候
编辑:发现问题但未解决。阅读和猫不喜欢字符NULL 和\n。我怎么能读懂这 2 个字符?
【问题讨论】:
-
这里的问题是您试图通过 catting 文件发送数据。如果文件是二进制文件,catting会导致垃圾输出。
-
考虑使用类似that
-
@RamanSailopal 我不认为这是问题所在。我尝试从文件中读取每个字节的字节,并得到相同的输出。我像这样使用它
while IFS= read -r -n 1 c;do echo -n "$c" >> /dev/ttyO5 done < "$FILE"
标签: linux bash serial-port embedded