0

I am trying to read response of the serial port. (I am using a RFID module) Here is my code:

import serial
ser = serial.Serial()
ser.port = "/dev/ttyUSB0"
ser.baudrate = 9600
ser.timeout = 3
ser.open()
if ser.isOpen():
    ser.write("\xFF\x01\x03\x10\x02\x02\x18")
    print("command written")
while ser.isOpen():
    response = ser.read(5)
    print("trying to read")
    print(int(response,16))

At first I used directly print(response) and what I got was:

trying to read
�#��

Therefore I used print(int(response,16)) in order to convert response to integer and now I am getting error:

Traceback (most recent call last):
  File "serialread.py", line 13, in <module>
    print(int(response,16))
ValueError: invalid literal for int() with base 16: '\x94#\xdb\xff'

What should I do? I am pretty new to python and do not have any idea what the problem can be.

1 Answer 1

1

Your string is already a hex literal:

>>> x = '\x94#\xdb\xff'
>>> x.encode('hex')
'9423dbff'
>>> int(x.encode('hex'),16)
2485378047L
Sign up to request clarification or add additional context in comments.

3 Comments

Hmm.. Ok now I am able to print 2485378047. But I do not want to print it in this way. I want to print it as 94 db ff etc. How can I do it? Thank you for your help.
Also, now I did the required changes at my code and my current problem is: trying to read 2485378047 trying to read Traceback (most recent call last): File "serialread.py", line 15, in <module> print(int(response,16)) ValueError: invalid literal for int() with base 16: '' Sorry for spamming you with my beginner questions.
You need to change print(int(response,16)) to print(response.encode('hex'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.