1

I am making a keypad and when I try to save the buttons that were pushed they reset back to zero.

int tmp = 1;
int digit = 1;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int code = 0;
void setup() {
 Serial.begin(9600);
 pinMode(7, INPUT);
 pinMode(2, INPUT);
 pinMode(3, INPUT);
 pinMode(4, INPUT);
 pinMode(5, INPUT);
 pinMode(6, INPUT);
 pinMode(9, OUTPUT);
 pinMode(8, OUTPUT);
}
void loop() {
 if (digit > 4) {
 digit = 1;
 }
 for (int i = 2; i <= 7; i++) {
 int tmp = digitalRead(i);
 if (tmp == HIGH) {
 if (digit == 1) {
 int a = i - 1;
 }
 if (digit == 2) {
 int b = i - 1;
 }
 if (digit == 3) {
 int c = i - 1;
 }
 if (digit == 4) {
 int d = i - 1;
 Serial.print(a);
 Serial.print(b);
 Serial.print(c);
 Serial.print(d);
 digitalWrite(8, HIGH);
 }
 digitalWrite(9, HIGH);
 delay(100);
 digitalWrite(9, LOW);
 delay(100);
 Serial.print(i);
 digit++;
 }
 }
}
dda
1,5951 gold badge12 silver badges17 bronze badges
asked Sep 15, 2017 at 1:14
4
  • There is a library for a keypad: github.com/Chris--A/Keypad If you want to make your own code, you have to specify what you want: should multiple keys presses at the same time being detected ? should there be debouncing ? do you want to know how long a key is pressed ? Commented Sep 15, 2017 at 3:07
  • I already have key detection but for some reason when I have it output variables A B C and D it only stores the last digit and the rest are 0 Commented Sep 15, 2017 at 4:10
  • @NathanAnderson - The compiler would be warning you about the issue, but warnings are turned off in the Arduino IDE by default. Commented Sep 15, 2017 at 7:33
  • You can make your code more flexible by keeping a running total (int total = 0;) and just add to it with each keypress: total = (total * 10) + i; - where i is the most recent digit input by the user. Commented Sep 15, 2017 at 13:11

1 Answer 1

3

Do you know what int a; does?

For example you have a global variable a and then you have local a. Local one hides global one.

In all cases you're changing local variables. Then you're printing global a,b,c and local d.

answered Sep 15, 2017 at 6:15
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.