how to create frequency with arduino

I want to reproduce a frequency right to a speaker without a DFPlayer. There’s any way to reproduce frequencies with an Arduino code?
Also those frequencies need to be modified by a distance sensor (that’s already done). How to link booth codes??

Thanks in advance :slight_smile:

#include <NewPing.h> // https://bitbucket.org/teckel12/arduino-new-ping/downloads/
const byte UltrasonicPin = 5;
const unsigned int MaxDistance = 200;
NewPing sonar(UltrasonicPin, UltrasonicPin, MaxDistance);

#include <SoftwareSerial.h>

void setup()
{
  Serial.begin(9600);
  DFPlayerSerial.begin(9600);

}

void loop()
{
  delay(50);                      // esperar 50ms entre pings (29ms como minimo)
  int distance = sonar.ping_cm(); // obtener el valor en cm (0 = fuera de rango)
  Serial.print(distance); Serial.println(F("cm"));

  if (distance < 10) {
    // distance less than 10cm
    Serial.println("Playing track 1 for 5 sec");

    delay(5000);

  } else if (distance < 20) {
    // distance between 10cm and 20cm
    
  } else if (distance < 50) {
    // distance between 20cm and 50cm
    
  } else {
    // distance more than 50cm
    
  }
}

tone()

I thought tone() work with piezo speaker, does it works also with a magnetic-driven speaker??

pepo177:
I thought tone() work with piezo speaker, does it works also with a magnetic-driven speaker??

This is a hardware interfacing question. Function 'tone()' produces a square wave on a digital output. What you connect it to is your business. You just have to avoid overloading the output by limiting the maximum current to about 20mA. Try driving your speaker through a series 220 ohm resistor and see what happens. Every speaker is different anyway...