-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Power down modes? #269
Comments
Not implemented yet. I will be happy to get a pull request from you :) |
Well, I was also reading it but I haven't noticed any useful difference between soft power-down and hard power-down. (?) And going to hard power-down is quite easy, I just set the RST pin low. To wake it up I call MFRC522.PCD_Init() and it sets RST pin high. You can also find that in PCD_Init() there is 50 milliseconds delay for crystal startup. I modified it for myself to only 5 ms and it seems to work well in my case. And generally, for battery operation, right now I'm testing the mode that ATmega328 asks MFRC522 if there is any PICC, if not then ATmega sets MFRC's RST pin low and goes to sleep for a second itself. After a second ATmega wakes up, sets RST pin high, asks MFRC and then it all go to sleep again... (Of course if there is a PICC present then it is more complicated.) And to be woken for as short time as possible I also noticed that in library there is set 25 ms timeout in TReloadReg registers. You can find it in PCD_Init(). This timeout is used in PCD_CommunicateWithPICC(). I shortened it to 10 ms and it seems to work. But like the wakeup delay I don't know what the right minimum is. |
I'll answer to myself. I started scope and it seems that my crystal+MFRC seems to be woken up in less than 300 microseconds. |
Good to hear about your tests! |
Well, I'm not testing soft power down. Because like I said, I don't understand what is on or off in this mode. In hard power-down (RST connected to GND) I measured 0.3 mA. It is quite a lot. I'm using a module called RFID-RC522 (popular and cheap on ebay, you can google it). I previously unsoldered resistor R1 nearby the power LED D1. (I think it was 1 kOhm, I didn't want to unsolder the LED.) But now I can see that there is also 10 kOhm R2 between 3.3V and RST and that makes that 0.3 mA. So I unsoldered R2 and in hard power-down my cheap multimeter displays 0.1 uA. It is suspiciously much less than "max. 5 microamp" in datasheet. Btw. two posts before I mentioned 10 ms timeout in PCD_CommunicateWithPICC. I googled datasheet for MF1S503x (MIFARE Classic 1K) and there it looks like that 10 ms is the maximum timeout for he longest operation. I'm trying to make something like "PICC_IsAnyCardPresent()" and to have this as fast as possible. ...
mfrc522.PCD_Init();
byte bufferATQA[2];
byte bufferSize = sizeof(bufferATQA);
MFRC522::StatusCode sta = mfrc522.PICC_RequestA(bufferATQA, &bufferSize);
bool result = (sta == MFRC522::STATUS_OK || sta == MFRC522::STATUS_COLLISION);
if (!result) {
sta = mfrc522.PICC_WakeupA(bufferATQA, &bufferSize);
result = (sta == MFRC522::STATUS_OK || sta == MFRC522::STATUS_COLLISION);
}
if (!result) digitalWrite(MFRC522_RST_PIN, LOW);
... This test takes about 30-40 ms according to cpu speed (with shorter wakeup delay, shorter timeouts, faster SPI). |
Well I power down both mcu (328p) and the the rc522 exit low power when card is detected. |
mfrc522.PCD_ReducedPowerCardDetection(MCU, LPMCU_PCD_MS, TH, FW_V); example /**
* ----------------------------------------------------------------------------
* This is a MFRC522 library example; see https://github.com/miguelbalboa/rfid
* for further details and other examples.
*
* NOTE: The library file MFRC522.h has a lot of useful info. Please read it.
*
* Released into the public domain.
* ----------------------------------------------------------------------------
* This sample shows how to read and write data blocks on a MIFARE Classic PICC
* (= card/tag).
*
* BEWARE: Data will be written to the PICC, in sector #1 (blocks #4 to #7).
*
*
* Typical pin layout used:
* -----------------------------------------------------------------------------------------
* MFRC522 Arduino Arduino Arduino Arduino Arduino
* Reader/PCD Uno/101 Mega Nano v3 Leonardo/Micro Pro Micro
* Signal Pin Pin Pin Pin Pin Pin
* -----------------------------------------------------------------------------------------
* RST/Reset RST 9 5 D9 RESET/ICSP-5 RST
* SPI SS SDA(SS) 10 53 D10 10 10
* SPI MOSI MOSI 11 / ICSP-4 51 D11 ICSP-4 16
* SPI MISO MISO 12 / ICSP-1 50 D12 ICSP-1 14
* SPI SCK SCK 13 / ICSP-3 52 D13 ICSP-3 15
*
*/
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
MFRC522::MIFARE_Key key;
/**
* Initialize.
*/
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
// Prepare the key (used both as key A and as key B)
// using FFFFFFFFFFFFh which is the default at chip delivery from the factory
for (byte i = 0; i < 6; i++) {
key.keyByte[i] = 0xFF;
}
Serial.println(F("Scan a MIFARE Classic PICC to demonstrate read and write."));
Serial.print(F("Using key (for A and B):"));
dump_byte_array(key.keyByte, MFRC522::MF_KEY_SIZE);
Serial.println();
Serial.println(F("BEWARE: Data will be written to the PICC, in sector #1"));
}
/**
* Main loop.
*/
void loop() {
// Look for new cards low power PCD and MCU etc...
mfrc522.PCD_ReducedPowerCardDetection(MCU, LPMCU_PCD_MS, TH, FW_V);
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
// Show some details of the PICC (that is: the tag/card)
Serial.print(F("Card UID:"));
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println();
Serial.print(F("PICC type: "));
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));
// Check for compatibility
if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI
&& piccType != MFRC522::PICC_TYPE_MIFARE_1K
&& piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
Serial.println(F("This sample only works with MIFARE Classic cards."));
return;
}
// In this sample we use the second sector,
// that is: sector #1, covering block #4 up to and including block #7
byte sector = 1;
byte blockAddr = 4;
byte dataBlock[] = {
0x01, 0x02, 0x03, 0x04, // 1, 2, 3, 4,
0x05, 0x06, 0x07, 0x08, // 5, 6, 7, 8,
0x08, 0x09, 0xff, 0x0b, // 9, 10, 255, 12,
0x0c, 0x0d, 0x0e, 0x0f // 13, 14, 15, 16
};
byte trailerBlock = 7;
MFRC522::StatusCode status;
byte buffer[18];
byte size = sizeof(buffer);
// Authenticate using key A
Serial.println(F("Authenticating using key A..."));
status = (MFRC522::StatusCode) mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
Serial.print(F("PCD_Authenticate() failed: "));
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
// Show the whole sector as it currently is
Serial.println(F("Current data in sector:"));
mfrc522.PICC_DumpMifareClassicSectorToSerial(&(mfrc522.uid), &key, sector);
Serial.println();
// Read data from the block
Serial.print(F("Reading data from block ")); Serial.print(blockAddr);
Serial.println(F(" ..."));
status = (MFRC522::StatusCode) mfrc522.MIFARE_Read(blockAddr, buffer, &size);
if (status != MFRC522::STATUS_OK) {
Serial.print(F("MIFARE_Read() failed: "));
Serial.println(mfrc522.GetStatusCodeName(status));
}
Serial.print(F("Data in block ")); Serial.print(blockAddr); Serial.println(F(":"));
dump_byte_array(buffer, 16); Serial.println();
Serial.println();
// Authenticate using key B
Serial.println(F("Authenticating again using key B..."));
status = (MFRC522::StatusCode) mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_B, trailerBlock, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
Serial.print(F("PCD_Authenticate() failed: "));
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
// Write data to the block
Serial.print(F("Writing data into block ")); Serial.print(blockAddr);
Serial.println(F(" ..."));
dump_byte_array(dataBlock, 16); Serial.println();
status = (MFRC522::StatusCode) mfrc522.MIFARE_Write(blockAddr, dataBlock, 16);
if (status != MFRC522::STATUS_OK) {
Serial.print(F("MIFARE_Write() failed: "));
Serial.println(mfrc522.GetStatusCodeName(status));
}
Serial.println();
// Read data from the block (again, should now be what we have written)
Serial.print(F("Reading data from block ")); Serial.print(blockAddr);
Serial.println(F(" ..."));
status = (MFRC522::StatusCode) mfrc522.MIFARE_Read(blockAddr, buffer, &size);
if (status != MFRC522::STATUS_OK) {
Serial.print(F("MIFARE_Read() failed: "));
Serial.println(mfrc522.GetStatusCodeName(status));
}
Serial.print(F("Data in block ")); Serial.print(blockAddr); Serial.println(F(":"));
dump_byte_array(buffer, 16); Serial.println();
// Check that data in block is what we have written
// by counting the number of bytes that are equal
Serial.println(F("Checking result..."));
byte count = 0;
for (byte i = 0; i < 16; i++) {
// Compare buffer (= what we've read) with dataBlock (= what we've written)
if (buffer[i] == dataBlock[i])
count++;
}
Serial.print(F("Number of bytes that match = ")); Serial.println(count);
if (count == 16) {
Serial.println(F("Success :-)"));
} else {
Serial.println(F("Failure, no match :-("));
Serial.println(F(" perhaps the write didn't work properly..."));
}
Serial.println();
// Dump the sector data
Serial.println(F("Current data in sector:"));
mfrc522.PICC_DumpMifareClassicSectorToSerial(&(mfrc522.uid), &key, sector);
Serial.println();
// Halt PICC
mfrc522.PICC_HaltA();
// Stop encryption on PCD
mfrc522.PCD_StopCrypto1();
}
/**
* Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);
}
} |
@KarlSix I'm quite interested how the |
Nope I haven't posted the code. |
When measuring with oscilloscope, I'm getting exactly 30 ms cycle with soft power down.
The results are very similar to jk987. However this does not require changing delays in the library (b/c no init is used in the loop) |
update: changed the PCD_WriteRegister to PCD_WriteRegister(TPrescalerReg, 0x43) as @jk987 suggested. Now the whole power on cycle is less than 15 mSec. If my estimates are correct and ESP8266 wont' add a lot, sleeping for one second and being active for 15 mSec should translate to 4-6 months on 2 AA batteries |
1.4mA is still a lot when battery powered, with arduino mini pro and rc522 total current consumption during sleep should be 60uA. |
agree. Need to solder out R1 and R2 and hope to get it down to 100uA or below |
@KarlSix Karl, I still would like to ask you to show us your mfrc522.PCD_ReducedPowerCardDetection. Please, is it possible or is it some secret? |
No secret for avr based microcontrollers it's simple you guys will figure it out. |
Here is the latest from my project
with reload timer set to 30 us, both card detection and reading the card tag are working fine and the cycle is reduced to 4 msec. For whatever reason further reducing the timer does not have visible effect on the timing.
As you might see, I did not want to change the library and introduced two additional functions in the code: mfrc522_fast_Reset and mfrc522_fastDetect. The latter does not really make any difference and I'll probably switch back to mfrc522.PICC_IsNewCardPresent() hope this helps someone |
oops. Forgot to uncomment one line in the code above. Should read
|
Here is the latest fast detection technique and some observations
without going into details, fastDetect3 is trying to check the device status without requiring data transfer from the mfrc. It returns true if detection gives anything other than timeout error. It could result in false positives (however I don’t see any false positives with device I have) and has to be followed by a slower library function (e.g. PICC_IsNewCardPresent) for an accurate detection. The detection cycle is around 1 mSec. This is much better than I expected at the beginning of the project! Two AA batteries voltage is 3033 mV and stays constant after 7.5 days of operation. Given ADC bit accounts for 8 mV, this means less than 1 mV/day voltage drop. The result is so good that I built a "final version" of the device to run on three AA batteries (without step up regulator and MOSFET that I mentioned in the previous comment) and convinced it will stay on for a year or two. The original device on two AA batteries is still on and I will let you know when it stops working (as I explained before, I expect ESP to stop emitting when the voltage is around 3 V which should take place in a month or so) the code:
|
Great job. I tried your idea with soft power down and extracting only important lines from MFRC522::PCD_CommunicateWithPICC() and it works fine! My detection cycle takes now cca 3.2 ms. I understand that most of it takes SPI communication between Atmega and RC522. Right now I'm having problem that I don't see any difference in setting various values of MFRC522_SPICLOCK on oscilloscope. In mfrc522.cpp there is always: |
@jk987,
This will force timeout in mfrc to occur much faster. I also was playing with SPI and did not see any significant difference (you'd have to change the speed in multiple places in the library). My SPI speed is library default |
I think this will not be the problem. I'm having TReloadReg 0x0190 and I'm swapping only TPrescalerReg values 0x05 (when testing card) and 0xA9 (original value when reading and writing). There is a weird in mfrc522.h that MFRC522_SPICLOCK is defined as SPI_CLOCK_DIV4 which I beleive is some one byte const. |
try also swapping TReloadReg. Switch it from 0x001E back to 0x0190 after detection |
@akellai Wow! Great work! |
here you go https://github.com/akellai/rfid-music
|
@akellai my sketch:
[ If mfrc522_fastDetect3 is looping, my multimeter shows me a draw of around 4mAh from the Card reader (LED on card reader removed). If a card is present it's around 5mAh. ] |
your sketch works fine with my board:
I noticed you are using different pins for RST/SS - should be no problem if you connected the board correctly. However 15 does not sound right for Pro Mini that I'm using. Does a standard example work on your board? |
@akellai I'm using a NodeMCU (ESP12 E), thats why the 15 (D8) Pin. It couldn't be the Pin as my main script is working fine and mfrc522_fastDetect1 and mfrc522_fastDetect2 are working fine as well. A bit weird... |
Interesting. You won't be able to achieve any reasonably low consumption with ESP b/c its wakeup cycle from deep sleep is ~300 mSec (at least I gave up this idea).
(shouldn't change anything IMHO). And also increase the timeout
instead of 10 |
@DimaVIII @akellai My opinion is that akellai has his fastDetect3 optimized to the edge and it can easilly happen that with other tags or other physical position of the reader and other metal things it doesn't work. Here is my piece of code I'm using for detection:
I think that the akellai magic was in setting TPrescalerReg and TReloadRegH/TReloadRegL. TReloadRegH/L I have 0x0200. But because I had a problem with this I ended up using my |
@akellai |
@itbetters, please take a look here https://github.com/akellai/rfid-music/blob/master/pinout.txt |
@akellai |
@itbetters, not sure but it reads "DE=A10". Could it be RT9193? |
@akellai Hello, I've been reading this and I think I will use you code in the project I'm working on. I just want to mention one thing: battery energy is not linear to battery voltage. That is, just because you battery dropped 10% of the initial voltage doesn't mean that the energy is 10% less than initial. In fact, most battery drop comparable amounts of voltage right at the start, that will explain the hockey stick figure you saw. Heres a diagram from a simple Duracell Coppertop AA battery: It's a bit tricky to interpret but this graph shows, in a way, the energy consumption of a battery. Energy = Power x Time and Power = Voltages x Amperage. Since the amperage is held constant for this curve, then you can imply that voltage is directly proportional to power AND voltage is directly related to energy for this graph. That means that the area under the curve equals the total energy capacity of the battery. As you can note, the energy capacity is largely dependent on the current consumption of the device. To estimate the energy left in the battery by reading the voltage (note: the voltage should be operating voltage, not open circuit voltage) you can draw a line. Say the voltage of a single cell is 1.2v. The area in red represents the energy already consumed by the load at that voltage and the area in green represents the energy left in the battery. Even though the voltage is 75% the nominal voltage, the area looks to be 20% of the total capacity. If I use your example, you stated that you voltage is 4.27 or 1.42 per cell. Assuming you used a duracell coppertop my best guess is that you battery is somewhere between 70-80% of total capacity. One last thing to note: depending on you cutoff voltage, the energy left within the battery could be useful. The built-in regulator, MIC5205, has a 17mV dropout which is next to nothing. However, that means that once the cell voltage approaches 1V or 3V in series, the energy left inside won't be used and is therefore wasted. Looking at the graph, I would say that that is about 5% leftover which is very good. This means the the usable capacity left in your batteries is about 65-75%. Assuming power consumption stays the same, the total lifespan of you batteries should be ~620 days and should be running out by Christmas this year. I'm sorry to intrude with this! I just hope this proves useful for future readers. |
This was exactly what I was looking for. Thank you so much. I was looking into how to get PICC_WakeupA working, but I haven't dived that deep into code before. This function does exactly what I needed it to do. However, I am using multiple RFID readers, so I've expanded on your code a little bit to make it work with multiple readers. See below.
Do note: this code is a bit redundant in the way it's currently programmed. I could simply remove Again, thank you @akellai for sharing your code! Also thanks to @octavio2895 for his addition to this discussion. This is indeed good information for anyone interested in doing any project working on batteries. |
OS version: W10___
Tried to save power by switching off and on when required. Help is appreciated |
I made an example how to use ESP32's deep sleep mode with MFRC522. I haven't done exact measurements yet, but a quick test shows you should be in the <100µA region with a 1s interval. That's good enough for my application. /* This is an example that show how to use MFRC522 with ESP32's deep sleep mode efficiently.
* In the deep sleep stub handler a quick check to see if a card is present is done (~1.5ms).
* Only if there is a card the full wake up sequence is initiated.
*
* In this handler almost all hardware is still uninitialized. Therefore all functions and data
* must be put into RTC RAM. That means you can't call any of the IDF or Arduino functions.
* Only ROM functions and direct register accesses are available.
* Therefore all hardware access functions had to be reimplemented. All functions intended to be
* called in deep sleep stub got an "ds" prefix.
*
* ATTENTION: Don't call these functions from your normal application. Only core 0 can access
* RTC fast RAM and normal arduino programms run on core 1.
*
* TODO: Hardware reset is unsupported at the moment.
*/
/******************* Configuration *****************/
#define DEBUG_PRINT_ENABLED 1
#define MFRC_CS 27
#define MFRC_SCK 12
#define MFRC_MOSI 4
#define MFRC_MISO 0
#define sleep_time_in_us 1000000ll
#include <Arduino.h>
#include <SPI.h>
#include <MFRC522.h>
#include "rom/rtc.h"
#include "soc/rtc_cntl_reg.h"
MFRC522 mfrc522 { MFRC_CS, UINT8_MAX };
#if DEBUG_PRINT_ENABLED
#include "soc/uart_reg.h"
static const char RTC_RODATA_ATTR debug_fmt_str[] = "---------> dbg: %d\n";
static const char RTC_RODATA_ATTR stub_fmt_str[] = "Deep sleep stub entered!\n";
static const char RTC_RODATA_ATTR wake_fmt_str[] = "Card detected. Waking up!\n";
static const char RTC_RODATA_ATTR sleep_fmt_str[] = "Sleeping again!\n";
#define DEBUG_PRINT ets_printf
#else
#define DEBUG_PRINT(...) do {} while (0)
#endif
/* Remember register offsets in RTC memory as esp32_gpioMux table is not available in deep sleep stub. */
uint32_t RTC_DATA_ATTR cs_reg = esp32_gpioMux[MFRC_CS].reg;
uint32_t RTC_DATA_ATTR sck_reg = esp32_gpioMux[MFRC_SCK].reg;
uint32_t RTC_DATA_ATTR mosi_reg = esp32_gpioMux[MFRC_MOSI].reg;
#define MFRC_REGISTER_READ_TIME 7 //us, used to calculate timeouts
static inline __attribute__((always_inline)) void dsGpioAsOutput(uint8_t pin, uint32_t reg_offset)
{
GPIO.enable_w1ts = ((uint32_t) 1 << pin);
ESP_REG(DR_REG_IO_MUX_BASE + reg_offset) = ((uint32_t) 2 << FUN_DRV_S) | FUN_IE | ((uint32_t) 2 << MCU_SEL_S);
}
static inline __attribute__((always_inline)) void dsDigitalWrite(uint8_t pin, bool value)
{
if (value) {
GPIO.out_w1ts = ((uint32_t) 1 << pin);
} else {
GPIO.out_w1tc = ((uint32_t) 1 << pin);
}
}
static inline __attribute__((always_inline)) uint32_t dsDigitalRead(uint8_t pin)
{
return (GPIO.in >> pin) & 0x1;
}
/* Hardware SPI is not initialized in deep sleep stub. */
uint8_t RTC_IRAM_ATTR dsSpiTransfer(uint8_t data)
{
dsDigitalWrite(MFRC_SCK, 0);
for (int i = 0; i < 8; i++) {
dsDigitalWrite(MFRC_MOSI, data & 0x80);
dsDigitalWrite(MFRC_SCK, 1);
data <<= 1;
data |= dsDigitalRead(MFRC_MISO);
dsDigitalWrite(MFRC_SCK, 0);
}
return data;
}
uint8_t RTC_IRAM_ATTR dsPCD_ReadRegister(MFRC522::PCD_Register reg)
{
dsDigitalWrite(MFRC_CS, 0);
dsSpiTransfer(0x80 | reg);
uint8_t result = dsSpiTransfer(0);
dsDigitalWrite(MFRC_CS, 1);
return result;
}
void RTC_IRAM_ATTR dsPCD_WriteRegister(MFRC522::PCD_Register reg, uint8_t value)
{
dsDigitalWrite(MFRC_CS, 0);
dsSpiTransfer(reg);
dsSpiTransfer(value);
dsDigitalWrite(MFRC_CS, 1);
}
bool RTC_IRAM_ATTR dsMFRC522_FastDetect()
{
dsPCD_WriteRegister(MFRC522::CollReg, 0);
dsPCD_WriteRegister(MFRC522::ComIrqReg, 0x7F);
dsPCD_WriteRegister(MFRC522::FIFOLevelReg, 0x80);
dsPCD_WriteRegister(MFRC522::FIFODataReg, MFRC522::PICC_CMD_REQA);
dsPCD_WriteRegister(MFRC522::BitFramingReg, 7);
dsPCD_WriteRegister(MFRC522::CommandReg, MFRC522::PCD_Transceive);
dsPCD_WriteRegister(MFRC522::BitFramingReg, 0x80 | 7);
// 50ms timeout. Much longer than required, but should not ever be used at all => does not matter.
for (uint32_t timeout = 0; timeout < 50000 / MFRC_REGISTER_READ_TIME; timeout++) {
uint8_t irq_flags = dsPCD_ReadRegister(MFRC522::ComIrqReg);
if (irq_flags & 0x30) {
// RxIrq || IdleIrq
return true;
}
if (irq_flags & 0x01) {
// TimeoutIrq
return false;
}
}
printf("Error\r\n");
return false;
}
void RTC_IRAM_ATTR dsMFRC522_FastReset()
{
dsGpioAsOutput(MFRC_CS, cs_reg);
dsGpioAsOutput(MFRC_SCK, sck_reg);
dsGpioAsOutput(MFRC_MOSI, mosi_reg);
// TODO: Set hardreset pin
// Reset & Wakeup
dsPCD_WriteRegister(MFRC522::CommandReg, MFRC522::PCD_SoftReset);
while ((dsPCD_ReadRegister(MFRC522::CommandReg) & (1 << 4))) {
// ~ 200us wake up time from power down
}
// Init timer
dsPCD_WriteRegister(MFRC522::TModeReg, 0x80); // TAuto=1; timer starts automatically at the end of the transmission in all communication modes at all speeds
dsPCD_WriteRegister(MFRC522::TPrescalerReg, 67); // 13.56MHz / (2 * 67 + 1) = ~100kHz => 10μs
dsPCD_WriteRegister(MFRC522::TReloadRegH, 0); // Reload timer with 30, ie 0.3ms before timeout.
dsPCD_WriteRegister(MFRC522::TReloadRegL, 30);
dsPCD_WriteRegister(MFRC522::TxASKReg, 0x40); // Default 0x00. Force a 100 % ASK modulation independent of the ModGsPReg register setting
dsPCD_WriteRegister(MFRC522::ModeReg, 0x3D); // Default 0x3F. Set the preset value for the CRC coprocessor for the CalcCRC command to 0x6363 (ISO 14443-3 part 6.2.4)
dsPCD_WriteRegister(MFRC522::TxControlReg, 0x83); // Antenna on
}
void RTC_IRAM_ATTR dsMFRC522_SoftPowerDown()
{
dsPCD_WriteRegister(MFRC522::CommandReg, MFRC522::PCD_NoCmdChange | 0x10);
}
void RTC_IRAM_ATTR esp_wake_deep_sleep(void)
{
DEBUG_PRINT(stub_fmt_str);
dsMFRC522_FastReset();
if (dsMFRC522_FastDetect()) {
// Card detected => Wake up system
DEBUG_PRINT(wake_fmt_str);
esp_default_wake_deep_sleep();
return;
} else {
// No card => go to sleep again
dsMFRC522_SoftPowerDown();
DEBUG_PRINT(sleep_fmt_str);
#if DEBUG_PRINT_ENABLED
//Wait till uart buffer is empty
while (REG_GET_FIELD(UART_STATUS_REG(0), UART_ST_UTX_OUT)) {
}
#endif
// https://gist.github.com/igrr/54f7fbe0513ac14e1aea3fd7fbecfeab with addition of setting new wake up time
// Add a fixed time offset to the current wake up time
uint64_t current_ticks = READ_PERI_REG(RTC_CNTL_SLP_TIMER0_REG) | (static_cast<uint64_t>(READ_PERI_REG(RTC_CNTL_SLP_TIMER1_REG)) << 32);
// same as rtc_time_us_to_slowclk(sleep_time_in_us, esp_clk_slowclk_cal_get())
uint64_t sleep_time_in_ticks = (sleep_time_in_us << 19) / REG_READ(RTC_SLOW_CLK_CAL_REG);
uint64_t new_ticks = current_ticks + sleep_time_in_ticks;
WRITE_PERI_REG(RTC_CNTL_SLP_TIMER0_REG, new_ticks & UINT32_MAX);
WRITE_PERI_REG(RTC_CNTL_SLP_TIMER1_REG, new_ticks >> 32);
// Set the pointer of the wake stub function.
REG_WRITE(RTC_ENTRY_ADDR_REG, (uint32_t )&esp_wake_deep_sleep);
// Go to sleep.
CLEAR_PERI_REG_MASK(RTC_CNTL_STATE0_REG, RTC_CNTL_SLEEP_EN);
SET_PERI_REG_MASK(RTC_CNTL_STATE0_REG, RTC_CNTL_SLEEP_EN);
// A few CPU cycles may be necessary for the sleep to start...
while (true) {
;
}
// never reaches here.
}
}
void setup()
{
Serial.begin(115200);
printf("setup() started\n");
if (rtc_get_reset_reason(0) == DEEPSLEEP_RESET) {
printf("Found card\n");
SPI.begin(MFRC_SCK, MFRC_MISO, MFRC_MOSI); //Enable hardware SPI
// Demo only: Dump card data
if (mfrc522.PICC_ReadCardSerial()) {
mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}
} else {
printf("No card present\n");
}
printf("Entering deep sleep\n");
esp_deep_sleep(sleep_time_in_us);
}
void loop()
{
} |
So I want to give your code a go, but a bit insure on the wiring between the ESP32 D1 mini and the RC522. How can I see what GIOP pins you are using on the ESP32? |
Pin configuration is right at the beginning:
You should be able to use any pins you want. |
Thanks that helped. A nother question. I seem to have some issue scanning some of my NFC/RFID tags when running this code. Also I'm trying to implement ESP NOW to push out the ID tag to a server. Would it be appropriate to call all the ESP now initialization in the void setup() after the card is found? |
I interests build rfid door lock rc522+mcu (328p) you can share information. |
Hi . |
According to this (chapter 8.6.1, page 33) I guess you can't: https://www.nxp.com/docs/en/data-sheet/MFRC522.pdf Seems quite logical because how would you wake it up again? |
thank you very much for your reply.
|
Thanks so much to @herm for that ESP32 code. I had to make a couple of modifications to get it working for me, which may be of help to anyone else trying to use it:
(gpioMux is obsolete in the current version of ESP32-IDF)
with
(Unlike gpioMux, GPIO_PIN_MUX_REG is available from within the stub, so no need to make special RTC variables anymore.)
This allows an extra millisecond for the card to get ready. Without this, like @hemandk I was finding that detection was very hit and miss, and when it did work the effective range was drastically reduced. After trying various things I had a hunch that everything was just happening a bit too quickly, and tried this extra delay, and it fixed it totally. 1000 was my first guess, and turned out to be right on the money: 500 and even 750 are not enough. But I only have one MFRC522 so I don't know if it will be the same with every reader, there might be some variation. Using this method I'm measuring an average current of just a few mA, about an order of magnitude less than my best previous method! |
I would take advance of this topic to ask your kind suggestion.
|
I think consumption can be much lower if wakeup stub code works on the ULP coprocessor of the ESP32. |
Pro tip: Only turn on the antenna right before issuing the start request to save extra power:
|
@Rotzbua This seemed like the most appropriate place to ask: I am running a small project off a 9v battery and would like to improve its lifespan. Currently it only lasts a few hours because its running items. Is there a way to run the reader on a low power mode only so that it detects an rfid tag and sends an interrupt so I can know when to turn everything else back on? |
And is there a way to have it do this with the arduino on low power mode? |
No, sorry. The whole point of this thread is because the MFRC522 cannot do low power card detection and has no way of waking up the MCU when it does detect a card. Polling is the only answer. With an ESP32 you can do this from a deep sleep stub (see herm's code earlier in the thread, and my updates to it); I don't know if there's anything similar on Arduino, but Arduino are usually not a great choice for low power. ESPs are better, and STMs better still (but harder to use). There are other RFID readers that support LPCD properly and can wake the MCU when they detect a card. |
Is it possible to run the code on a board (PN532) with I2C protocol? |
Hello!
Reading the MFRC522 data sheet, it seems like it supports several power-saving modes, including a "soft power-down" mode (http://www.nxp.com/documents/data_sheet/MFRC522.pdf). Is there a way to use this functionality from this RFID library?
Or, generally, for battery operation, could you document some best practices for saving power when using this library?
Thanks!
The text was updated successfully, but these errors were encountered: