Search code examples
rubyrfid

Make a loop in Ruby with peripherical that detects rfid


so I'm trying with my raspberry to do a program that reads rfid cards in Ruby.

#!/usr/bin/env ruby

require 'mfrc522'




class Rfid
    def read_uid
        r = MFRC522.new
        r.picc_request(MFRC522::PICC_REQA)
        begin
            uid, sak = r.picc_select
            puts "El seu identificador es: "
            puts "%02x%02x%02x%02x" % uid
        rescue
            retry
        end
        return uid
    end
end


if __FILE__ == $0


rf = Rfid.new
uid=rf.read_uid


end

The problem is that if my card is not over the rfid when i execute the program it gets a CommunicationError. I am trying to do a loop so that if it doesn't detect the card it keeps trying but it doesn't work. Any ideas??


Solution

  • The basic problem you faced with is that begin .. end is not a loop. You can read more about ruby loops here for example

    I think it should looks like this:

    class Rfid
      def read_uid
        r = MFRC522.new
        loop do
          r.picc_request(MFRC522::PICC_REQA)
          uid, sak = r.picc_select
          
          puts "El seu identificador es: "
          puts "%02x%02x%02x%02x" % uid
    
          break uid if uid
        rescue
          redo
        end
      end
    end
    

    rescue - is to retry when you get any error raised

    break - to quit from looping

    I also should to note that using rescue without specific error class - it's bad practice because it might rescue any error even if it's just a typo in code.

    In your case it might be like:

    class Rfid
      def read_uid
        r = MFRC522.new
        loop do
          .... 
          break uid if uid
        rescue CommunicationError
          redo
        end
      end
    end