title: Serial port control through a shell script
body: <p>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.</p>
  
  <p>My problem is with the following code:</p>
  
  <pre><code># read device output in the background.
  head -n 1 /dev/ttyUSB0 &amp;
  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" &gt; /dev/ttyUSB0
  
  # (#2) wait for head.
  while kill -0 $head 2&gt;/dev/null ; do : ; done
  </code></pre>
  
  <p>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.</p>
  
  <p>Another issue is in (#2) where I would like to use a timeout. I've tried something like:</p>
  
  <pre><code>timeout 1 bash -c "while kill -0 $head 2&gt;/dev/null ; do : ; done"
  </code></pre>
  
  <p>But I get: <code>Timeout: aborting command ``bash'' with signal 9</code> and the program gets stuck.</p>
  
  <p>By the way, before the code above is executed I do initialize the serial port with:</p>
  
  <pre><code>stty -F /dev/ttyUSB0 9600 cs8 -cstopb
  </code></pre>
  
  <p>EDIT: 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.</p>