通过shell脚本控制串口

问题描述 投票:0回答:1

我正在开发一个方向控制器。我有一个通过 I2C 与传感器(罗盘)通信的开发板。因为板子非常有限(没有操作系统),我开发了一个简单的程序来接收类似的东西:(1)“get 0”读取传感器的寄存器 0; (2) 'set 0 10' 将传感器的寄存器 0 设置为值 10。对于这些情况中的每一种,电路板都会返回:(1) 'Done: 10'。 (寄存器 0 的值为 10); (2) '完成';和 (3) 'error: ...' 在出错的情况下。有了这个,我正在尝试开发一个 shell 脚本 (bash) 来发送命令和检索数据,以便了解传感器和开发控制器。

我的问题是以下代码:

# read device output in the background.
head -n 1 /dev/ttyUSB0 &
head=$!

# (#1): without the following stmt I get:
#   head: cannot open `/dev/ttyUSB0' for reading: : Protocol error
sleep 0.1

# send command to the device.
echo "get 0" > /dev/ttyUSB0

# (#2) wait for head.
while kill -0 $head 2>/dev/null ; do : ; done

我猜(#1)是由'head'和'echo'之间的读/写冲突引起的,但我不知道为什么,我也不知道如何解决它。

另一个问题是在 (#2) 中我想使用超时。我试过类似的东西:

timeout 1 bash -c "while kill -0 $head 2>/dev/null ; do : ; done"

但是我得到:

Timeout: aborting command ``bash'' with signal 9
程序卡住了。

顺便说一句,在执行上面的代码之前,我用以下代码初始化串口:

stty -F /dev/ttyUSB0 9600 cs8 -cstopb

编辑:我不想要交互式终端。我想在必要时使用这个例程。这个例程是控制器(读/写传感器的寄存器)的必要基础,稍后将在板上实现。

bash serial-port
1个回答
0
投票

为了解决(#1),我修改了例程以使用 fd:

# $1: the device filename, eg. /dev/ttyS0
# $2: number of lines to read before exit.

exec 3<>$1

head -n "$2" 0<&3 &
wait_pid=$!

cat - 1>&3

wait $wait_pid

exec 3>&-

编辑:为了解决(#2),我没有为例程提供超时支持,而是将该责任委托给调用者。但是,如果超时,我们需要清理。为此,我在

wait_pid=$!
之后添加了以下内容:

trap="if kill -0 $wait_pid ; then kill -TERM $wait_pid ; fi"
trap "$trap" SIGINT SIGKILL SIGTERM
© www.soinside.com 2019 - 2024. All rights reserved.