2

我们在从串口获取数据时遇到问题。我们有这个 python 代码,它的目的是从文件中获取一个值然后递增它。我们正试图用电机伺服将它连接到 arduino,这样当它检测到增量时,伺服就会移动。

#
# fetch counter 
#

import time
import urllib
import serial

# usb serial connection to arduino
ser = serial.Serial('COM3', 9600)

last_counter = open("hitcounter.txt")
for b in last_counter:
b = b.strip()
while (True):
counter = open("hitcounter.txt")
for a in counter:
    a = a.strip()

delta = int(a) - int(b)
ass = delta+1
print ass
print "counter: %s, delta: %s" % (a, delta)
x=chr(ser.write(chr(ord(chr(delta)))))
print type(x)
print "%s" %(x)
y=ser.write(ass)

print type(y)
print "%s" %(y)
b = a
time.sleep(10)
4

1 回答 1

2

在您的代码中:

while (True):

它后面的行没有缩进,所以不是代码块的一部分。您的代码将在这里简单地空闲循环。:(

假设我了解您的代码逻辑:

#
# fetch counter 
#

import time
import urllib
import serial

# usb serial connection to arduino
ser = serial.Serial('COM3', 9600)

last_counter = open("hitcounter.txt")

for b in last_counter:
    b = b.strip()

while (True):
    counter = open("hitcounter.txt")
    for a in counter:
        a = a.strip()

    delta = int(a) - int(b)
    ass = delta+1
    print ass
    print "counter: %s, delta: %s" % (a, delta)
    x=chr(ser.write(chr(ord(chr(delta)))))
    print type(x)
    print "%s" %(x)
    y=ser.write(ass)

    print type(y)
    print "%s" %(y)
    b = a
    time.sleep(10)
于 2013-03-26T20:43:13.287 回答