Найти - Пользователи
Полная версия: PySerial: Write не отправляет строку.
Начало » Центр помощи » PySerial: Write не отправляет строку.
1
Cukerman
Добрый день. Помогите начинающему, необходимо отправить строку hex “33 98 50 56 09 09 09 11 21 00 00 6e ” в неизменом виде в порт. Как её коректно преобразовать?
Python 3.10 ругает так:

TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq))
TypeError: unicode strings are not supported, please encode to bytes: ‘33985056090909112100006e’


 import serial
ser = serial.Serial (port='COM1',baudrate=9600, parity=serial. PARITY_NONE, stopbits=serial. STOPBITS_ONE, bytesize=serial.EIGHTBITS,timeout=0)
dtr_string1 ="33 98 50 56 09 09 09 11 21 00 00 6e"
print(dtr_string1)  
s_string1 = dtr_string1.replace(" ", "")
print(s_string1)
ser.write(s_string1)
print(s_string1)
ser.close
py.user.next
  
>>> text = '33 98 50 56 09 09 09 11 21 00 00 6e'
>>> 
>>> arr = bytearray.fromhex(text.replace(' ', ''))
>>> arr
bytearray(b'3\x98PV\t\t\t\x11!\x00\x00n')
>>> 
>>> arr[0], hex(arr[0])
(51, '0x33')
>>> arr[1], hex(arr[1])
(152, '0x98')
>>>
Cukerman
спасибо. НО в таком случае.
 ser.write(hex(arr[11]))
ошибка
raise TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq))
TypeError: unicode strings are not supported, please encode to bytes: ‘0x6e’
хотя print(hex(arr))
выводит >> 0x6e
py.user.next
  
ser.write(arr)
Cukerman
Спасибо, Работает! Осталось понять как переменную n в шестнадцатеричнном виде добавить в конец массива
#arr.extend(bytearray.fromhex(str(num)))
#arr.append(numH)

 >>> n = 11
>>> print (n)
11
>>> print (type(n))
<class 'int'>
>>> m=str(n)
>>> print (type(m))
<class 'str'>
>>> bytearray.fromhex(m)
bytearray(b'\x11')
>>> h=hex(n)
>>> print (type(h))
<class 'str'>
>>> print (h)
0xb
>>> bytearray.fromhex(h)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: non-hexadecimal number found in fromhex() arg at position 1
py.user.next
Cukerman
Осталось понять как переменную n в шестнадцатеричнном виде добавить в конец массива
  
>>> arr = bytearray(b'3\x98PV\t\t\t\x11!\x00\x00n')
>>> 
>>> arr.append(0x11)
>>> arr.append(17)
>>> arr.extend(b'\x11')
>>> arr.extend([0x11])
>>> arr += b'\x11'
>>> arr += bytes([0x11])
>>> 
>>> arr
bytearray(b'3\x98PV\t\t\t\x11!\x00\x00n\x11\x11\x11\x11\x11\x11')
>>>
Cukerman
Спасибо, старший брат!
п.с. А я изобретал костыль для Питона, arr.append(17) сам конвертит как нужно.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB