Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I write the code read RFID tag using reader RDM880 in python. It work well but sometime when I put the card in the far distance or too fast.It will error like this and stop working
CSS
tach_7 = data[7]
IndexError : string index out of range

I want in this case it will restart. Here is my code in my idea to solve this problem. But I don't know how to get error "string index out of range" to output and check it? How can I do this? Thanks for help.
Python
import serial
import time
from binascii import hexlify
chuoi="\xAA\x00\x03\x25\x26\x00\x00\xBB"
serial=serial.Serial("/dev/ttyAMA0",
                     baudrate=9600,
                     stopbits=serial.STOPBITS_ONE,
                     parity=serial.PARITY_NONE,
                     bytesize=serial.EIGHTBITS,
                     timeout=0.1)
ID_rong = 128187
def RFID(str): 
        serial.write(chuoi)
        data=serial.readline()
        tach_5 = data[5]
        tach_6 = data[6]
        hex_5=hexlify(tach_5)
        hex_6=hexlify(tach_6)
        num_5 = int(hex_5,16)
        num_6 = int(hex_6,16)
        num_a = num_5 * 1000 + num_6
        if(num_a != ID_rong):
                tach_7 = data[7]
                tach_8 = data[8]
                hex_7=hexlify(tach_7)
                hex_8=hexlify(tach_8)
                num_7 = int(hex_7,16)
                num_8 = int(hex_8,16)
                num= num_7 * 1000 + num_8 + num_6*1000000 + num_5 * 1000000000
        else:
                num = num_5 * 1000 + num_6
        return num
def check_read():
    if( 'string index out of range' ?????):
        return 1
    else:
        return 0
while 1:
    num =RFID(chuoi)
    print num
    x = check_read()
    if (x==1):
        #restart read RFID
Posted

1 solution

The exception "string index out of range" doesn't worth "getting to output", whatever it is. You need to prevent this exception instead. Not doing so would be a serious abuse, even if you make it working. You can run it under the debugger and see there the exception is thrown. Let me tell you that your programming style is totally unacceptable for a real application developed for production. Everything is hard-coded, important conditions are not checked up, and so on.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900