I am trying to attain data from an RFID reader I have attached to a serial port. The data is coming through as jumbled characters, which I have to convert to hex. I am getting an error trying to convert it to hex, when I do this:
puts "%02X" % key
I get this error: '%' : invalid value for Integer(): "\xE2\x10......"etc
It is almost converting it right as the "\xE2\x10..." etc is close to what it should be outputting, it should be 00 00 E2 00 10... etc. I'm not sure if there is another way to convert it to hex, I've also tried:
key.to_i.to_s(16)
and
key.hex
But both produce 0 as the output, which isn't correct. When I try to convert it to just an integer it converts it to a 0, I'm not sure why.
Here is the full code if that helps, most of it is taken from an example on the net:
require "serialport"
class RfidReader
attr_accessor :key
def initialize(port)
port_str = "COM7"
baud_rate = 9600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
@sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
@key_parts = []
@key_limit = 16 # number of slots in the RFID card.
while true do
main
end
@sp.close
end
def key_detected?
@key_parts << @sp.getc
if @key_parts.size >= @key_limit
self.key = @key_parts.join()
@key_parts = []
true
else
false
end
end
def main
if key_detected?
self.key.gsub!(/\0/, '')
#puts self.key.hex
#puts self.key.to_i.to_s(16)
puts "%02X" % key
#puts key
end
end
end
RfidReader.new("COM7")