Python CGI向serial p发送长字符串

2024-05-23 22:31:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于Raspberry Pi的Python CGI脚本,它可以将文本框的内容转换为1和0

二进制字符串被稍微格式化并通过串行端口发送到arduino。。。arduino使用字符串中的数据来处理LED。如果我将二进制字符串剪切并粘贴到arduino串行监视器中,一切正常,当我尝试通过下面的python代码自动运行时,一切都开始工作,但很快就停止了循环。在

我可以通过改变时间。睡觉(3) 在ser.写入命令。。。。。但是我不想设置一个不必要的长延迟,我希望确保代码在继续打印HTML内容之前等待字符串发送(并停止arduino上的灯光显示)。在

说到这里,整个字符串必须通过arduino,因为arduino等待字符串末尾的'\n'来处理它。在

我猜这一定是个小学生的错误。。。。建议和建议非常感谢。这是我使用的CGI代码。在

#!/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>"

Tags: the字符串代码内容timehtmlserialh2