通过shell脚本串口控制 [英] Serial port control through a shell script

查看:1250
本文介绍了通过shell脚本串口控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发的方向控制器。我有一个开发板,与传感器(指南针)通过I2C通信。由于板是pretty限制(无OS),我开发了一个简单的程序来接收喜欢的东西:(1)得0'读取传感器的寄存器0; (2)设定为0 10'和值10设置传感器的寄存器0对于这些案件的板回报:(1)完成:10。 (寄存器0的值为10); (2)完成。; (3)错误:...在错误的情况下。有了这个,我试图建立一个shell脚本(bash)的,以便了解传感器和开发控制器发送命令和检索数据。

I am developing an orientation controller. I have a development board which communicates with the sensor (a compass) through I2C. Because the board is pretty limited (no OS), I developed a simple program to receive things like: (1) 'get 0' to read the sensor's register 0; (2) 'set 0 10' to set the sensor's register 0 with the value 10. For each of these cases the board returns: (1) 'Done: 10.' (register 0 has the value 10); (2) 'Done.'; and (3) 'error: ...' in case of error. With this, I am trying to develop a shell script (bash) to send commands and retrieve data in order to understand the sensor and develop the controller.

我的问题是与以下code:

My problem is with the following code:

# 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)通过读引起/写头和回响之间的冲突,但我不知道为什么,我对如何解决它不知道。

I guess (#1) is caused by a read/write conflict between 'head' and 'echo', but I don't know why and I have no idea on how to solve it.

另一个问题是(#2),我想用一个暂停。我已经试过类似:

Another issue is in (#2) where I would like to use a timeout. I've tried something like:

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

但我得到:超时:中止命令``庆典''与信号9 ,程序卡住

顺便说一句,前code以上执行我做初始化串口:

By the way, before the code above is executed I do initialize the serial port with:

stty -F /dev/ttyUSB0 9600 cs8 -cstopb

编辑:我不想要一个交互终端。我想利用这个程序是必要的。这个程序是控制器的必要基础(读/写传感器的寄存器),后来将在电路板上实现。

I don't want an interactive terminal. I want to use this routine as necessary. This routine is the necessary foundation of the controller (read/write sensor's registers) which later will be implemented in the board.

推荐答案

要解决(#1)我修改了程序来使用FD:

To solve (#1) I modified the routine to use a 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 = $

EDIT: To solve (#2), instead of providing the routine with timeout support I delegate that responsibility to the caller. However, in case of timeout we need to clean up. For that I've added the following after wait_pid=$!:

trap="if kill -0 $wait_pid ; then kill -TERM $wait_pid ; fi"
trap "$trap" SIGINT SIGKILL SIGTERM

这篇关于通过shell脚本串口控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