So i created a class and when i created objects and use them, they seem to share their variables between each other ( the currentReading, previousReading and the time variable). how can i create objects that have their own variables so that type of conflict cant happen?
code : ( read the buttons and print them in the lcd screen)
#include <LiquidCrystal.h>
LiquidCrystal lcd(6, 5, 3, 2, 1, 0);
class button {
public:
void SetupButton(int pino);
int Read();
private:
int _pin;
};
void button::SetupButton(int pin) {
pinMode(pin, INPUT_PULLUP);
_pin = pin;
}
int button::Read() {
static boolean currentReading, previousReading = 1;
static unsigned long time;
currentReading = digitalRead(_pin);// reading
if (previousReading - currentReading == 1) { // when reading gos from 1 to 0
time = millis();
}
if (currentReading - previousReading == 1 && (50 < (millis() - time) < 500)) { // when reading gos back to 1 before 500ms
previousReading = currentReading;
return 1;
}
if (3000 > (millis() - time) && (millis() - time) > 500 && !currentReading) { // when reading keeps in 0 after 500ms
previousReading = currentReading;
return 2;
}
if ((millis() - time) > 3000 && !currentReading) { // // when reading keeps in 0 after 3000ms
previousReading = currentReading;
return 3;
}
previousReading = currentReading; // current reading becomes the previous
return 0;
}
button up;
button down;
void setup() {
lcd.begin(16, 2);
up.SetupButton(A0);
down.SetupButton(A1);
}
void loop() {
lcd.setCursor(0, 0);
lcd.print(up.Read());
lcd.print(down.Read());
}
ps : i already know how to do this without using classes but doing it with classes makes the code much cleaner so i am trying to achieve this
up = button(4);
It is normal to pass essential attributes in the constructor.