How to send a sequence of AT commands to a serial port in bash?

倾然丶 夕夏残阳落幕 提交于 2019-12-10 18:16:35

问题


In Linux I need to send a sequence of AT commands to a serial port on e.g. /dev/ttyS0, which has to wait for an OK answer before the next command is sent. I could imagine doing something like

echo 'AT' > /dev/ttyS0
echo 'ATS0=0' > dev/ttyS0
...

but this does not evaluate the answer from the device on that port.

Is there a very simple way to automate this within a bash script, probably with the help of socat and/or microcom but no tools which cannot found on the most simple linux system.


回答1:


If you install the PPP package you can use the chat program that comes with it. Or you can use kermit. Or the cu program that comes with uucp. But to do it with pure shell is trickier. You might be able to use the read and printf functions, with stdio redirected to the port.

some snippet:

stty -F /dev/ttyS0 38400 raw
chat -f script.txt < /dev/ttyS0 > /dev/ttyS0

Should get you started.




回答2:


Here is a very simple way to automate this within a bash script:

$ (echo AT; echo ATS0=0) | atinout - /dev/ttyS0 -
AT
OK
ATS0=0
OK
$

by using the atinout program which is written specifically with this functionality as its sole purpose. The output above is assuming ATE1; without echo the response from the modem will be "\r\n\r\nOK\r\n\r\nOK\r\n".

In the example above, atinout will send the first command AT (properly terminating the command line with \r), wait until it receives a Final Result Code (e.g. OK) and first then continue processing the next command.

You can give input from a file by specifying that instead of the first -, and if you want to capture the output give a file name instead of the last -. You can use here doc instead of grouped echo commands if you like.




回答3:


To show the messages from:

echo -e "ATHO\r" > /dev/ttyACM0

or any other modem commands type who to find the terminal number then run:

cat /dev/ttyACM0 >& /dev/pts/8 &

Then the messages from the AT command will show on your terminal.




回答4:


You have an error :

cat 'AT'

means display AT file wich not exists I guess.

Instead, try doing :

cat<<EOF>/dev/ttyS0
AT
ATS0=0

EOF

That uses shell here-doc



来源:https://stackoverflow.com/questions/14878684/how-to-send-a-sequence-of-at-commands-to-a-serial-port-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!