【发布时间】:2015-08-03 00:54:50
【问题描述】:
我开发了两个版本的代码来与 arduino 交互。版本 1:-
import urllib
import sys
from time import sleep
import serial
import time
ser = serial.Serial('COM4', 9600)
#ser.open()
while True:
sock = urllib.urlopen('http://pro*******.com')
htmlSource = sock.read()
z = str(htmlSource)
l = z[0] + z[1]
sock.close()
print l
if l == 'On':
counter = '1'
else:
counter = '0'
ser.write(counter)
time.sleep(4)
ser.close()
print "safe to close"
这个问题是当我关闭程序时,它会继续运行串行端口,所以如果我想再次使用它,请重新启动我的电脑。所以我开发了另一个版本来使用 keybordinterupt 但对于这个串行写入功能不起作用。我不知道我的代码有什么问题。有没有人可以帮我解决这个问题? 版本 2:
import urllib
import sys
from time import sleep
import serial
import time
ser = serial.Serial('COM4', 9600)
try:
while True:
sock = urllib.urlopen('http://pro*******.com')
htmlSource = sock.read()
z = str(htmlSource)
l = z[0] + z[1]
sock.close()
print l
print "Please enter CTL+C to stop"
if l == 'On':
ser.write('1')
else:
ser.write('0')
time.sleep(4)
except KeyboardInterrupt:
pass
ser.close()
print "safe to close"
【问题讨论】:
标签: python python-2.7 arduino pyserial