Skip to main content
 首页 » 编程设计

python之与 arduino 代码交互的 Pyserial 无法正常工作

2025年05月04日69hnrainll

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

请您参考如下方法:

使用类内部的代码并实例化该类并调用方法。

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();