通过串行端口从Velleman k8090读取和写入数据,不使用Python 3
各位, 我有一个Velleman k8090中继板,我试图从中读取和写入一些数据(我在下面的链接中找到了代码源:)。 我可以用python-2.x做得很好,但是当我切换到python-3.x时,它在linux(ubuntu)和windows(10)上都不再工作了。 它没有显示一些错误或类似的内容,但继电器没有切换。我认为它并没有执行(读或写)正确的假设。Python3在读/写过程中出现了一些错误,我不明白。请帮忙! 下面是我的python代码和终端输出 代码通过串行端口从Velleman k8090读取和写入数据,不使用Python 3,python,arrays,python-3.x,serial-port,port,Python,Arrays,Python 3.x,Serial Port,Port,各位, 我有一个Velleman k8090中继板,我试图从中读取和写入一些数据(我在下面的链接中找到了代码源:)。 我可以用python-2.x做得很好,但是当我切换到python-3.x时,它在linux(ubuntu)和windows(10)上都不再工作了。 它没有显示一些错误或类似的内容,但继电器没有切换。我认为它并没有执行(读或写)正确的假设。Python3在读/写过程中出现了一些错误,我不明白。请帮忙! 下面是我的python代码和终端输出 代码 #!/usr/bin/python3
#!/usr/bin/python3
import serial
import time
# Source: https://stackoverflow.com/questions/17862862/python-read-data-via-serial-port-from-velleman-k8090
# https://iot4beginners.com/how-to-read-and-write-from-serial-port-using-raspberry-pi/
COM_PORT = 'COM4'
class Velleman8090:
def __init__(self, port=COM_PORT):
self.port = port
self.baud_rate = 19200
self.data_bits = serial.EIGHTBITS
self.parity = serial.PARITY_NONE
self.stop_bits = serial.STOPBITS_ONE
self.flow_control = False
def open_device(self):
self.talk = serial.Serial(self.port, self.baud_rate, self.data_bits, self.parity, self.stop_bits, timeout=0.5, write_timeout=2)
print("open")
def firmware_version(self):
cmd = 0x11
mask = 0xff
param1 = 0x00
param2 = 0x00
#data = b'\x04P\x11\xff\x00\xa8\x0f'
#data = bytearray(b'\\x04\\x11\\xff\\x00\\x00\\xec\\x0f')
data = packet(cmd, mask, param1, param2)
print(data)
self.talk.flush()
self.talk.write(data.encode())
print("correct")
output = self.talk.read(7)
print (output)
output = output.encode('hex') #converts the strange characters to hex
output = output.hex() # Python 3
print (output)
def close_device(self):
self.talk.close()
print("close")
def chksum(cmd,msk,p1,p2):
checksum = (((~(0x04 + cmd + msk + p1 + p2)) + 0x01) & 0xff)
print("checksum %s" % (hex(checksum)))
return checksum
def packet(cmd,msk,p1,p2):
print("packet")
return str(bytearray([0x04, cmd, msk, p1, p2, chksum(cmd, msk, p1, p2), 0x0f]))
def main():
vm8090 = Velleman8090()
vm8090.open_device()
vm8090.firmware_version()
vm8090.close_device()
if __name__ == "__main__":
main()
终端输出(窗口外壳)
PS C:\Users\atc\Desktop> python .\testVellman.py
open
packet
checksum 0xec
bytearray(b'\x04\x11\xff\x00\x00\xec\x0f')
correct
b''
close
PS C:\Users\atc\Desktop>