I'm writing a program with three different cases. Case one an LED is off, in another it is on and in the last case the brightness is controlled by a potentiometer. Each case works as I press the button. The issue I am having is with the third case. The potentiometer is read only once and the LED is set accordingly. I would like the LED to be adjusted continuously until the button is pushed again and the case is switched to off. I used the Serial.print to see the valves read from the potentiometer. I verified its only read once on each cycle through the different cases. I also changed from a SWITCH/CASE to If statements and it only reads the potentiometer once.
CODE HAS BEEN UPDATED
//-------------------------------------------------------
// BUTTON AND POT - TEST
// KNOWN ISSUE - POT ONLY TAKES ON READING
// vonderasche
// 7/28/2016
//-------------------------------------------------------
const int BUTTON_PIN = 9;
const int LED_PIN = 3;
const unsigned long DEBOUNCE_TIME = 50;
int val = 0;
int pot = 0;
int state = 0;
void setup()
{
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600);
}
bool button_press()
{
static bool last_state;
static unsigned long last_state_change;
unsigned long now = millis();
if (now - last_state_change < DEBOUNCE_TIME)
return false;
bool state = digitalRead(BUTTON_PIN);
if (state != last_state) last_state_change = now;
bool press = last_state && !state;
last_state = state;
return press;
}
void loop()
{
unsigned long now = millis();
static enum { OFF, ON, POT } state;
if (button_press()) switch (state) {
case OFF:
analogWrite(LED_PIN, 255);
state = ON;
Serial.println(state);
break;
case ON:
analogWrite(LED_PIN, 0);
state = POT;
Serial.println(state);
break;
case POT:
Serial.println(state);
int Mode = button_press();
while (val < 1023) {
val = (analogRead(pot) / 4);
analogWrite(LED_PIN, val);
Serial.println(val);
state = OFF;
break;
}
}
}