ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
rc522.h
Go to the documentation of this file.
1#pragma once
2
4#include "esphome/core/hal.h"
7
8#include <vector>
9
10namespace esphome {
11namespace rc522 {
12
13class RC522BinarySensor;
14class RC522Trigger;
15class RC522 : public PollingComponent {
16 public:
17 void setup() override;
18
19 void dump_config() override;
20
21 void update() override;
22
23 void loop() override;
24
25 void register_tag(RC522BinarySensor *tag) { this->binary_sensors_.push_back(tag); }
26 void register_ontag_trigger(RC522Trigger *trig) { this->triggers_ontag_.push_back(trig); }
28
30
31 protected:
32 // Return codes from the functions in this class. Remember to update GetStatusCodeName() if you add more.
33 // last value set to 0xff, then compiler uses less ram, it seems some optimisations are triggered
34 enum StatusCode : uint8_t {
35 STATUS_OK, // Success
36 STATUS_WAITING, // Waiting result from RC522 chip
37 STATUS_ERROR, // Error in communication
38 STATUS_COLLISION, // Collision detected
39 STATUS_TIMEOUT, // Timeout in communication.
40 STATUS_NO_ROOM, // A buffer is not big enough.
41 STATUS_INTERNAL_ERROR, // Internal error in the code. Should not happen ;-)
42 STATUS_INVALID, // Invalid argument.
43 STATUS_CRC_WRONG, // The CRC_A does not match
44 STATUS_MIFARE_NACK = 0xff // A MIFARE PICC responded with NAK.
45 };
46
58
59 enum PcdRegister : uint8_t {
60 // Page 0: Command and status
61 // 0x00 // reserved for future use
62 COMMAND_REG = 0x01 << 1, // starts and stops command execution
63 COM_I_EN_REG = 0x02 << 1, // enable and disable interrupt request control bits
64 DIV_I_EN_REG = 0x03 << 1, // enable and disable interrupt request control bits
65 COM_IRQ_REG = 0x04 << 1, // interrupt request bits
66 DIV_IRQ_REG = 0x05 << 1, // interrupt request bits
67 ERROR_REG = 0x06 << 1, // error bits showing the error status of the last command executed
68 STATUS1_REG = 0x07 << 1, // communication status bits
69 STATUS2_REG = 0x08 << 1, // receiver and transmitter status bits
70 FIFO_DATA_REG = 0x09 << 1, // input and output of 64 uint8_t FIFO buffer
71 FIFO_LEVEL_REG = 0x0A << 1, // number of uint8_ts stored in the FIFO buffer
72 WATER_LEVEL_REG = 0x0B << 1, // level for FIFO underflow and overflow warning
73 CONTROL_REG = 0x0C << 1, // miscellaneous control registers
74 BIT_FRAMING_REG = 0x0D << 1, // adjustments for bit-oriented frames
75 COLL_REG = 0x0E << 1, // bit position of the first bit-collision detected on the RF interface
76 // 0x0F // reserved for future use
77
78 // Page 1: Command
79 // 0x10 // reserved for future use
80 MODE_REG = 0x11 << 1, // defines general modes for transmitting and receiving
81 TX_MODE_REG = 0x12 << 1, // defines transmission data rate and framing
82 RX_MODE_REG = 0x13 << 1, // defines reception data rate and framing
83 TX_CONTROL_REG = 0x14 << 1, // controls the logical behavior of the antenna driver pins TX1 and TX2
84 TX_ASK_REG = 0x15 << 1, // controls the setting of the transmission modulation
85 TX_SEL_REG = 0x16 << 1, // selects the internal sources for the antenna driver
86 RX_SEL_REG = 0x17 << 1, // selects internal receiver settings
87 RX_THRESHOLD_REG = 0x18 << 1, // selects thresholds for the bit decoder
88 DEMOD_REG = 0x19 << 1, // defines demodulator settings
89 // 0x1A // reserved for future use
90 // 0x1B // reserved for future use
91 MF_TX_REG = 0x1C << 1, // controls some MIFARE communication transmit parameters
92 MF_RX_REG = 0x1D << 1, // controls some MIFARE communication receive parameters
93 // 0x1E // reserved for future use
94 SERIAL_SPEED_REG = 0x1F << 1, // selects the speed of the serial UART interface
95
96 // Page 2: Configuration
97 // 0x20 // reserved for future use
98 CRC_RESULT_REG_H = 0x21 << 1, // shows the MSB and LSB values of the CRC calculation
99 CRC_RESULT_REG_L = 0x22 << 1,
100 // 0x23 // reserved for future use
101 MOD_WIDTH_REG = 0x24 << 1, // controls the ModWidth setting?
102 // 0x25 // reserved for future use
103 RF_CFG_REG = 0x26 << 1, // configures the receiver gain
104 GS_N_REG = 0x27 << 1, // selects the conductance of the antenna driver pins TX1 and TX2 for modulation
105 CW_GS_P_REG = 0x28 << 1, // defines the conductance of the p-driver output during periods of no modulation
106 MOD_GS_P_REG = 0x29 << 1, // defines the conductance of the p-driver output during periods of modulation
107 T_MODE_REG = 0x2A << 1, // defines settings for the internal timer
108 T_PRESCALER_REG = 0x2B << 1, // the lower 8 bits of the TPrescaler value. The 4 high bits are in TModeReg.
109 T_RELOAD_REG_H = 0x2C << 1, // defines the 16-bit timer reload value
110 T_RELOAD_REG_L = 0x2D << 1,
111 T_COUNTER_VALUE_REG_H = 0x2E << 1, // shows the 16-bit timer value
113
114 // Page 3: Test Registers
115 // 0x30 // reserved for future use
116 TEST_SEL1_REG = 0x31 << 1, // general test signal configuration
117 TEST_SEL2_REG = 0x32 << 1, // general test signal configuration
118 TEST_PIN_EN_REG = 0x33 << 1, // enables pin output driver on pins D1 to D7
119 TEST_PIN_VALUE_REG = 0x34 << 1, // defines the values for D1 to D7 when it is used as an I/O bus
120 TEST_BUS_REG = 0x35 << 1, // shows the status of the internal test bus
121 AUTO_TEST_REG = 0x36 << 1, // controls the digital self-test
122 VERSION_REG = 0x37 << 1, // shows the software version
123 ANALOG_TEST_REG = 0x38 << 1, // controls the pins AUX1 and AUX2
124 TEST_DA_C1_REG = 0x39 << 1, // defines the test value for TestDAC1
125 TEST_DA_C2_REG = 0x3A << 1, // defines the test value for TestDAC2
126 TEST_ADC_REG = 0x3B << 1 // shows the value of ADC I and Q channels
127 // 0x3C // reserved for production tests
128 // 0x3D // reserved for production tests
129 // 0x3E // reserved for production tests
130 // 0x3F // reserved for production tests
131 };
132
133 // MFRC522 commands. Described in chapter 10 of the datasheet.
134 enum PcdCommand : uint8_t {
135 PCD_IDLE = 0x00, // no action, cancels current command execution
136 PCD_MEM = 0x01, // stores 25 uint8_ts into the internal buffer
137 PCD_GENERATE_RANDOM_ID = 0x02, // generates a 10-uint8_t random ID number
138 PCD_CALC_CRC = 0x03, // activates the CRC coprocessor or performs a self-test
139 PCD_TRANSMIT = 0x04, // transmits data from the FIFO buffer
140 PCD_NO_CMD_CHANGE = 0x07, // no command change, can be used to modify the CommandReg register bits without
141 // affecting the command, for example, the PowerDown bit
142 PCD_RECEIVE = 0x08, // activates the receiver circuits
144 0x0C, // transmits data from FIFO buffer to antenna and automatically activates the receiver after transmission
145 PCD_MF_AUTHENT = 0x0E, // performs the MIFARE standard authentication as a reader
146 PCD_SOFT_RESET = 0x0F // resets the MFRC522
147 };
148
149 // Commands sent to the PICC.
150 enum PiccCommand : uint8_t {
151 // The commands used by the PCD to manage communication with several PICCs (ISO 14443-3, Type A, section 6.4)
152 PICC_CMD_REQA = 0x26, // REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for
153 // anticollision or selection. 7 bit frame.
154 PICC_CMD_WUPA = 0x52, // Wake-UP command, Type A. Invites PICCs in state IDLE and HALT to go to READY(*) and
155 // prepare for anticollision or selection. 7 bit frame.
156 PICC_CMD_CT = 0x88, // Cascade Tag. Not really a command, but used during anti collision.
157 PICC_CMD_SEL_CL1 = 0x93, // Anti collision/Select, Cascade Level 1
158 PICC_CMD_SEL_CL2 = 0x95, // Anti collision/Select, Cascade Level 2
159 PICC_CMD_SEL_CL3 = 0x97, // Anti collision/Select, Cascade Level 3
160 PICC_CMD_HLTA = 0x50, // HaLT command, Type A. Instructs an ACTIVE PICC to go to state HALT.
161 PICC_CMD_RATS = 0xE0, // Request command for Answer To Reset.
162 // The commands used for MIFARE Classic (from http://www.mouser.com/ds/2/302/MF1S503x-89574.pdf, Section 9)
163 // Use PCD_MFAuthent to authenticate access to a sector, then use these commands to read/write/modify the blocks on
164 // the sector.
165 // The read/write commands can also be used for MIFARE Ultralight.
166 PICC_CMD_MF_AUTH_KEY_A = 0x60, // Perform authentication with Key A
167 PICC_CMD_MF_AUTH_KEY_B = 0x61, // Perform authentication with Key B
169 0x30, // Reads one 16 uint8_t block from the authenticated sector of the PICC. Also used for MIFARE Ultralight.
170 PICC_CMD_MF_WRITE = 0xA0, // Writes one 16 uint8_t block to the authenticated sector of the PICC. Called
171 // "COMPATIBILITY WRITE" for MIFARE Ultralight.
173 0xC0, // Decrements the contents of a block and stores the result in the internal data register.
175 0xC1, // Increments the contents of a block and stores the result in the internal data register.
176 PICC_CMD_MF_RESTORE = 0xC2, // Reads the contents of a block into the internal data register.
177 PICC_CMD_MF_TRANSFER = 0xB0, // Writes the contents of the internal data register to a block.
178 // The commands used for MIFARE Ultralight (from http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf, Section 8.6)
179 // The PICC_CMD_MF_READ and PICC_CMD_MF_WRITE can also be used for MIFARE Ultralight.
180 PICC_CMD_UL_WRITE = 0xA2 // Writes one 4 uint8_t page to the PICC.
181 };
182
183 void pcd_reset_();
184 void initialize_();
185 void pcd_antenna_on_();
186 void pcd_antenna_off_();
187
188 virtual uint8_t pcd_read_register(PcdRegister reg
189 ) = 0;
190
196 uint8_t count,
197 uint8_t *values,
198 uint8_t rx_align
199 ) = 0;
201 uint8_t value
202 ) = 0;
203
209 uint8_t count,
210 uint8_t *values
211 ) = 0;
212
214 uint8_t mask
215 );
217 uint8_t mask
218 );
219
220 void pcd_transceive_data_(uint8_t send_len);
221
222 void pcd_calculate_crc_(uint8_t *data,
223 uint8_t length
224 );
225
230
231 uint8_t buffer_[9];
233 uint8_t send_len_; // index of first byte for RX
234 uint8_t back_length_;
235 uint8_t uid_buffer_[10]; // buffer to construct the uid (for 7 and 10 bit uids)
236 uint8_t uid_idx_ = 0; // number of read uid bytes e.g. index of the next available position in uid_buffer
237 uint8_t error_counter_ = 0; // to reset if unresponsive
238 uint8_t rx_align_;
239 uint8_t *valid_bits_;
240
242 uint8_t reset_count_{0};
243 uint32_t reset_timeout_{0};
244 std::vector<RC522BinarySensor *> binary_sensors_;
245 std::vector<RC522Trigger *> triggers_ontag_;
246 std::vector<RC522Trigger *> triggers_ontagremoved_;
247 std::vector<uint8_t> current_uid_;
248
250 NONE = 0,
252 } error_code_{NONE};
253};
254
256 public:
257 void set_uid(const std::vector<uint8_t> &uid) { uid_ = uid; }
258
259 bool process(std::vector<uint8_t> &data);
260
261 void on_scan_end() {
262 if (!this->found_) {
263 this->publish_state(false);
264 }
265 this->found_ = false;
266 }
267
268 protected:
269 std::vector<uint8_t> uid_;
270 bool found_{false};
271};
272
273class RC522Trigger : public Trigger<std::string> {
274 public:
275 void process(std::vector<uint8_t> &data);
276};
277
278} // namespace rc522
279} // namespace esphome
This class simplifies creating components that periodically check a state.
Definition component.h:425
Base class for all binary_sensor-type classes.
void publish_state(bool new_state)
Publish a new state to the front-end.
bool process(std::vector< uint8_t > &data)
Definition rc522.cpp:464
std::vector< uint8_t > uid_
Definition rc522.h:269
void set_uid(const std::vector< uint8_t > &uid)
Definition rc522.h:257
virtual void pcd_write_register(PcdRegister reg, uint8_t count, uint8_t *values)=0
Writes a number of uint8_ts to the specified register in the MFRC522 chip.
std::vector< RC522Trigger * > triggers_ontagremoved_
Definition rc522.h:246
void dump_config() override
Definition rc522.cpp:75
virtual uint8_t pcd_read_register(PcdRegister reg)=0
GPIOPin * reset_pin_
Definition rc522.h:241
enum esphome::rc522::RC522::RC522Error NONE
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:245
void pcd_reset_()
Performs a soft reset on the MFRC522 chip and waits for it to be ready again.
Definition rc522.cpp:262
uint8_t * valid_bits_
Definition rc522.h:239
uint32_t awaiting_comm_time_
Definition rc522.h:227
void register_tag(RC522BinarySensor *tag)
Definition rc522.h:25
std::vector< RC522BinarySensor * > binary_sensors_
Definition rc522.h:244
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:234
void update() override
Definition rc522.cpp:94
StatusCode await_crc_()
Definition rc522.cpp:441
uint8_t reset_count_
Definition rc522.h:242
uint32_t reset_timeout_
Definition rc522.h:243
void setup() override
Definition rc522.cpp:17
uint8_t error_counter_
Definition rc522.h:237
void register_ontagremoved_trigger(RC522Trigger *trig)
Definition rc522.h:27
virtual void pcd_read_register(PcdRegister reg, uint8_t count, uint8_t *values, uint8_t rx_align)=0
Reads a number of uint8_ts from the specified register in the MFRC522 chip.
StatusCode await_transceive_()
Definition rc522.cpp:360
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
enum esphome::rc522::RC522::State STATE_NONE
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:427
std::vector< uint8_t > current_uid_
Definition rc522.h:247
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:235
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:231
void loop() override
Definition rc522.cpp:106
virtual void pcd_write_register(PcdRegister reg, uint8_t value)=0
void set_reset_pin(GPIOPin *reset)
Definition rc522.h:29
void register_ontag_trigger(RC522Trigger *trig)
Definition rc522.h:26
void process(std::vector< uint8_t > &data)
Definition rc522.cpp:480
uint16_t reset
Definition ina226.h:5
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
uint16_t length
Definition tt21100.cpp:0