简体   繁体   中英

Python CGI - Sending long strings to serial port

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.

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.

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).

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.

Guess this must be a school boy error.... tips and pointers much appreciated. Here is the CGI code I'm using.

#!/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 "<html>"
print "<head>"
print "<title>Binary Prayer - a test script</title>"
print "</head>"
print "<body>"
print "<h2>You entered the following text: %s</h2>" % prayer
print "<h2>%s</h2>" % binprayer
print "<h2>%s</h2>" % bintrim
print "</body>"
print "</html>"

I had a look at http://pyserial.sourceforge.net/pyserial_api.html

 write(data)
    Parameters: data – Data to send.
    Returns: Number of bytes written.

I think you should make sure you write everything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM