ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
rc522.cpp
Go to the documentation of this file.
1#include "rc522.h"
3#include "esphome/core/log.h"
4
5// Based on:
6// - https://github.com/miguelbalboa/rfid
7
8namespace esphome::rc522 {
9
10static const uint8_t WAIT_I_RQ = 0x30; // RxIRq and IdleIRq
11
12ESPHOME_LOG_TAG(TAG, "rc522");
13
14// Max UID size for RFID tags (4, 7, or 10 bytes)
15static constexpr size_t RC522_MAX_UID_SIZE = 10;
16
17static const uint8_t RESET_COUNT = 5;
18
20 state_ = STATE_SETUP;
21 // Pull device out of power down / reset state.
22
23 // First set the resetPowerDownPin as digital input, to check the MFRC522 power down mode.
24 if (reset_pin_ != nullptr) {
26
27 if (!reset_pin_->digital_read()) { // The MFRC522 chip is in power down mode.
28 ESP_LOGV(TAG, "Power down mode detected. Hard resetting");
29 reset_pin_->pin_mode(gpio::FLAG_OUTPUT); // Now set the resetPowerDownPin as digital output.
30 reset_pin_->digital_write(false); // Make sure we have a clean LOW state.
31 delayMicroseconds(2); // 8.8.1 Reset timing requirements says about 100ns. Let us be generous: 2μsl
32 reset_pin_->digital_write(true); // Exit power down mode. This triggers a hard reset.
33 // Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74μs.
34 // Let us be generous: 50ms.
36 return;
37 }
38 }
39
40 // Setup a soft reset
41 reset_count_ = RESET_COUNT;
43}
44
46 // Per original code, wait 50 ms
47 if (millis() - reset_timeout_ < 50)
48 return;
49
50 // Reset baud rates
51 ESP_LOGV(TAG, "Initialize");
52
55 // Reset ModWidthReg
57
58 // When communicating with a PICC we need a timeout if something goes wrong.
59 // f_timer = 13.56 MHz / (2*TPreScaler+1) where TPreScaler = [TPrescaler_Hi:TPrescaler_Lo].
60 // TPrescaler_Hi are the four low bits in TModeReg. TPrescaler_Lo is TPrescalerReg.
61 pcd_write_register(T_MODE_REG, 0x80); // TAuto=1; timer starts automatically at the end of the transmission in all
62 // communication modes at all speeds
63
64 // TPreScaler = TModeReg[3..0]:TPrescalerReg, ie 0x0A9 = 169 => f_timer=40kHz, ie a timer period of 25μs.
66 pcd_write_register(T_RELOAD_REG_H, 0x03); // Reload timer with 0x3E8 = 1000, ie 25ms before timeout.
68
69 // Default 0x00. Force a 100 % ASK modulation independent of the ModGsPReg register setting
71 pcd_write_register(MODE_REG, 0x3D); // Default 0x3F. Set the preset value for the CRC coprocessor for the CalcCRC
72 // command to 0x6363 (ISO 14443-3 part 6.2.4)
73
74 state_ = STATE_INIT;
75}
76
78 ESP_LOGCONFIG(TAG, "RC522:");
79
80 LOG_PIN(" RESET Pin: ", this->reset_pin_);
81
82 LOG_UPDATE_INTERVAL(this);
83
84 for (auto *child : this->binary_sensors_) {
85 LOG_BINARY_SENSOR(" ", "Tag", child);
86 }
87}
88
90 if (state_ == STATE_INIT) {
92 pcd_clear_register_bit_mask_(COLL_REG, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared.
95 state_ = STATE_PICC_REQUEST_A;
96 } else {
97 ESP_LOGW(TAG, "Communication takes longer than update interval: %d", state_);
98 }
99}
100
102 // First check reset is needed
103 if (reset_count_ > 0) {
104 pcd_reset_();
105 return;
106 }
107 if (state_ == STATE_SETUP) {
108 initialize_();
109 return;
110 }
111
112 StatusCode status = STATUS_ERROR; // For lint passing. TODO: refactor this
113 if (awaiting_comm_) {
114 if (state_ == STATE_SELECT_SERIAL_DONE) {
115 status = await_crc_();
116 } else {
118 }
119
120 if (status == STATUS_WAITING) {
121 return;
122 }
123 awaiting_comm_ = false;
124 ESP_LOGV(TAG, "finished communication status: %d, state: %d", status, state_);
125 }
126
127 switch (state_) {
129 if (status == STATUS_TIMEOUT) { // no tag present
130 for (auto *obj : this->binary_sensors_)
131 obj->on_scan_end(); // reset the binary sensors
132 ESP_LOGV(TAG, "CMD_REQA -> TIMEOUT (no tag present) %d", status);
133 state_ = STATE_DONE;
134 } else if (status != STATUS_OK) {
135 ESP_LOGW(TAG, "CMD_REQA -> Not OK %d", status);
136 state_ = STATE_DONE;
137 } else if (back_length_ != 2) { // || *valid_bits_ != 0) { // ATQA must be exactly 16 bits.
138 ESP_LOGW(TAG, "CMD_REQA -> OK, but unexpected back_length_ of %d", back_length_);
139 state_ = STATE_DONE;
140 } else {
141 state_ = STATE_READ_SERIAL;
142 }
143 if (state_ == STATE_DONE) {
144 // Don't wait another loop cycle
146 }
147 break;
148 }
149 case STATE_READ_SERIAL: {
150 ESP_LOGV(TAG, "STATE_READ_SERIAL (%d)", status);
151 switch (uid_idx_) {
152 case 0:
154 break;
155 case 3:
157 break;
158 case 6:
160 break;
161 default:
162 ESP_LOGE(TAG, "uid_idx_ invalid, uid_idx_ = %d", uid_idx_);
163 state_ = STATE_DONE;
164 return;
165 }
166 buffer_[1] = 32;
168 state_ = STATE_SELECT_SERIAL;
169 break;
170 }
171 case STATE_SELECT_SERIAL: {
172 buffer_[1] = 0x70; // select
173 // todo: set CRC
174 buffer_[6] = buffer_[2] ^ buffer_[3] ^ buffer_[4] ^ buffer_[5];
177 break;
178 }
180 send_len_ = 6;
182 state_ = STATE_READ_SERIAL_DONE;
183 break;
184 }
186 if (status != STATUS_OK || back_length_ != 3) {
187 if (status == STATUS_TIMEOUT) {
188 ESP_LOGV(TAG, "STATE_READ_SERIAL_DONE -> TIMEOUT (no tag present) %d", status);
189 } else {
190 char hex_buf[format_hex_pretty_size(RC522_MAX_UID_SIZE)];
191 ESP_LOGW(TAG, "Unexpected response. Read status is %d. Read bytes: %d (%s)", status, back_length_,
193 }
194
195 state_ = STATE_DONE;
196 uid_idx_ = 0;
197
199 return;
200 }
201
202 // copy the uid
203 bool cascade = buffer_[2] == PICC_CMD_CT; // todo: should be determined based on select response (buffer[6])
204 for (uint8_t i = 2 + cascade; i < 6; i++)
206 ESP_LOGVV(TAG, "copied uid to idx %d last byte is 0x%x, cascade is %d", uid_idx_, uid_buffer_[uid_idx_ - 1],
207 cascade);
208
209 if (cascade) { // there is more bytes in the UID
210 state_ = STATE_READ_SERIAL;
211 return;
212 }
213
214 std::vector<uint8_t> rfid_uid(std::begin(uid_buffer_), std::begin(uid_buffer_) + uid_idx_);
215 uid_idx_ = 0;
216 // ESP_LOGD(TAG, "Processing '%s'", format_hex_pretty(rfid_uid, '-', false).c_str()); // NOLINT
218 state_ = STATE_INIT; // scan again on next update
219 bool report = true;
220
221 for (auto *tag : this->binary_sensors_) {
222 if (tag->process(rfid_uid)) {
223 report = false;
224 }
225 }
226
227 if (this->current_uid_ == rfid_uid) {
228 return;
229 }
230
231 this->current_uid_ = rfid_uid;
232
233 for (auto *trigger : this->triggers_ontag_)
234 trigger->process(rfid_uid);
235
236 if (report) {
237 char uid_buf[format_hex_pretty_size(RC522_MAX_UID_SIZE)];
238 ESP_LOGD(TAG, "Found new tag '%s'", format_hex_pretty_to(uid_buf, rfid_uid.data(), rfid_uid.size(), '-'));
239 }
240 break;
241 }
242 case STATE_DONE: {
243 if (!this->current_uid_.empty()) {
244#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
245 char uid_buf[format_hex_pretty_size(RC522_MAX_UID_SIZE)];
246 ESP_LOGV(TAG, "Tag '%s' removed",
247 format_hex_pretty_to(uid_buf, this->current_uid_.data(), this->current_uid_.size(), '-'));
248#endif
249 for (auto *trigger : this->triggers_ontagremoved_)
250 trigger->process(this->current_uid_);
251 }
252 this->current_uid_ = {};
253 state_ = STATE_INIT;
254 break;
255 }
256 default:
257 break;
258 }
259} // namespace rc522
260
265 // The datasheet does not mention how long the SoftRest command takes to complete.
266 // But the MFRC522 might have been in soft power-down mode (triggered by bit 4 of CommandReg)
267 // Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74μs.
268 // Let us be generous: 50ms.
269
270 if (millis() - reset_timeout_ < 50)
271 return;
272
273 if (reset_count_ == RESET_COUNT) {
274 ESP_LOGI(TAG, "Soft reset");
275 // Issue the SoftReset command.
277 }
278
279 // Expect the PowerDown bit in CommandReg to be cleared (max 3x50ms)
280 if ((pcd_read_register(COMMAND_REG) & (1 << 4)) == 0) {
281 reset_count_ = 0;
282 ESP_LOGI(TAG, "Device online");
283 // Wait for initialize
285 return;
286 }
287
288 if (--reset_count_ == 0) {
289 this->mark_failed(LOG_STR("Reset command failed"));
290 }
291}
292
298 uint8_t value = pcd_read_register(TX_CONTROL_REG);
299 if ((value & 0x03) != 0x03) {
300 pcd_write_register(TX_CONTROL_REG, value | 0x03);
301 }
302}
303
308 uint8_t value = pcd_read_register(TX_CONTROL_REG);
309 if ((value & 0x03) != 0x00) {
310 pcd_write_register(TX_CONTROL_REG, value & ~0x03);
311 }
312}
313
318 uint8_t mask
319) {
320 uint8_t tmp = pcd_read_register(reg);
321 pcd_write_register(reg, tmp | mask); // set bit mask
322}
323
328 uint8_t mask
329) {
330 uint8_t tmp = pcd_read_register(reg);
331 pcd_write_register(reg, tmp & (~mask)); // clear bit mask
332}
333
340void RC522::pcd_transceive_data_(uint8_t send_len) {
341#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
342 char hex_buf[format_hex_pretty_size(RC522_MAX_UID_SIZE)];
343 ESP_LOGV(TAG, "PCD TRANSCEIVE: RX: %s", format_hex_pretty_to(hex_buf, buffer_, send_len, '-'));
344#endif
345 delayMicroseconds(1000); // we need 1 ms delay between antenna on and those communication commands
346 send_len_ = send_len;
347 // Prepare values for BitFramingReg
348 // For REQA and WUPA we need the short frame format - transmit only 7 bits of the last (and only)
349 // uint8_t. TxLastBits = BitFramingReg[2..0]
350 uint8_t bit_framing = (buffer_[0] == PICC_CMD_REQA) ? 7 : 0;
351
352 pcd_write_register(COMMAND_REG, PCD_IDLE); // Stop any active command.
353 pcd_write_register(COM_IRQ_REG, 0x7F); // Clear all seven interrupt request bits
354 pcd_write_register(FIFO_LEVEL_REG, 0x80); // FlushBuffer = 1, FIFO initialization
355 pcd_write_register(FIFO_DATA_REG, send_len_, buffer_); // Write sendData to the FIFO
356 pcd_write_register(BIT_FRAMING_REG, bit_framing); // Bit adjustments
357 pcd_write_register(COMMAND_REG, PCD_TRANSCEIVE); // Execute the command
358 pcd_set_register_bit_mask_(BIT_FRAMING_REG, 0x80); // StartSend=1, transmission of data starts
359 awaiting_comm_ = true;
361}
362
364 if (millis() - awaiting_comm_time_ < 2) // wait at least 2 ms
365 return STATUS_WAITING;
366 uint8_t n = pcd_read_register(
367 COM_IRQ_REG); // ComIrqReg[7..0] bits are: Set1 TxIRq RxIRq IdleIRq HiAlertIRq LoAlertIRq ErrIRq TimerIRq
368 if (n & 0x01) { // Timer interrupt - nothing received in 25ms
369 back_length_ = 0;
370 error_counter_ = 0; // reset the error counter
371 return STATUS_TIMEOUT;
372 }
373 if (!(n & WAIT_I_RQ)) { // None of the interrupts that signal success has been set.
374 // Wait for the command to complete.
375 if (millis() - awaiting_comm_time_ < 40)
376 return STATUS_WAITING;
377 back_length_ = 0;
378 ESP_LOGW(TAG, "Communication with the MFRC522 might be down, reset in %d",
379 10 - error_counter_); // todo: trigger reset?
380 if (error_counter_++ >= 10) {
381 setup();
382 error_counter_ = 0; // reset the error counter
383 }
384
385 return STATUS_TIMEOUT;
386 }
387 // Stop now if any errors except collisions were detected.
388 uint8_t error_reg_value = pcd_read_register(
389 ERROR_REG); // ErrorReg[7..0] bits are: WrErr TempErr reserved BufferOvfl CollErr CRCErr ParityErr ProtocolErr
390 if (error_reg_value & 0x13) { // BufferOvfl ParityErr ProtocolErr
391 return STATUS_ERROR;
392 }
393 error_counter_ = 0; // reset the error counter
394
395 n = pcd_read_register(FIFO_LEVEL_REG); // Number of uint8_ts in the FIFO
396 if (n > sizeof(buffer_))
397 return STATUS_NO_ROOM;
398 if (n > sizeof(buffer_) - send_len_)
399 send_len_ = sizeof(buffer_) - n; // simply overwrite the sent values
400 back_length_ = n; // Number of uint8_ts returned
401 pcd_read_register(FIFO_DATA_REG, n, buffer_ + send_len_, rx_align_); // Get received data from FIFO
402 uint8_t valid_bits_local =
403 pcd_read_register(CONTROL_REG) & 0x07; // RxLastBits[2:0] indicates the number of valid bits in the last
404 // received uint8_t. If this value is 000b, the whole uint8_t is valid.
405
406 // Tell about collisions
407 if (error_reg_value & 0x08) { // CollErr
408 ESP_LOGW(TAG, "collision error, received %d bytes + %d bits (but anticollision not implemented)",
409 back_length_ - (valid_bits_local > 0), valid_bits_local);
410 return STATUS_COLLISION;
411 }
412 // Tell about collisions
413 if (valid_bits_local) {
414 ESP_LOGW(TAG, "only %d valid bits received, tag distance to high? Error code is 0x%x", valid_bits_local,
415 error_reg_value); // TODO: is this always due to collissions?
416 return STATUS_ERROR;
417 }
418#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
419 char hex_buf[format_hex_pretty_size(RC522_MAX_UID_SIZE)];
420 ESP_LOGV(TAG, "received %d bytes: %s", back_length_,
422#endif
423
424 return STATUS_OK;
425}
426
433void RC522::pcd_calculate_crc_(uint8_t *data,
434 uint8_t length
435) {
436 ESP_LOGVV(TAG, "pcd_calculate_crc_(..., %d, ...)", length);
437 pcd_write_register(COMMAND_REG, PCD_IDLE); // Stop any active command.
438 pcd_write_register(DIV_IRQ_REG, 0x04); // Clear the CRCIRq interrupt request bit
439 pcd_write_register(FIFO_LEVEL_REG, 0x80); // FlushBuffer = 1, FIFO initialization
440 pcd_write_register(FIFO_DATA_REG, length, data); // Write data to the FIFO
441 pcd_write_register(COMMAND_REG, PCD_CALC_CRC); // Start the calculation
442
443 awaiting_comm_ = true;
445}
446
448 if (millis() - awaiting_comm_time_ < 2) // wait at least 2 ms
449 return STATUS_WAITING;
450
451 // DivIrqReg[7..0] bits are: Set2 reserved reserved MfinActIRq reserved CRCIRq reserved reserved
452 uint8_t n = pcd_read_register(DIV_IRQ_REG);
453 if (n & 0x04) { // CRCIRq bit set - calculation done
454 pcd_write_register(COMMAND_REG, PCD_IDLE); // Stop calculating CRC for new content in the FIFO.
455 // Transfer the result from the registers to the result buffer
458
459 ESP_LOGVV(TAG, "pcd_calculate_crc_() STATUS_OK");
460 return STATUS_OK;
461 }
462 if (millis() - awaiting_comm_time_ < 89)
463 return STATUS_WAITING;
464
465 ESP_LOGD(TAG, "pcd_calculate_crc_() TIMEOUT");
466 // 89ms passed and nothing happened. Communication with the MFRC522 might be down.
467 return STATUS_TIMEOUT;
468}
469
470bool RC522BinarySensor::process(std::vector<uint8_t> &data) {
471 bool result = true;
472 if (data.size() != this->uid_.size()) {
473 result = false;
474 } else {
475 for (size_t i = 0; i < data.size(); i++) {
476 if (data[i] != this->uid_[i]) {
477 result = false;
478 break;
479 }
480 }
481 }
482 this->publish_state(result);
483 this->found_ = result;
484 return result;
485}
486void RC522Trigger::process(std::vector<uint8_t> &data) {
487 char uid_buf[format_hex_pretty_size(RC522_MAX_UID_SIZE)];
488 this->trigger(format_hex_pretty_to(uid_buf, data.data(), data.size(), '-'));
489}
490
491} // namespace esphome::rc522
uint8_t status
Definition bl0942.h:8
void mark_failed()
Mark this component as failed.
virtual void pin_mode(gpio::Flags flags)=0
virtual void digital_write(bool value)=0
virtual bool digital_read()=0
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Definition automation.h:556
void publish_state(bool new_state)
Publish a new state to the front-end.
bool process(std::vector< uint8_t > &data)
Definition rc522.cpp:470
std::vector< uint8_t > uid_
Definition rc522.h:263
std::vector< RC522Trigger * > triggers_ontagremoved_
Definition rc522.h:245
void dump_config() override
Definition rc522.cpp:77
virtual uint8_t pcd_read_register(PcdRegister reg)=0
GPIOPin * reset_pin_
Definition rc522.h:240
void pcd_transceive_data_(uint8_t send_len)
Transfers data to the MFRC522 FIFO, executes a command, waits for completion and transfers data back ...
Definition rc522.cpp:340
std::vector< RC522Trigger * > triggers_ontag_
Definition rc522.h:244
void pcd_reset_()
Performs a soft reset on the MFRC522 chip and waits for it to be ready again.
Definition rc522.cpp:264
uint32_t awaiting_comm_time_
Definition rc522.h:226
std::vector< RC522BinarySensor * > binary_sensors_
Definition rc522.h:243
void pcd_antenna_off_()
Turns the antenna off by disabling pins TX1 and TX2.
Definition rc522.cpp:307
uint8_t back_length_
In: Max number of uint8_ts to write to *backData. Out: The number of uint8_ts returned.
Definition rc522.h:233
void update() override
Definition rc522.cpp:89
StatusCode await_crc_()
Definition rc522.cpp:447
uint8_t reset_count_
Definition rc522.h:241
uint32_t reset_timeout_
Definition rc522.h:242
void setup() override
Definition rc522.cpp:19
uint8_t error_counter_
Definition rc522.h:236
StatusCode await_transceive_()
Definition rc522.cpp:363
void pcd_antenna_on_()
Turns the antenna on by enabling pins TX1 and TX2.
Definition rc522.cpp:297
void pcd_set_register_bit_mask_(PcdRegister reg, uint8_t mask)
Sets the bits given in mask in register reg.
Definition rc522.cpp:317
void pcd_calculate_crc_(uint8_t *data, uint8_t length)
Use the CRC coprocessor in the MFRC522 to calculate a CRC_A.
Definition rc522.cpp:433
std::vector< uint8_t > current_uid_
Definition rc522.h:246
void pcd_clear_register_bit_mask_(PcdRegister reg, uint8_t mask)
Clears the bits given in mask from register reg.
Definition rc522.cpp:327
uint8_t uid_buffer_[10]
Definition rc522.h:234
uint8_t buffer_[9]
buffer for communication, the first bits [0..back_idx-1] are for tx , [back_idx..back_idx+back_len] f...
Definition rc522.h:230
void loop() override
Definition rc522.cpp:101
virtual void pcd_write_register(PcdRegister reg, uint8_t value)=0
void process(std::vector< uint8_t > &data)
Definition rc522.cpp:486
ESPHOME_LOG_TAG(TAG, "rc522")
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition hal.cpp:48
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:498
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:1609
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
uint16_t length
Definition tt21100.cpp:0