|
| 1 | +/* |
| 2 | + * A simple library to interface with rdm6300 rfid reader. |
| 3 | + * Arad Eizen (https://github.com/arduino12) 23/09/18. |
| 4 | + */ |
| 5 | + |
| 6 | +#include "RDM6300.h" |
| 7 | +#include <Arduino.h> |
| 8 | + |
| 9 | + |
| 10 | +void Rdm6300::begin(int rx_pin) |
| 11 | +{ |
| 12 | + /* init serial port to rdm6300 baud, without TX, and 20ms read timeout */ |
| 13 | +#ifdef ARDUINO_ARCH_ESP32 |
| 14 | + _serial = new HardwareSerial(1); |
| 15 | + _serial->begin(RDM6300_BAUDRATE, SERIAL_8N1, rx_pin, -1); |
| 16 | +#else |
| 17 | + _serial = new SoftwareSerial(rx_pin, -1); |
| 18 | + _serial->begin(RDM6300_BAUDRATE); |
| 19 | +#endif |
| 20 | + _serial->setTimeout(20); |
| 21 | +} |
| 22 | + |
| 23 | +bool Rdm6300::update(void) |
| 24 | +{ |
| 25 | + char buff[RDM6300_PACKET_SIZE]; |
| 26 | + uint32_t tag_id; |
| 27 | + uint8_t checksum; |
| 28 | + |
| 29 | + if (!_serial->available()) |
| 30 | + return false; |
| 31 | + |
| 32 | + /* if a packet doesn't begin with the right byte, remove that byte */ |
| 33 | + if (_serial->peek() != RDM6300_PACKET_BEGIN && _serial->read()) |
| 34 | + return false; |
| 35 | + |
| 36 | + /* if read a packet with the wrong size, drop it */ |
| 37 | + if (RDM6300_PACKET_SIZE != _serial->readBytes(buff, RDM6300_PACKET_SIZE)) |
| 38 | + return false; |
| 39 | + |
| 40 | + /* if a packet doesn't end with the right byte, drop it */ |
| 41 | + if (buff[13] != RDM6300_PACKET_END) |
| 42 | + return false; |
| 43 | + |
| 44 | + /* add null and parse checksum */ |
| 45 | + buff[13] = 0; |
| 46 | + checksum = strtol(buff + 11, NULL, 16); |
| 47 | + /* add null and parse tag_id */ |
| 48 | + buff[11] = 0; |
| 49 | + tag_id = strtol(buff + 3, NULL, 16); |
| 50 | + /* add null and parse version (needs to be xored with checksum) */ |
| 51 | + buff[3] = 0; |
| 52 | + checksum ^= strtol(buff + 1, NULL, 16); |
| 53 | + |
| 54 | + /* xore the tag_id and validate checksum */ |
| 55 | + for (uint8_t i = 0; i < 32; i += 8) |
| 56 | + checksum ^= ((tag_id >> i) & 0xFF); |
| 57 | + if (checksum) |
| 58 | + return false; |
| 59 | + |
| 60 | + /* if a new tag appears- return it */ |
| 61 | + if (_last_tag_id != tag_id) { |
| 62 | + _last_tag_id = tag_id; |
| 63 | + _next_read_ms = 0; |
| 64 | + } |
| 65 | + /* if the old tag is still here set tag_id to zero */ |
| 66 | + if (_next_read_ms > millis()) |
| 67 | + tag_id = 0; |
| 68 | + _next_read_ms = millis() + RDM6300_NEXT_READ_MS; |
| 69 | + |
| 70 | + _tag_id = tag_id; |
| 71 | + return tag_id; |
| 72 | +} |
| 73 | + |
| 74 | +bool Rdm6300::is_tag_near(void) |
| 75 | +{ |
| 76 | + return _next_read_ms > millis(); |
| 77 | +} |
| 78 | + |
| 79 | +uint32_t Rdm6300::get_tag_id(void) |
| 80 | +{ |
| 81 | + uint32_t tag_id = _tag_id; |
| 82 | + _tag_id = 0; |
| 83 | + return tag_id; |
| 84 | +} |
0 commit comments