【问题标题】:Pyserial to interect arduino code is not functioning与arduino代码交互的Pyserial不起作用
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 请查看下方评论
    • 串行写入或读取有时不能正常工作,有时不能正常工作,当我键盘中断时,它显示以下错误:- Traceback(最近一次调用最后):文件“F:\versityproject \pythoncode\newd.py",第 39 行,在 arduinoSerial.stop() 中; TypeError: 'bool' 对象不可调用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多