I am trying to use a modified MFRC522 module on UART, but I am stuck finding the correct formatting for serial read/write in python 3.
There is a library for python 2 which works for me:
The readme on that link also describes the modification to the module.
I'm having trouble getting the .self.ser.write
and .self.ser.read
in functions writeRegister
and readRegister
to work in python 3. These get string inputs, which I now understand is fine for python 2, but must be converted to bytes for python 3.
def writeRegister(self, addr, val, size=None):
if size is None:
count = 0
while True:
self.ser.flushInput()
self.ser.write(chr(addr&0x7F))
self.ser.write(chr(val))
tmp = ord(self.ser.read(1))
if(tmp == addr):
return True
count+=1
if(count > 10):
print ("Error de escritura en: "+ hex(addr))
return False
else:
self.ser.flushInput()
for txBytes in range (0, size):
self.ser.write(chr(addr&0x7F))
tmp = ord(self.ser.read(1))
if(tmp == addr):
self.ser.write(chr(val[txBytes]))
else:
print ("Error de escritura en bloque")
return False
return True
def readRegister(self, addr):
self.ser.flushInput()
self.ser.write(chr(addr|0x80))
val = self.ser.read(1)
return ord(val)
I suspected it's a matter of correctly applying .encode('utf-8')
or similar, but I can't find a working solution. If I try
chr(0x80).encode('utf-8')
I get
UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: ordinal not in range(128)
Maybe I am going down the wrong path with that.
I'll try bytes
:
bytes(chr(0x80), 'utf-8')
Gives 2 bytes in this case (>128 i guess):
b'\xc2\x80'
Maybe this is getting closer, but I get stuck on how to read back and decode. I don't know how or if to modify the ord
parts. So I can't seem to get the response from the mfrc522.
Does anyone have any suggestions?
Anybody successfully used this mfrc522 UART on python 3?
There should be no need to use char
in either Python 2.x or 3.x, you can just write bytes to the port:
self.ser.write(bytes[addr&0x7F])
For the reading function just drop the ord()
from the return sentence, it's not needed for Python 3.x.
See here for more details.