Hello!
This is my first post, so I’m a bit unsure of how I should post this.
I am using an Arduino Uno board.
What I am trying to as a whole use 8 LED’s as a form of input. Each LED is a number [1-8] and I use the potentiometer to “scroll through” the LED to get the value/number of the LED I want.
I’ve used a loop to scroll through the LED’s and a pushbutton to stop the loop/scrolling. Now all I need is to retain the value/number of the LED that I stopped at. This is where I run into problems.
I’m using a int variable declared in the first line of one of my function (int tempGuess) to try to retain the value. I change it inside an if statement, and then return it/print it. However, every time I try to return the value or print out the variable it just returns to its original value outside of the if statement.
Is there something wrong with how I am using the variable?
Is this a good method to use?
Thank you very much!
Code:
const int MAX_BOARD_SIZE = 8;
const int BANK_SIZE = 3;
int buttonPins[] = {19, 18, 17, 16, 15, 9, 10, 11};
const int ledPin = 2;
const int buttonPin = 12;
int buttonState = 0;
int locationCells[BANK_SIZE];
int sensorPin = A0; // select the input pin for the potentiometer
int sensorValue = 0;
void setup(){
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
//setup game
void loop() {
char guess = 'n';
String result = "miss";
guess = getGuess();
if (guess != 'n') {
//Serial.print("You guessed:");
Serial.println(guess);
//Serial.println(result);
}
}
/* A function to fetch the character input from the Serial Monitor.
returns 'n' if no guess, else the user input
*/
char getGuess(){
sensorValue = analogRead(sensorPin);
int chosenLedNum = map(sensorValue, 0, 1023, 0, 7);
buttonState = digitalRead(buttonPin);
//Declaring the global int variable
int tempGuess = 0;
//if the button is pressed turn on LED and the button row of LED's
if (buttonState == LOW) {
digitalWrite(ledPin, HIGH);
//value of the potentiometer is compared to the LED number
for(int i = 0; i<8; i++){
//if they are the same the LED lights up
if (chosenLedNum == (i)){
digitalWrite(buttonPins[i], HIGH);
//changing the value of the global int variable
tempGuess = i+1;
}
else {
digitalWrite(buttonPins[i], LOW);
}
}
}
else {
digitalWrite(ledPin, LOW);
//turns off the row of LED's
for(int i = 0; i<8; i++){
digitalWrite(buttonPins[i], LOW);
}
}
//should print/return a value other than 0, but it doesn't
Serial.println(guess);
return tempGuess;
}