toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.

dprovencher:
Thanks for the suggestion, but I got something working before I read your message. I don't know if I get the same volume I would get with toneAC but now I can tell it's way louder and I can get frequencies I couldn't before with tone(). Sound is way clearer too and no wierd noises. The only thing bothering me is I can't do anything else while the loop is running, but as my other components are only LEDs I can work around it.

// frequency : hertz

// duration : milliseconds
void toneAlmostAC(unsigned int frequency, unsigned int duration)
{
  // A1 and A2 hardcoded (PD1, PD2)
 
  PORTD.OUT &= 0b11111001; // Clear A1 and A2
  PORTD.OUT |= 0b00000010; // Set A1
  unsigned long delay = 1000000 / frequency / 2;
  unsigned long end = millis() + duration;
  while(millis() < end)
  {
    PORTD.OUT ^= 0b00000110; // Toggle A1 and A2
    delayMicroseconds(delay);
  }
  PORTD.OUT &= 0b11111001; // Clear A1 and A2
}

You'll need to use timers to do multiple things as once, which is the reason for the ToneAC library. What you're doing is blocking mode, where one thing runs at a time.

I'd look into using timers on your microcontroller, or using an amp, or use a classic Arduino that works with all the libraries out there.

Tim