Pyserial to interect arduino代码无效

时间:2015-08-03 00:54:50

标签: python python-2.7 arduino pyserial

我开发了两个版本的代码来与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"

1 个答案:

答案 0 :(得分:1)

使用Class中的代码并实例化该类并调用方法。

import urllib
import sys
from time import sleep
import serial
import time

class ArduinoSerial:

    def __init__(self, port, baudRate):
        self.ser = serial.Serial(port, baudRate)
        self.stop = False
        #self.ser.open()

    def run(self):
        while not self.stop:    
            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'
            self.ser.write(counter)

            time.sleep(4)

    def stop(self):
        self.stop = True
        ser.close()
        print "safe to close"

arduinoSerial = ArduinoSerial('COM4', 9600)
try:
    arduinoSerial.run();
except KeyboardInterrupt:
    arduinoSerial.stop();
    print "Recieved Kill Command. Quitting"
    sys.exit(0)

# Just to be safe   
arduinoSerial.stop();