Problem with writting on EEPROM

Greetings friends!!!

I am currently working on a token dispenser which is supposed to have a RTC and MP3 module and thermal printer. whenever the button is pressed the MP3 module says the token number and thermal printer prints the token with time stamps on it. To keep the track of the token count in case of power failure I decded to push the token count on EEPROM so that it can be fetched back. But the problem is after certain counts the token count automatically jumps to random number and never gets back to normal counting. Like the machine may go from 1 to 16 sequentially but then it randomly jumps to 62 or 122 or any number like wise. although I have set a constraint so that the token number wouldn’t go beyond 100 but it doesn’t work accordingly. I am posting the code. Please help me to sort this thing out m really stuck with problem since last three months.

#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"
#include <EEPROM.h>
#include "Adafruit_Thermal.h"

#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;
int address = 10;

#define TX_PIN 6 // Arduino transmit  YELLOW WIRE  labeled RX on printer
#define RX_PIN 5 // Arduino receive   GREEN WIRE   labeled TX on printer

SoftwareSerial mySerial(RX_PIN, TX_PIN); // Declare SoftwareSerial obj first
Adafruit_Thermal printer(&mySerial);     // Pass addr to printer constructor


SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;

int count = 0;

int chiran = 0;
int token;

int minite;
int hor;
int CurrentDate;

int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

int relay = 4;
boolean stat = false;
int minutes;
int hours;

void setup()
{
  if (! rtc.begin())
  {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (rtc.lostPower())
  {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
//        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    //     rtc.adjust(DateTime(2019, 2, 27, 8, 16, 0));
  }

  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);
  mySerial.begin(9600);
  printer.begin();

  mySoftwareSerial.begin(9600);
  Serial.begin(115200);

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while (true) {
      delay(0); // Code to compatible with ESP8266 watch dog.
    }
  }
  Serial.println(F("DFPlayer Mini online."));

  myDFPlayer.volume(30);  //Set volume value. From 0 to 30
  //myDFPlayer.play(1);  //Play the first mp3

  pinMode(3, INPUT);
  DateTime now = rtc.now();
  hours = now.hour();
  Serial.print("Hours: ");
  Serial.println(hours);

//EEPROM.write(address, count);
  int trial = EEPROM.read(address);
  Serial.print("trial:");
  Serial.println(trial);
}

void loop()
{
  DateTime now = rtc.now();
  //  CurrentDate = now.day();
  digitalWrite(4, HIGH); //relay
  int reading = digitalRead(3);

  if (reading != lastButtonState)
  {
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay)
  {
    if (reading != buttonState)
    {
      buttonState = reading;
      if (buttonState == HIGH)
      {
        DateTime now = rtc.now();
        //        delay(1000);
        chiran = EEPROM.read(address);
        Serial.print("chiran before increment: ");
        Serial.println(chiran);
        token  = ++chiran;
        Serial.print("token:");
        Serial.println(token);
        myDFPlayer.play(token);
        delay(1000);

        Serial.println("thermal printer");

        printer.justify('C');
        printer.doubleHeightOn();
        printer.boldOn();
        printer.println("");
        //  printer.clear();
        printer.println("Dr. N. M. Lunawat");
        printer.doubleHeightOff();
        printer.setSize('S');
        printer.println(F("B.E.H.M.S.(Bom.)"));
        printer.println(F("D.Pharm, N.D.(Poona)"));
        printer.boldOff();

        printer.setSize('S');
        printer.println(F("Shankar Nagar, Takli Road,Nashik"));
        printer.justify('C');
        printer.println(F("----------------------------"));

        printer.justify('L');
        //printer.print(F("Date:"));
        printer.print(now.day(), DEC);
        printer.print('/');
        printer.print(now.month(), DEC);
        printer.print('/');
        printer.print(now.year(), DEC);

        printer.print(F("            "));
        //printer.println(F("Time:"));
        printer.print(now.hour(), DEC);
        printer.print(':');
        printer.print(now.minute(), DEC);
        printer.print(':');
        printer.print(now.second(), DEC);
        printer.println();

        printer.println(F(""));
        printer. justify('C');
        printer.println(F("WE CARE..."));
        printer.doubleHeightOn();
        printer.boldOn();
        printer.println(token);
        printer.doubleHeightOff();
        printer.boldOff();
        printer.println(F("WE TAKE CARE..."));

        printer.println(F(""));
        printer.justify('L');
        printer.setSize('S');

        printer.print(F("Estimated Time:"));
        minite = now.minute() + 5;
        if (minite > 60)
        {
          hor = now.hour() + 1;
          printer.print(hor);
          printer.print(':');
          switch (minite)
          {
            case 61:
              printer.print(F("1"));
              break;

            case 62:
              printer.print(F("2"));
              break;

            case 63:
              printer.print(F("3"));
              break;

            case 64:
              printer.print(F("4"));
              break;

            case 65:
              printer.print(F("5"));
              break;
          }
        }
        else
        {
          printer.print(now.hour(), DEC);
          printer.print(':');
          printer.print(minite);
        }

        printer.print(':');
        printer.print(now.second(), DEC);
        printer.println();

        printer. justify('C');
        printer.println(F("----------------------------"));
        printer.println(F(""));
        printer.println(F(""));

        if (token > 100)
        {
          token = 0;
        }
        EEPROM.write(address, token);
        
      }
    }
  }
  lastButtonState = reading;

  if (now.hour() == 0)
  {
    count = 0;
    EEPROM.write(address, count);
  }
 }

I'm taking a bit of a guess here, but I'm wondering if it's to do with all your variables being ints while eeprom reads and writes are bytes.

neiklot: I'm taking a bit of a guess here, but I'm wondering if it's to do with all your variables being ints while eeprom reads and writes are bytes.

Ok I didn't got it....so what hanges do I need to make. can you please elaborate it

Ok I didn't got it....so what hanges do I need to make. can you please elaborate it

For writing and reading 2 byte integers use EEPROM.put() and EEPROM.get() and increment the addresses by 2.

cattledog: For writing and reading 2 byte integers use EEPROM.put() and EEPROM.get() and increment the addresses by 2.

I may sound bit amatuer but can you please help me out how am gonna fetch back the count if its written on diffeerent location.

cattledog: For writing and reading 2 byte integers use EEPROM.put() and EEPROM.get() and increment the addresses by 2.

should it be something like this?

EEPROM.put(address, token);

intead of EEPROM.write(address, token);

and for incrementing address

address += sizeof(token)

is that correct?

I just tested this:

//eeprom put and get integers

#include <EEPROM.h>

int myInt1 = 12345;
int myInt2 = 999;
int myInt3 = 22222;

int myInt10;
int myInt20;
int myInt30;

void setup() {

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("values");
  Serial.println(myInt1);
  Serial.println(myInt2);
  Serial.println(myInt3);
  Serial.println("putting");
  int eeAddress = 0;   //Location we want the data to be put.
  Serial.println(eeAddress);
  EEPROM.put(eeAddress, myInt1);
  eeAddress += sizeof(int);
  Serial.println(eeAddress);
  EEPROM.put(eeAddress, myInt2);
  eeAddress += sizeof(int);
  Serial.println(eeAddress);
  EEPROM.put(eeAddress, myInt3);

  Serial.println("getting");
  eeAddress = 0;   //Location we want the data to be got
  Serial.println(eeAddress);
  EEPROM.get(eeAddress, myInt10);
  Serial.println(myInt10);
  eeAddress += sizeof(int);
  Serial.println(eeAddress);
  EEPROM.get(eeAddress, myInt20);
  Serial.println(myInt20);
  eeAddress += sizeof(int);
  Serial.println(eeAddress);
  EEPROM.get(eeAddress, myInt30);
  Serial.println(myInt30);


}

void loop() {
 
}

neiklot:
I just tested this:

//eeprom put and get integers

#include <EEPROM.h>

int myInt1 = 12345;
int myInt2 = 999;
int myInt3 = 22222;

int myInt10;
int myInt20;
int myInt30;

void setup() {

Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println(“values”);
  Serial.println(myInt1);
  Serial.println(myInt2);
  Serial.println(myInt3);
  Serial.println(“putting”);
  int eeAddress = 0;  //Location we want the data to be put.
  Serial.println(eeAddress);
  EEPROM.put(eeAddress, myInt1);
  eeAddress += sizeof(int);
  Serial.println(eeAddress);
  EEPROM.put(eeAddress, myInt2);
  eeAddress += sizeof(int);
  Serial.println(eeAddress);
  EEPROM.put(eeAddress, myInt3);

Serial.println(“getting”);
  eeAddress = 0;  //Location we want the data to be got
  Serial.println(eeAddress);
  EEPROM.get(eeAddress, myInt10);
  Serial.println(myInt10);
  eeAddress += sizeof(int);
  Serial.println(eeAddress);
  EEPROM.get(eeAddress, myInt20);
  Serial.println(myInt20);
  eeAddress += sizeof(int);
  Serial.println(eeAddress);
  EEPROM.get(eeAddress, myInt30);
  Serial.println(myInt30);

}

void loop() {

}

thanks for the greatest help I will surely try this and get back to tell if did sorted out my problem or not

Neiklot. I am really thankful for the help you did but I am really confused how should I integrate those things in my code. Like I need to push the value of token count after a particular key is pressed. What I am really confused about is, initially when I will press the key the token count will increment from 0 and written to 0th address, when I press the key next time I am supposed to fetch that token count from the 0th location but then i would have already incremented the address. Also even if I reference the address variable to 0 and fetch the token count from there, then on the next key press the sequence will get messed up. can you please help me to make it more simple for me. I am not asking to actually write the code for me, but what I expect is it would be very helpful for me if you could guide me with how can I integrate this into my code. Awaiting your kind response

I’d love to help but I’m struggling to understand what it is you’re trying to do.

First I’m confused about the words “token” and “count”. You have variables called token and count, but in that last post you use the phrase “token count” with both words together :wink:

So let’s just use a generic variable name myVar:

You have an int called myVar, which needs to get written to eeprom on the first (and presumably every subsequent odd) press of a button? It goes in addresses 0 and 1. On the 2nd (and presumably every future even press) those two bytes get read back to the same variable, myVar?

Along the way, myVar gets changed, so that each odd press, the current value in myVar is saved?

Is that correct?

So if myVar is always EEPROM.put() to address 0 and 1, and then obviously EEPROM.get()-ed from there, you don’t need to have a variable eeAddress. You can just put to 0 and get from 0.

If there are other integer variables that need saving, they would be (say) in 2&3 and 4&5; no need for a variable to hold those addresses.

I’m not sure what you need help with, but let’s start by testing if my understanding is correct.

(One thought: if you have the same button for put-ting and get-ting, it might me easier to use two different buttons…)

PS, thinking a bit more, I remembered that you said the retrieval is for after power fail and restore. So a press for a retrieval is a “first” press not a “second” so I would definitely go with two buttons a and B.

So the scenario is:

run sketch for first time
initialise myVar to 0
press A, increment myVar to 1, put
press A, increment myVar to 2, put
press A, increment myVar to 3, put
press A, increment myVar to 4, put
power goes off
power comes back
sketch starts from the beginning
initialise myVar to 0
press B, get myVar back as 4

Correct?

To keep the track of the token count in case of power failure I decded to push the token count on EEPROM so that it can be fetched back. But the problem is after certain counts the token count automatically jumps to random number and never gets back to normal counting.

It sounds like you have resolved the issue of an int occupying two bytes of eeprom memory.

So if myVar is always EEPROM.put() to address 0 and 1, and then obviously EEPROM.get()-ed from there, you don't need to have a variable eeAddress. You can just put to 0 and get from 0.

Yes, as a simple starting point, you can always write and read at the same address. If the token count always resided at address 0 and 1. I think it meets the functional needs of your program.

Is this correct?

With this simple approach there is a potential problem in that the EEPROM memory is only specified to work for a limited number of writes. The spec is probably 100K writes to an address (reads have not limit), but that is very conservative.

For heavy eeprom use, people use wear leveling routines. That is, the storage location is moved around so that the use is distributed over the entire eeprom space. Google on the term " Arduino eeprom wear leveling"

Wear leveling complicates recovery after a power failure because you need to figure out where the current valid data is located. There are several ways to implement wear leveling. The fact that you have sequential data makes the task easier, but I would leave that refinement to the point where you have the program working as you want.

First of all my hearties thanks to Neiklot and cattledog. And M extremelysorry for confusing with "token and "count. What I meant is its a token dispenser system. I need to store the last token dispensed in EEPROM. But like Neiklot said I don't need to store the last token each time on different memory location so i guess that solves my problem. But as per cattledog u r guiding me m really worried about what after 100K write cycles? and if I use wear leveling then i will have to face the problem which u told m about also each time changing the eeaddress and retreiving back from the changed eeAddress woulb bit difficult me to figure out. For now I am not going to keep the eeAddress variable and would be using 0 and 1 eeAddress only and lets see what it yeilds. I will get back with results. Once again very very thanks to both of you for ur timely help. Stay blessed

There are several methods to get around EEPROM write-life…
You can nponitor the power, and if it’s going down - detect that and save the volatile values as needed.
When it restarts - reload them from EEPROM.

A diode, two resistors, and 470uF capacitor on Vin (and an analog input) will let you write EEPROM reliably & safely when power goes down. Save also if you’re doing a crash-stop or restart from software.

I used this on a product for over two years with hundreds in the field.

if I use wear leveling then i will have to face the problem which u told m about also each time changing the eeaddress and retreiving back from the changed eeAddress woulb bit difficult me to figure out.

I see that you are going to use an RTC in the sketch. You should be able to use the month to spread the values over 12 locations instead of simply 0/1. This approach should be easier to implement than some of the other wear leveling routines.

For example Jan token numbers in address 0 and 1 Feb token numbers in address 2 and 3 March token numbers in address 4 and 5

etc.

If all the eeprom locations are preloaded loaded with zeros, it will help if there is a power failure over a month transition. When recovering from power down, read the rtc, get the current month and go to the address for the current month, if the read value is 0, go to the previous months address for the last count.

When you get to a new year, you can move everything to the next set of 24 addresses. With 1024 addresses in eeprom, you will get 42 years with this approach to the address management.

You will have a record of monthly tokens issued in the EEPROM which might be useful.

lastchancename:
There are several methods to get around EEPROM write-life…
You can nponitor the power, and if it’s going down - detect that and save the volatile values as needed.
When it restarts - reload them from EEPROM.

A diode, two resistors, and 470uF capacitor on Vin (and an analog input) will let you write EEPROM reliably & safely when power goes down. Save also if you’re doing a crash-stop or restart from software.

I used this on a product for over two years with hundreds in the field.

lastchancename I will surely try this one. Thanks for a great help. Can you please help me out how should I detect the power failure?

cattledog:
I see that you are going to use an RTC in the sketch. You should be able to use the month to spread the values over 12 locations instead of simply 0/1. This approach should be easier to implement than some of the other wear leveling routines.

For example
Jan token numbers in address 0 and 1
Feb token numbers in address 2 and 3
March token numbers in address 4 and 5

etc.

If all the eeprom locations are preloaded loaded with zeros, it will help if there is a power failure over a month transition. When recovering from power down, read the rtc, get the current month and go to the address for the current month, if the read value is 0, go to the previous months address for the last count.

When you get to a new year, you can move everything to the next set of 24 addresses. With 1024 addresses in eeprom, you will get 42 years with this approach to the address management.

You will have a record of monthly tokens issued in the EEPROM which might be useful.

Thats really great idea and m surely gonna implement this. But for now changing EEPROM.write() to EEPROM.put() didn’t yeilded expected results!!

It was all good for two day but this morning it started the count from 122 surprisingly!!! and this shouldn’t even happen bcoz I use a loop which sets the count to 0 if it goes beyond 100. This is the code I am using right now

#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"
#include <EEPROM.h>
#include "Adafruit_Thermal.h"

#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;
int address = 20;

#define TX_PIN 6 // Arduino transmit  YELLOW WIRE  labeled RX on printer
#define RX_PIN 5 // Arduino receive   GREEN WIRE   labeled TX on printer

SoftwareSerial mySerial(RX_PIN, TX_PIN); // Declare SoftwareSerial obj first
Adafruit_Thermal printer(&mySerial);     // Pass addr to printer constructor


SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;

int count = 0;

int chiran = 0;
int token;

int minite;
int hor;
int CurrentDate;

int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

int relay = 4;
boolean stat = false;
int minutes;
int hours;

void setup()
{
  if (! rtc.begin())
  {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (rtc.lostPower())
  {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
//        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    //     rtc.adjust(DateTime(2019, 2, 27, 8, 16, 0));
  }

  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);
  mySerial.begin(9600);
  printer.begin();

  mySoftwareSerial.begin(9600);
  Serial.begin(115200);

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while (true) {
      delay(0); // Code to compatible with ESP8266 watch dog.
    }
  }
  Serial.println(F("DFPlayer Mini online."));

  myDFPlayer.volume(30);  //Set volume value. From 0 to 30
  //myDFPlayer.play(1);  //Play the first mp3

  pinMode(3, INPUT);
  DateTime now = rtc.now();
  hours = now.hour();
  Serial.print("Hours: ");
  Serial.println(hours);

  EEPROM.put(address, count);
  int trial = EEPROM.read(address);
  Serial.print("trial:");
  Serial.println(trial);
}

