#include #include #include #include "controls.h" #include "error.h" // For initializing simple buttons int initButton(Button *button) { pinMode(button->pin, INPUT); return ERRNO_SUCCESS; } // Read the state of a given button int readButton(Button *button) { uint32_t pinvalue; uint32_t curmillis; uint32_t buttonvalue; if ( button == NULL ) { ERROR(ERRNO_NULLPOINTER); } curmillis = millis(); buttonvalue = digitalRead(button->pin); if ( (button->state & BUTTON_STATE_BOUNCING) == BUTTON_STATE_BOUNCING ) { if ( (curmillis - button->debounce_start_time) >= button->debouncetime ) { if ( buttonvalue == button->pressedvalue ) { button->state = BUTTON_STATE_DOWN; } else { button->state = BUTTON_STATE_UP; } Serial.printf("Button on pin %d has debounced state %d\n", button->pin, button->state); button->debounce_start_time = 0; return ERRNO_SUCCESS; } return ERRNO_SUCCESS; } if ( buttonvalue != button->pressedvalue && ( (button->state & BUTTON_STATE_DOWN) == BUTTON_STATE_DOWN || (button->state & BUTTON_STATE_HELD) == BUTTON_STATE_HELD)){ // We are beginning to release. Debounce. Serial.printf("Debouncing button on pin %d for release\n", button->pin); button->state = button->state | BUTTON_STATE_BOUNCING; button->debounce_start_time = curmillis; } if ( buttonvalue == button->pressedvalue && ( (button->state & BUTTON_STATE_DOWN) != BUTTON_STATE_DOWN && (button->state & BUTTON_STATE_HELD) != BUTTON_STATE_HELD)){ // We are beginning to press. Debounce. Serial.printf("Debouncing button on pin %d for press\n", button->pin); button->state = button->state | BUTTON_STATE_BOUNCING; button->debounce_start_time = curmillis; } return ERRNO_SUCCESS; } uint32_t readDifficulty() { analogRead(PIN_DIFFICULTY); delay(1); uint32_t setting = analogRead(PIN_DIFFICULTY); uint32_t divisor = 4096/9; return setting/divisor; }