Python Code Explanation
Posted: Thu Feb 09, 2017 2:23 pm
Hello Sir/Madam
I have chosen the "Sounds Like RFID: Using a Radio Frequency Identification (RFID) Reader to Make Musical Instruments" project this year, but I am confused on one area of the Python code.
Please explain what the following code means line by line.
Thank you
# This is a short program that reads data coming from the RFID reader, one
# character at a time. The data coming in is 10 chararcters of useful information
# followed by 2 characters that indicate the end of the tag. It takes each incoming
# character and decides if it's a character a human can read or if it's one of the special
# end-of-tag characters. When it thinks it's done with the tag, it calls the 'handle_data()'
# progam we defined just above.
def read_from_port(ser):
# Let's start with an empty storage area for the incoming data
new_data = ""
while True:
# Read in one character
reading = ser.read(1)
# If we got one, the 'length' will be 1. If not, we have nothing to look at
if len(reading) > 0:
# A standard CR character (ASCII 13, or 0x0D) tells us we have all the data
if b'\r' == reading:
# If the data is complete, call our data handler to do something with it
handle_data(new_data)
# clear the storage area and get ready for new data
new_data = ""
elif reading >= b'0' and reading <= b'F':
# The character is human readable and will be in the range 0-9 or A-F,
# so stick it on the end of the storage area to build up the incoming data string
new_data = new_data + reading.decode()
I have chosen the "Sounds Like RFID: Using a Radio Frequency Identification (RFID) Reader to Make Musical Instruments" project this year, but I am confused on one area of the Python code.
Please explain what the following code means line by line.
Thank you
# This is a short program that reads data coming from the RFID reader, one
# character at a time. The data coming in is 10 chararcters of useful information
# followed by 2 characters that indicate the end of the tag. It takes each incoming
# character and decides if it's a character a human can read or if it's one of the special
# end-of-tag characters. When it thinks it's done with the tag, it calls the 'handle_data()'
# progam we defined just above.
def read_from_port(ser):
# Let's start with an empty storage area for the incoming data
new_data = ""
while True:
# Read in one character
reading = ser.read(1)
# If we got one, the 'length' will be 1. If not, we have nothing to look at
if len(reading) > 0:
# A standard CR character (ASCII 13, or 0x0D) tells us we have all the data
if b'\r' == reading:
# If the data is complete, call our data handler to do something with it
handle_data(new_data)
# clear the storage area and get ready for new data
new_data = ""
elif reading >= b'0' and reading <= b'F':
# The character is human readable and will be in the range 0-9 or A-F,
# so stick it on the end of the storage area to build up the incoming data string
new_data = new_data + reading.decode()