summaryrefslogtreecommitdiffstats
path: root/arduino/src/rf.cpp
blob: 181b784008de10a50f26817c5621c5173d442fa2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <Arduino.h>
#include <SM130.h>
#include <Wire.h>

#include "config.h"

/** Global variable that holds RFID reader object. */
SM130 rfid;

/**
 * Init NFC subsystem
 */
void rf_init(void) {
  Wire.begin();
  rfid.address = 0x30;
  rfid.reset();
#ifdef DEBUG
    Serial.print("SM130 firmware version: ");
    Serial.println(rfid.getFirmwareVersion());
#endif //DEBUG
}

/**
 * Resets the NFC controller
 */

void rf_reset() {
  rfid.reset();
}

/**
 * Sends seek command to rfid reader.
 */
void rf_seek() {
  rfid.seekTag();
}

/**
 * Handles communication with rfid reader.
 * @param p_rfid Pointer to space where mifare id will be written.
 * @return Returns true when authorized user rfid was rd.
 */
boolean rf_comm(unsigned long * p_rfid) {
  static unsigned long last_millis_seek = 0;
  static unsigned long last_millis_reset = 0;

  unsigned long new_millis = millis();

  (*p_rfid) = 0;
  if (new_millis < last_millis_seek) {
    last_millis_seek = new_millis; 
  } else if ((new_millis - last_millis_seek) > RF_PERIOD_SEEK_MS) {
    rf_seek();
    last_millis_seek = new_millis;
  }
  if (new_millis < last_millis_reset) {
    last_millis_reset = new_millis;
  } else if ((new_millis - last_millis_reset) > RF_PERIOD_RESET_MS) {
    rf_reset();
    last_millis_reset = new_millis;
  }

  if (rfid.available()){
    //Message received
    uint8_t *rf_bytes = rfid.getTagNumber();
#ifdef DEBUG
    Serial.print("RFID Tag: ");
    for (int i = 0; i < 8; i++) {
      Serial.print(rf_bytes[i], HEX);
      Serial.print(",");
    }
    Serial.println();
#endif //DEBUG
      unsigned long data=(long(rf_bytes[3])<<24)|(long(rf_bytes[2])<<16)|(long(rf_bytes[1])<<8)|(long(rf_bytes[0]));
      (*p_rfid) = data;
      return true;
  } 
  return false;
}