0

I want to do is BEEP! to show that the program is running.

#define SPKR 4 //this is the digital pin that you plugged the red       wire into

void setup()
{
   pinMode(SPKR, OUTPUT); //set the speaker as output
}

void loop() //do this over and over
{
   digitalWrite(SPKR, HIGH); //turn the speaker on
   delay(500);                     //wait for half a second
   digitalWrite(SPKR, LOW); //turn the speaker off
   delay(500);                    //wait for half a second
}

With out this any other way I mean without repeating the code HIGH / LOW during this beep I want do same things else

Mark Smith
  • 2,181
  • 1
  • 10
  • 14

1 Answers1

2

The code you show will toggle the SPKR pin at a 1 Hz rate. If you have an ordinary speaker attached, you will hear it click twice a second, but it won't generate an audible tone.

To generate a tone, use tone(pin, frequency) calls, or tone(pin, frequency, duration) calls.

For example:

void loop() {
   tone(SPKR, 400, 500); // 400 Hz tone for half second
   delay(500);           // no tone for half second
}

Note, ordinary speakers are low-impedance devices, eg 4 Ω, 8 Ω, etc. You can use an audio transformer for impedance matching – this helps produce an adequate output volume – but lacking that, should put a resistor (eg 220 Ω) in series with the speaker to avoid over-current conditions. AVR pins can deliver 25 mA without too much stress, and typically are rated at an absolute max of 40 mA.

James Waldby - jwpat7
  • 8,840
  • 3
  • 17
  • 32