NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » An interesting beep

February 26, 2010
by bretm
bretm's Avatar

I'm making a circuit with a numeric keypad and I wanted it to beep each time a key is pressed. I came up with the code below. It plays a 1760Hz tone for 1/20th of a second. It starts out at 50% duty cycle and gradually reduces the duty cycle to near 0% by the end of the duration. This gives it a lot of funky changing overtones.

#define PIEZO _BV(PD2)

void InitBeep()
{
  DDRD |= PIEZO; // configure pin PD2 for output
}

void Beep()
{
  int i;
  int period = 1000000 / 1760; // 1760 Hz is "A"
  int delay = period / 2;      // start out at 50% duty cycle
  int cycles = 50000 / period; // play tone for 0.05 sec
  int pwmRate = delay / cycles;// amount to shorten duty cycle/period

  for (i=0; i<cycles; i++)     // For each cycle,
  {
    PORTD |= PIEZO;            // turn on the piezo signal,
    delay_us(delay);           // wait for a bit,
    PORTD &= ~PIEZO;           // turn off the piezo,
    delay_us(period - delay);  // and wait the remainder of the period.
    delay -= pwmRate;          // Reduce the duty cycle after each period.
  }
}

Post a Reply

Please log in to post a reply.

Did you know that you can use a transistor to interface between different voltage levels of digital logic? Learn more...