Reputation: 1
New to programming. Using PIC18F4520 with a MM74C922N 4x4 matrix keypad connected to Port A bits 0 to 3. Basically this keypad has a 4 bit output(DCBA) that corresponds to what key was pressed based on the table below. What I want to do is to have a variable switch between 2 states when the '1' key is pressed(DCBA = 0000). When '1' is pressed, variable = 1. When '1' is pressed again, variable = 2. When '1' is pressed yet again, variable = 1. So and and so forth... Any help is appreciated
Code:
char keypressed[16] = { '1', '2', '3', 'F', '4', '5', '6', 'E', '7', '8', '9', 'D', 'A', '0', 'B', 'C' };
if(key == keypressed[0])
... //Variable setting
Upvotes: 0
Views: 140
Reputation: 8237
There are many ways of switching between two values. This method uses the following
x = a + b - x
to switch the values of x between a and b. So if you wish to switch between 0 and 5, 1 and 4 or 2 and 3 it would be
x = 5 - x
The big problem with this technique is that x must be initialized. It can go wildly wrong if x is not initialized. So to switch between 1 and 2, a + b = 3. Using @GauravPathak's code, it would be
#include <stdio.h>
int main()
{
int var = 1;
int userinp = 0;
do {
printf("Enter value: ");
scanf("%d", &userinp);
if(userinp == 1) {
var = 3 - var;
printf("var: %d\n", var);
}
}while(userinp != EOF);
}
Upvotes: 0
Reputation: 1143
As per your comment, you want to switch back and forth between values for a particular variable.
In order to achieve this you can store those two values in an array and then use XOR operation to change the index of the array and assign the value to the variable as show in the sample/example code below:
#include <stdio.h>
int main(void)
{
int values[2] = {1,2};
int var = values[0];
int idx = 0;
int userinp = 0;
do {
printf("Enter value: ");
scanf("%d", &userinp);
if(userinp == 1) {
idx = idx ^ 1;
printf("idx:: %d\n", idx);
var = values[idx];
printf("var: %d\n", var);
}
}while(userinp != EOF);
}
Upvotes: 0