# 1 "C:\\Users\\juanm\\Desktop\\informatica_industrial_giei_ejercicios\\Ejercicios\\tema6_sistemas_de_tiempo_real\\02_problem1_data_loss\\02_problem1_data_loss.ino"
/*

Author: Juan M. Gandarias

Date: 03/11/2023

Description: polling_example_problem1

*/

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(26 /* LED connected to GPIO26*/, 0x03); // Configure LED as output
  pinMode(27 /* Button connected to GPIO27*/, 0x05); // Configure button as input (internal pull-up)

  t = 0.0; // Initialize time
}

void loop()
{
  if (!digitalRead(27 /* Button connected to GPIO27*/)) // If the button is pressed (note: pressed reads LOW due to INPUT_PULLUP)
  {
    if (button_state) // If the previous state was ON
    {
      digitalWrite(26 /* LED connected to GPIO26*/, 0x0); // Turn the LED OFF
    }
    else // If the previous state was OFF
    {
      digitalWrite(26 /* LED connected to GPIO26*/, 0x1); // 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(4 /* Potentiometer connected to GPIO04*/));
  t = millis();

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