我使用下面的python代码从我的MAC + XBee协调器与XBee + Arduino进行通信。但是在尝试通过串行发送数据包时,我收到端口未打开错误。
错误消息
Sending LOAD
Traceback (most recent call last):
File "xbeeTxRx.py", line 139, in <module>
main()
File "xbeeTxRx.py", line 109, in main
sendPacket(WHERE, LOADString)
File "xbeeTxRx.py", line 49, in sendPacket
data = what)
File "/Library/Python/2.7/site-packages/xbee/base.py", line 399, in send
self._write(self._build_command(cmd, **kwargs))
File "/Library/Python/2.7/site-packages/xbee/base.py", line 91, in _write
self.serial.write(frame)
File "/Library/Python/2.7/site-packages/serial/serialposix.py", line 517, in write
raise portNotOpenError
serial.serialutil.SerialException: Attempting to use a port that is not open
以下代码。一旦我添加了def main,问题就会发生。如果没有def main并且我调用sendPacket(WHERE,LOADString)那么它工作正常。
#this port address will change
PORT = '/dev/tty.usbserial-A104IC2U'
BAUD_RATE = 9600
WHERE = '\x00\x13\xA2\x00\x40\xF7\x43\xC1'
UNKNOWN = '\xff\xfe' # This is the 'I don't know' 16 bit address
dataString='LOAD'
LOADString='LOAD:T1name=-60.00&T2name=-40.00&T3name=-20.00&T4name=0.00&T5name=+20.00&T6name=+60.00'
STOPString='STOP'
packets = Queue.Queue()
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
def message_received(data):
packets.put(data, block=False)
print 'gotta packet'
def sendPacket(where, what):
zb.send('tx',
dest_addr_long = where,
dest_addr = UNKNOWN,
data = what)
print 'Sent Packet'
def sendQueryPacket():
sendPacket(WHERE, dataString)
print 'Sent Query Packet'
def handlePacket(data):
print 'In handlePacket: ',
print data['id'],
if data['id'] == 'tx_status':
print data['deliver_status'].encode('hex')
elif data['id'] == 'rx':
print data
print repr(data['source_addr_long'])
print data['rf_data']
elif data['id'] == 'rx_long_addr':
print data
print repr(data['source_addr_long'])
print data['rf_data']
else:
print 'Unimplemented frame type'
# Create XBee library API object, which spawns a new thread
zb = ZigBee(ser, callback=message_received)
def main():
print ("Sending LOAD")
#send load command
sendPacket(WHERE, LOADString)
while True:
try:
time.sleep(0.1)
if packets.qsize() > 0:
print 'packet availabe'
newPacket = packets.get_nowait()
handlePacket(newPacket)
except KeyboardInterrupt:
print("Sending STOP")
sendPacket(WHERE, STOPString)
break
zb.halt()
ser.close()
if __name__ == "__main__":
main()
答案 0 :(得分:0)
老兄你应该把zb.halt()
和see.close()
放在最后一个if语句后面,你可以打电话给你的主。