#define DEBUG false

#if DEBUG
#include <SoftwareSerial.h>
#endif

#define PIN_SAMPLE    A0
#define PIN_TRIGGER   A3
#define PIN_THRESHOLD A2
#define PIN_DISCHARGE PB1
#define PIN_OUTPUT    PB2
#define SERIAL_RX     PB0
#define SERIAL_TX     PB5
#define SERIAL_DELAY  1000

#if DEBUG
unsigned long timerSerial = 0;
SoftwareSerial mySerial(SERIAL_RX, SERIAL_TX);
#endif

uint16_t sample;
uint16_t trigger;
uint16_t threashold;

float sinVal;
uint16_t outVal;

uint8_t angle = 180;

void setup()
{
  pinMode(PIN_TRIGGER, INPUT);
  pinMode(PIN_THRESHOLD, INPUT);
  pinMode(PIN_DISCHARGE, OUTPUT);
  pinMode(PIN_OUTPUT, OUTPUT);

#if DEBUG
  mySerial.begin(9600);
#else
  pinMode(PIN_SAMPLE, INPUT);
#endif

  digitalWrite(PIN_DISCHARGE, LOW);
  digitalWrite(PIN_OUTPUT, LOW);
}

void loop()
{
  trigger = analogRead(PIN_TRIGGER);
  threashold = analogRead(PIN_THRESHOLD);

#if DEBUG
  if (millis() - timerSerial >= SERIAL_DELAY) {
    timerSerial = millis();
    mySerial.print(trigger);
    mySerial.print(" ");
    mySerial.println(threashold);
  }
#endif

  if (trigger < 338)
  {
    digitalWrite(PIN_DISCHARGE, LOW);
    digitalWrite(PIN_OUTPUT, HIGH);
  }

  if (threashold > 686)
  {
    digitalWrite(PIN_DISCHARGE, HIGH);
    digitalWrite(PIN_OUTPUT, LOW);
    while (analogRead(PIN_TRIGGER) > 338)
    {
      for (int x = 0; x < 180; x++)
      {
#if DEBUG
        mySerial.println(x);
#else
        // Captura as amostras de audio e converte em graus
        sample = analogRead(PIN_SAMPLE);
        angle = map(sample, 512, 1023, 1, 180);
#endif
        // Converte graus em radianos para obter o valor do seno
        sinVal = (sin(x * (3.1412 / angle)));
        outVal = int(sinVal * 255);
        analogWrite(PIN_OUTPUT, outVal);
      }
    }
  }
}
ATTINY8520PU