bangnaga

Arduino RFID Update

Jun 14th, 2012 (edited)
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.21 KB | None | 0 0
  1. void setup() {
  2.   Serial.begin(9600);                                 // connect to the serial port
  3. }
  4.  
  5. void loop () {
  6.   byte i = 0;
  7.   byte val = 0;
  8.   byte code[6];
  9.   byte checksum = 0;
  10.   byte bytesread = 0;
  11.   byte tempbyte = 0;
  12.  
  13.   if(Serial.available() > 0) {
  14.     if((val = Serial.read()) == 2) {                  // check for header
  15.       bytesread = 0;
  16.       while (bytesread < 12) {                        // read 10 digit code + 2 digit checksum
  17.         if( Serial.available() > 0) {
  18.           val = Serial.read();
  19.           if((val == 0x0D)||(val == 0x0A)||(val == 0x03)||(val == 0x02)) { // if header or stop bytes before the 10 digit reading
  20.             break;                                    // stop reading
  21.           }
  22.  
  23.           // Do Ascii/Hex conversion:
  24.           if ((val >= '0') && (val <= '9')) {
  25.             val = val - '0';
  26.           } else if ((val >= 'A') && (val <= 'F')) {
  27.             val = 10 + val - 'A';
  28.           }
  29.  
  30.           // Every two hex-digits, add byte to code:
  31.           if (bytesread & 1 == 1) {
  32.             // make some space for this hex-digit by
  33.             // shifting the previous hex-digit with 4 bits to the left:
  34.             code[bytesread >> 1] = (val | (tempbyte << 4));
  35.  
  36.             if (bytesread >> 1 != 5) {                // If we're at the checksum byte,
  37.               checksum ^= code[bytesread >> 1];       // Calculate the checksum... (XOR)
  38.             };
  39.           } else {
  40.             tempbyte = val;                           // Store the first hex digit first...
  41.           };
  42.  
  43.           bytesread++;                                // ready to read next digit
  44.         }
  45.       }
  46.  
  47.       // Output to Serial:
  48.  
  49.       if (bytesread == 12) {                          // if 12 digit read is complete
  50.         //Serial.print("5-byte code: ");
  51.         for (i=0; i<5; i++) {
  52.           if (code[i] < 16) Serial.print("0");
  53.           Serial.print(code[i], HEX);
  54.           Serial.print(" ");
  55.         }
  56.         Serial.println();
  57.  
  58.         //Serial.print("Checksum: ");
  59.         //Serial.print(code[5], HEX);
  60.         //Serial.println(code[5] == checksum ? " -- passed." : " -- error.");
  61.         //Serial.println();
  62.       }
  63.  
  64.       bytesread = 0;
  65.     }
  66.   }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment