RobertoPasic
Newbie level 6
Hi there, I use eeprom in RTC DS3231 with Arduino uno, I need to save number of button press, every HIGH state on button need to increment counter and save number on eeprom,
I need counter value max 9999, in my case after 255 counter start from 0 again, can somebody help with advice?
thanks
my code
I need counter value max 9999, in my case after 255 counter start from 0 again, can somebody help with advice?
thanks
my code
Code:
#include <DS3231.h>
DS3231 rtc(SDA, SCL);
#include "Wire.h"
#define EEPROM_I2C_ADDRESS 0x57
const int buttonPin1 = 7; // pin7 button in
int buttonState1 = 0; // start value for button
int Val = 0; // counter for the number of button presses
int readVal = 0; // read value from address 0
int sum = 0; // sum readVal + new
int freshVal = 0; // print last sum
void setup() {
Wire.begin();
Serial.begin(19200);
rtc.begin();
//The following lines can be uncommented to set the date and time
//rtc.setTime(16, 31, 0); // Set the time to 15:36:00 (24hr format)
//rtc.setDate(06, 06, 2020); // Set the date to 19 Noemvri 2019
pinMode(buttonPin1, INPUT);
readVal = readEEPROM(0, EEPROM_I2C_ADDRESS); //if you need to reset value on addres 0 comment this line
//writeEEPROM(0, 0, EEPROM_I2C_ADDRESS); //uncomment this line to write 0 on addres 0
}
void loop() {
buttonState1 = digitalRead(buttonPin1);
delay(100);
if (buttonState1 == HIGH) { // if button is High
dothis();
} else {
delay(50);
}
}
void dothis() {
Val++;
sum = readVal + Val;
writeEEPROM(0, sum, EEPROM_I2C_ADDRESS);
freshVal = readEEPROM(0, EEPROM_I2C_ADDRESS);
delay(100);
Serial.println(freshVal); //print freshVal
}
void writeEEPROM(int address, byte sum, int i2c_address){
// Begin transmission to I2C EEPROM
Wire.beginTransmission(i2c_address);
// Send memory address as two 8-bit bytes
Wire.write((int)(address >> 8)); // MSB
Wire.write((int)(address & 0xFF)); // LSB
// Send data to be stored
Wire.write(sum);
// End the transmission
Wire.endTransmission();
// Add 5ms delay for EEPROM
delay(5);
}
byte readEEPROM(int address, int i2c_address){
// Define byte for received data
byte rcvData = 0x00;
// Begin transmission to I2C EEPROM
Wire.beginTransmission(i2c_address);
// Send memory address as two 8-bit bytes
Wire.write((int)(address >> 8)); // MSB
Wire.write((int)(address & 0xFF)); // LSB
// End the transmission
Wire.endTransmission();
// Request one byte of data at current memory address
Wire.requestFrom(i2c_address, 1);
// Read the data and assign to variable
rcvData = Wire.read();
// Return the data as function output
return rcvData;
}