title: Python CGI - Sending long strings to serial port
body: <p>I have a Python CGI script on Raspberry Pi which converts the contents of a text box to 1's and 0's. I'm looking to have a string of 1000 ish max.</p>
  
  <p>The binary string is formatted slightly and sent to an arduino via the serial port... the arduino uses the data in the string to do stuff with LED's. If I cut and paste the binary string into the arduino serial monitor, all works fine, when I try to automote this via the following python code, everything starts to work but stops soon into the cycle.</p>
  
  <p>I can control how long this takes to work by altering the time.sleep(3) after the ser.write command..... but I don't want to set an unecessary long delay I would like to ensure the code waits for the string to send before moving on to printing the HTML stuff back, (and stopping the light display on the arduino).</p>
  
  <p>Having said this, the entire string MUST be getting through to the arduino as the arduino waits for '\n' at the end of the string to process it.</p>
  
  <p>Guess this must be a school boy error.... tips and pointers much appreciated. Here is the CGI code I'm using.</p>
  
  <pre><code>#!/usr/bin/python
  # Import modules for CGI handling and serial
  import cgi, cgitb, serial, time, binascii
  # Create instance of FieldStorage 
  form = cgi.FieldStorage() 
  #define serial port
  ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
  #Wait while serial connects
  time.sleep(3)
  # Get data from fields
  prayer = form.getvalue('prayer')
  # Convert to binary
  binprayer = bin(int(binascii.hexlify(prayer), 16))
  # remove the '0b' from the front end of the string
  bintrimint = binprayer[2:]
  # add a \n to the end
  bintrim = bintrimint + '\n'
  
  ser.write(bintrim)
  time.sleep(3)
  
  print "Content-type:text/html\r\n\r\n"
  print "&lt;html&gt;"
  print "&lt;head&gt;"
  print "&lt;title&gt;Binary Prayer - a test script&lt;/title&gt;"
  print "&lt;/head&gt;"
  print "&lt;body&gt;"
  print "&lt;h2&gt;You entered the following text: %s&lt;/h2&gt;" % prayer
  print "&lt;h2&gt;%s&lt;/h2&gt;" % binprayer
  print "&lt;h2&gt;%s&lt;/h2&gt;" % bintrim
  print "&lt;/body&gt;"
  print "&lt;/html&gt;"
  </code></pre>