write to device and capture response
I have a device which is /dev/ttyACM0. I can "screen" to this device screen /dev/ttyACM0
and interact with the device. I need to be able to script the sending of a simple command and capture the response. The command is simple, like type "ver" and hit return, the device responds with a numerical version value. It works in screen.
I am trying to script this in bash, and cannot seem to figure out how to make it work. stuff like echo "ver" > /dev/ttyACM0
produces nothing. I have tried print, same thing. Can someone point me at how to do this?
Solution 1:
In Unix/Linux everything is a file. Every time you echo to a device (/dev) you are opening for writing, then writing an the closing. A simple way to catch the output of a device is as simple as
tail -f /dev/ttyACM0 (-f keeps the line open)
this will cat the output and keep the device open.
As an example, in my case, I have one project that read sensors in an Arduino and in parallel send the information to a server and also the serial port.
Now, serial ttys need to match speed on the os and the device. So sometimes you do not get the output unless you have the right speed and setting. if you type in a terminal
stty /dev/ttyACM0
you will get the current speed configuration.
So, you could try something like this (but not always work)
updated ++
#!/bin/bash
input="/dev/ttyACM1" #sets the device
stty -F $input 115200 min 0
#added to initialize the line
stty -F $input -brkint -icrnl -imaxbel -opost -onlcr -isig
stty -F $input -icanon -iexten -echo -echoe -echok -echoctl -echoke
echo "ver" >>$input #send the command
tail -f $input & #reads and wait for ever
sleep 2s
killall tail #Could be an issue if other tail running
in my case that shell output this (it will no take the ver command as it is not implemented, but after that reads from the tty whatever the tty is sending). With the change tail stops earlier and output gets truncated at 2 seconds
1970-00-00-00:00:00: Init SDCard...
1970-00-00-00:00:00: SDCard Init done.
1970-00-00-00:00:00: Reading configuration...
1970-00-00-00:00:00: Done...
1970-01-01-00:00:01: IP: 192.168.22.199
Again, the -f flag keeps the terminal open but, if I take it off I get nothing (I lost the buffer output)
That is why I think a small c program will do better.
Hope this helps.