0

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?

asked Sep 26, 2016 at 1:08
2

1 Answer 1

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.

answered Sep 26, 2016 at 4:59
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.