#include <Arduino.h>

// Define LED, button, and buzzer pins
const int redLedPin = 3;
const int greenLedPin = 4;
const int buttonPin = 2;
const int buzzerPin = 8; // Buzzer connected to pin 8

void setup() {
  Serial.begin(9600);
  Serial.println("Setup started...");

  pinMode(redLedPin, OUTPUT);
  pinMode(greenLedPin, OUTPUT);
  Serial.println("LED pins configured.");

  pinMode(buttonPin, INPUT_PULLUP);
  Serial.println("Button pin configured.");

  pinMode(buzzerPin, OUTPUT);
  Serial.println("Buzzer pin configured as output for tone().");

  Serial.println("Setup completed.");
}

void beep(int frequencyHz, int durationMs, int count = 1, int pauseMs = 100) {
  Serial.print("Beeping... ");
  Serial.print(count);
  Serial.println(" times");

  for (int i = 0; i < count; i++) {
    tone(buzzerPin, frequencyHz, durationMs); // Start playing a tone
    delay(durationMs); // Delay for tone's duration
    noTone(buzzerPin); // Although tone() has duration, calling noTone() to ensure it stops

    if (i < count - 1) { // Pause between beeps, if not the last beep
      delay(pauseMs);
    }
  }
}

void transmitBit(bool bitValue) {
  Serial.print("Transmitting bit: ");
  Serial.println(bitValue ? "1" : "0");

  if (bitValue) {
    digitalWrite(redLedPin, HIGH);
    delay(500);
    digitalWrite(redLedPin, LOW);
  } else {
    digitalWrite(greenLedPin, HIGH);
    delay(500);
    digitalWrite(greenLedPin, LOW);
  }
  delay(500); // Wait between transmissions for clarity
}

void loop() {
  Serial.println("\nWaiting for button press...");
  while (digitalRead(buttonPin)) {}

  Serial.println("Button pressed.");
  delay(20); // Debounce delay

  beep(1000, 100, 1); // Beep once at the start
  Serial.println("Start of conversion.");

  int analogValue = analogRead(A0);
  Serial.print("Analog value read: ");
  Serial.println(analogValue);

  for (int i = 9; i >= 0; i--) {
    transmitBit(bitRead(analogValue, i));
  }

  Serial.println("End of transmission.");
  delay(20); // Debounce delay

  beep(1000, 100, 2, 100); // Double beep at the end
  Serial.println("End of conversion.");

  while (!digitalRead(buttonPin)) {} // Wait for button release

  Serial.println("Waiting before next read cycle...");
  delay(1000); // Wait before the next cycle
}