So, I have 3 buttons to a arduino. I want to detect the button press on the 3 of them.
For that, i've created a function:
int OnKeyPress (int port) {
int LastState, BeginState, r;
r = 0;
BeginState = digitalRead(port);
if (BeginState != LastState) {
if (BeginState == 1) r = 1 ;
}
delay(5);
LastState = BeginState;
return r;
}
I want to instantiate 3 instances of this code, separately and they have to retain this variables int LastState, BeginState, r;
for each button, and the next time the function runs on the loop, the variables are the same of when they ran last time.
Just, how?
1 Answer 1
This is an ordinary method (function) which can not be instantiated. It is necessary to write a class with 1 or more methods in it in order to instantiate multiple copies of that class and the method(s) with in that class.
The integers "LastState", "BeginState" and "r" only have scope within the method and will not survive after returning from the method. There are several approaches to preserve these variables from one call to the next. They can be declared as static integers. Or they can be defined globally.
It appears you are recreating the existing Bounce library. I encourage you to continue if you are learning. However, you may want to look at the Bounce library's code for guidance.
class
. tutorialspoint.com/cplusplus/cpp_classes_objects.htm