Pyserial を使用してシリアル ポートから Bluetooth モデム経由で送信された数値を読み取ろうとしています。私は Python の初心者で、利用しようとしている良い例を見つけました。
from threading import Thread
import time
import serial
last_received = ''
def receiving(ser):
global last_received
buffer = ''
while True:
buffer = buffer + ser.read(ser.inWaiting())
if '\n' in buffer:
lines = buffer.split('\n') # Guaranteed to have at least 2 entries
last_received = lines[-2]
#If the modem sends lots of empty lines, you'll lose the
#last filled line, so you could make the above statement conditional
#like so: if lines[-2]: last_received = lines[-2]
buffer = lines[-1]
class SerialData(object):
def __init__(self, init=50):
try:
self.ser = ser = serial.Serial(
port='/dev/tty.FireFly-16CB-SPP',
baudrate=115200,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
except serial.serialutil.SerialException:
#no serial connection
self.ser = None
else:
Thread(target=receiving, args=(self.ser,)).start()
def next(self):
if not self.ser:
return 140 #return anything so we can test when Arduino isn't connected
#return a float value or try a few times until we get one
for i in range(40):
raw_line = last_received
try:
return float(raw_line.strip())
except ValueError:
print 'bogus data',raw_line
time.sleep(.005)
return 0.
def __del__(self):
if self.ser:
self.ser.close()
if __name__=='__main__':
s = SerialData()
for i in range(500):
time.sleep(.015)
print s.next()
別のプログラムでポートを開くことができ、そこからデータを送受信できます。ただし、上記のコードではポートが開かれていないようで、ターミナル ウィンドウに対して「100」を 500 回繰り返すだけですが、どこから来たのか、ポートが正しく開かない理由はわかりません。他のプログラムのようにポートを開くのに遅延はないので、開こうとしているかどうかさえわかりません。
他に何を試すべきか、またはエラーがどこにあるのかわからないので、助けを求めています。私は何を間違っていますか?