void loop()
{
  DateTime now = rtc.now();
  //  CurrentDate = now.day();
  digitalWrite(4, HIGH); //relay
  int reading = digitalRead(3);

  if (reading != lastButtonState)
  {
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay)
  {
    if (reading != buttonState)
    {
      buttonState = reading;
      if (buttonState == HIGH)
      {
        DateTime now = rtc.now();
        //        delay(1000);
        EEPROM.get(address, chiran);
        Serial.print("chiran before increment: ");
        Serial.println(chiran);
        token  = ++chiran;
        Serial.print("token:");
        Serial.println(token);
        myDFPlayer.play(token);
        delay(1000);

        Serial.println("thermal printer");

        printer.justify('C');
        printer.doubleHeightOn();
        printer.boldOn();
        printer.println("");
        //  printer.clear();
        printer.println("Dr. N. M. Lunawat");
        printer.doubleHeightOff();
        printer.setSize('S');
        printer.println(F("B.E.H.M.S.(Bom.)"));
        printer.println(F("D.Pharm, N.D.(Poona)"));
        printer.boldOff();

        printer.setSize('S');
        printer.println(F("Shankar Nagar, Takli Road,Nashik"));
        printer.justify('C');
        printer.println(F("----------------------------"));

        printer.justify('L');
        //printer.print(F("Date:"));
        printer.print(now.day(), DEC);
        printer.print('/');
        printer.print(now.month(), DEC);
        printer.print('/');
        printer.print(now.year(), DEC);

        printer.print(F("            "));
        //printer.println(F("Time:"));
        printer.print(now.hour(), DEC);
        printer.print(':');
        printer.print(now.minute(), DEC);
        printer.print(':');
        printer.print(now.second(), DEC);
        printer.println();

        printer.println(F(""));
        printer. justify('C');
        printer.println(F("WE CARE..."));
        printer.doubleHeightOn();
        printer.boldOn();
        printer.println(token);
        printer.doubleHeightOff();
        printer.boldOff();
        printer.println(F("WE TAKE CARE..."));

        printer.println(F(""));
        printer.justify('L');
        printer.setSize('S');

        printer.print(F("Estimated Time:"));
        minite = now.minute() + 5;
        if (minite > 60)
        {
          hor = now.hour() + 1;
          printer.print(hor);
          printer.print(':');
          switch (minite)
          {
            case 61:
              printer.print(F("1"));
              break;

            case 62:
              printer.print(F("2"));
              break;

            case 63:
              printer.print(F("3"));
              break;

            case 64:
              printer.print(F("4"));
              break;

            case 65:
              printer.print(F("5"));
              break;
          }
        }
        else
        {
          printer.print(now.hour(), DEC);
          printer.print(':');
          printer.print(minite);
        }

        printer.print(':');
        printer.print(now.second(), DEC);
        printer.println();

        printer. justify('C');
        printer.println(F("----------------------------"));
        printer.println(F(""));
        printer.println(F(""));

        Serial.println("thermal printer done");
        
        if (token > 100)
        {
          token = 0;
        }
        EEPROM.put(address, token);
        
      }
    }
  }
  lastButtonState = reading;

  if (now.hour() == 0)
  {
    count = 0;
    EEPROM.write(address, count);
  }
 }

You appear to be using a mixture of write()/read() and put()/get() to/from the same address. Is that deliberate ?

I see the following use of the EEPROM at 5 places in your code your code

EEPROM.put(address, count);//in setup and count == 0
int trial = EEPROM.read(address)
EEPROM.get(address, chiran);
EEPROM.put(address, token);
EEPROM.write(address, count);

count, token and chiran all all integers and take two memory locations.

You need to consistently use .put() and .get() to save and retrieve with these integers.

Do not use .read() and .write(), they are for single bytes only.

Clean this up, and see if the mystery values are resolved.

OP, Have a look at my post in this thread I made a while ago. https://forum.arduino.cc/index.php?topic=563839.0

The regulators are irrelevant, but if you divide* your primary, dirty DC input, and put a decent capacitor (470uF#) ‘after’ the diode you can fast poll that analogue input to determine if the voltage is below your required threshold.

470uF let’s me reliably save around 2K of data to EEPROM.

  • a 47K / 10 K divider gives approx 28V of input range (0-1023).

Based on this, I either - do nothing, warn of low input voltage, or save EEPROM and enter shutdown/crash stop mode and while(1) loop. With a reset or power up, restore your EEPROM values to RAM, and get going again as appropriate.

cattledog: I see the following use of the EEPROM at 5 places in your code your code

EEPROM.put(address, count);//in setup and count == 0
int trial = EEPROM.read(address)
EEPROM.get(address, chiran);
EEPROM.put(address, token);
EEPROM.write(address, count);

count, token and chiran all all integers and take two memory locations.

You need to consistently use .put() and .get() to save and retrieve with these integers.

Do not use .read() and .write(), they are for single bytes only.

Clean this up, and see if the mystery values are resolved.

Ok I really missed to look at those in hurry. I will check fixing those and get back to tell u the results