arduinoWeigandKeyboard/hidReader.ino

82 lines
1.9 KiB
C++

// Based on: http://www.pagemac.com/projects/rfid/arduino_wiegand
#include <Keyboard.h>
// DATA pins
#define DATA0 2
#define DATA1 3
#define WEIGAND_WAIT_TIME 500 // time to wait for another weigand pulse.
#define DATA_SIZE 32
volatile uint32_t dataBits = 0; // stores all of the data bits
volatile size_t bitCount = 0; // number of bits recieved
volatile unsigned long weigand_idle_start;
inline void gotBit(char bit) {
weigand_idle_start = millis();
//Serial.print(bit, BIN);
bitWrite(dataBits, DATA_SIZE - bitCount, bit);
bitCount++;
}
// interrupts for DATA0/DATA1
void ISR_INT0() { gotBit(0); }
void ISR_INT1() { gotBit(1); }
void setup() {
pinMode(DATA0, INPUT);
pinMode(DATA1, INPUT);
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(DATA0), ISR_INT0, FALLING);
attachInterrupt(digitalPinToInterrupt(DATA1), ISR_INT1, FALLING);
Keyboard.begin();
}
void loop()
{
// Check if last bit was recieved more than WEIGAND_WAIT_TIME ago
if (bitCount > 0 && (millis() - weigand_idle_start) >= WEIGAND_WAIT_TIME) {
unsigned char i;
uint32_t data = dataBits >> (DATA_SIZE - bitCount + 1);
Serial.print("Read ");
Serial.print(bitCount);
Serial.print(" bits: ");
Serial.println(data, BIN);
// standard 26 bit format:
// P: parity bit, F: facility code, C: card code
// PFFFFFFFFCCCCCCCCCCCCCCCCP
if (bitCount == 26) {
uint8_t facilityCode = (data >> 17) & 0xFF;
uint16_t cardCode = (data >> 1) & 0xFFFF;
// TODO: check parity bits
printBits(facilityCode, cardCode);
}
else {
// TODO: handle failures and other formats
}
// reset for the next card
bitCount = 0;
}
}
void printBits(uint8_t facilityCode, uint16_t cardCode) {
Keyboard.print(facilityCode);
Keyboard.print('\t');
Keyboard.print(cardCode);
Keyboard.print('\n');
Serial.print("FC = ");
Serial.print(facilityCode);
Serial.print(", CC = ");
Serial.println(cardCode);
}