I am new to Arduino (and the looping structure of it) and am writing a program that tracks beers poured from a keg. I am having trouble logically thinking about the setup of the variables/code though.
There is going to be a toggle switch determining what size keg we are using- a half keg or a pony keg. From here, we know the total ounces in the keg so we can figure out how many ounces remain which will be displayed on a screen.
The problem is I am unsure how to set the ouncesRemaining or kegSize without it being overwritten constantly when the program runs. If I were to hard code something like int ouncesRemaining = 661 at the beginning of the program outside of the loop, it would be easy. But I need to offer the user a choice of keg size with a physical switch and am unsure what to do to only set the number at the beginning of the program and not constantly reset it.
I have an idea to get around it but I'm unsure if this is the best way to do it. Since I am learning I am looking to see if there is a better/easier/correct way to do this type of thing.
This is not the exact code but simplified to show the idea:
int buttonPin=2;
int buttonState=0;
int i = 0;
int kegSize;
int ouncesRemaining;
int maxPony = 661;
int maxHalf = 1984;
float kegRemaining = 100;
void setup() {
pinMode(buttonPin, INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == LOW){ //LOW = keg is a Pony keg
ouncesRemaining=maxPony;
kegSize=maxPony;
//alreadyRan == 1
}
else if (buttonState = HIGH){ //HIGH = keg is a Half barrel keg
ouncesRemaining=maxHalf;
kegSize=maxHalf;
}
while (i != 10){ //Not the real condition that happens in program
ouncesRemaining=(ouncesRemaining - 1);
i++;
delay(1000);
}
kegRemaining=((float)ouncesRemaining/kegSize * 100); //Print this to LCD display
}
Here is my idea to fix/get around my issue. I add a variable to make sure the 'program setup' only runs once at the beginning of the program:
int buttonPin=2;
int buttonState=0;
int i = 0;
int kegSize;
int ouncesRemaining;
int maxPony = 661;
int maxHalf = 1984;
float kegRemaining = 100;
int programSetup = 0;
void setup() {
pinMode(buttonPin, INPUT);
}
void loop() {
if (programSetup == 0) {
buttonState = digitalRead(buttonPin);
if (buttonState == LOW){ //LOW = keg is a Pony keg
ouncesRemaining=maxPony;
kegSize=maxPony;
//alreadyRan == 1
}
else if (buttonState = HIGH){ //HIGH = keg is a Half barrel keg
ouncesRemaining=maxHalf;
kegSize=maxHalf;
}
}
while (i != 10){ //Not the real condition that happens in program
ouncesRemaining=(ouncesRemaining - 1);
i++;
delay(1000);
}
kegRemaining=((float)ouncesRemaining/kegSize * 100); //Print this to LCD display
}