/*
Author: Juan M. Gandarias
Date: 03/11/2023
Description: polling_example_problem1
*/

#define LED_PIN 26    // LED connected to GPIO26
#define BUTTON_PIN 27 // Button connected to GPIO27
#define POT_PIN 4     // Potentiometer connected to GPIO04

double t;                  // Variable to track time
bool button_state = false; // Variable to store the button state

void setup()
{
  Serial.begin(115200); // Initialize serial port

  pinMode(LED_PIN, OUTPUT);          // Configure LED as output
  pinMode(BUTTON_PIN, INPUT_PULLUP); // Configure button as input (internal pull-up)

  t = 0.0; // Initialize time
}

void loop()
{
  if (!digitalRead(BUTTON_PIN)) // If the button is pressed (note: pressed reads LOW due to INPUT_PULLUP)
  {
    if (button_state) // If the previous state was ON
    {
      digitalWrite(LED_PIN, LOW); // Turn the LED OFF
    }
    else // If the previous state was OFF
    {
      digitalWrite(LED_PIN, HIGH); // Turn the LED ON
    }
    button_state = !button_state; // Store that the state has toggled
  }

  // Send data over serial (frequency and potentiometer value)
  Serial.println("freq: ");
  Serial.println(1 / double((millis() - t) / 1e3));
  Serial.println("Sensor value: ");
  Serial.println(analogRead(POT_PIN));
  t = millis();

  // Loop every 50ms => 20Hz
  delay(50);
}