Hallo zusammen,
ich versuche über UART mit Python Data zu senden und zu empfangen. Das
Senden kalppt aber das Lesen ist immer noch fehlerhaft.
1 | import time, os, re, urllib
|
2 | import msvcrt
|
3 | import sys
|
4 | import serial
|
5 | import struct
|
6 |
|
7 | port="COM38"
|
8 | def getAndSend1(test,type):
|
9 | global port
|
10 | if type=='int' :
|
11 | value=int(test) ##casting string to int
|
12 | ba=bytearray(struct.pack("i",value))
|
13 | elif type=='float' :
|
14 | value=float(test) ##casting string to float
|
15 | ba=bytearray(struct.pack("f",value))
|
16 | else:
|
17 | print("undefined type")
|
18 | return 0
|
19 |
|
20 | ba= b'\x7E\x7E'+ba+b'\x01\x01' ##adding header and tail to the byte array
|
21 |
|
22 | print("sent: "+str([ "0x%02x" % b for b in ba])) ##print the packet before sending it
|
23 |
|
24 | ser = serial.Serial(port, 115200) ##open serial port
|
25 | while ser.isOpen()==0: ##waiting till port get open
|
26 | 1==1
|
27 | time.sleep(2)
|
28 |
|
29 | ser.write(ba) ##sending the packet
|
30 | result = ser.read(8) ##reading the serial port
|
31 | print("recieved: "+str([ "0x%02x" % r for r in result]))
|
32 | resVal=struct.unpack("f",result[2:6]);
|
33 | print(str(resVal[0])+"\n")
|
34 |
|
35 | getAndSend1(1,'int')
|
sent: ['0x7e', '0x7e', '0x01', '0x00', '0x00', '0x00', '0x01', '0x01']
Traceback (most recent call last):
File "C:\Users\User\Desktop\V4(1).py", line 35, in <module>
getAndSend1(1,'int')
File "C:\Users\User\Desktop\V4(1).py", line 31, in getAndSend1
print("recieved: "+str([ "0x%02x" % r for r in result]))
TypeError: %x format: a number is required, not str
>>>