#include <Tone32.h>
#include <pitches.h>
#define IR_Sensor 18
#define BUZZER_PIN 19
#define BUZZER_CHANNEL 0
int Counter;
int IR;
int frequency;
// the setup function runs once when you press reset or power the board
void setup()
{
Serial.begin(115200);
Serial.println("Setup start");
pinMode(IR_Sensor, INPUT);
Serial.println("Setup end");
}
// the loop function runs over and over again until power down or reset
void loop()
{
if (Counter == 0)
{
IR = digitalRead(IR_Sensor);
if (IR = HIGH)
{
Counter++;
Serial.println(Counter);
delay(1000);
}
}
if (Counter >= 1);
{
Counter++;
delay(1000);
}
if (Counter >= 900)
{
Serial.println(Counter);
Counter = 0;
delay(500);
}
Serial.println(Counter);
Buzzz();
Serial.println(frequency);
}
void Buzzz()
{
if (Counter == 300 && Counter <= 600)
{
frequency = 4000;
}
if (Counter == 600 && Counter <= 900)
{
frequency = 8000;
}
if (Counter <= 300)
{
Serial.println("Buzz");
tone(BUZZER_PIN, frequency, 500, BUZZER_CHANNEL);
noTone(BUZZER_PIN, BUZZER_CHANNEL);
delay(500);
tone(BUZZER_PIN, frequency, 500, BUZZER_CHANNEL);
noTone(BUZZER_PIN, BUZZER_CHANNEL);
delay(500);
}
}
The op might want to learn more about the tone32.h library being used and how the numbers being sent to the tone32 library affect the ESP32's LEDC API, clicky clicky, and how those numbers are effecting the HardwareTimers and how the pitches.h numbers are interacting with the hardware timers.
The ESP32 MCU doesn't have as much driving power on its pins as Arduino UNO's 328P MCU. If you wish to use a buzzer, you need to drive it with some transistors. Even if you don't want transistors, you should use some resistors such as 500 ohm in series with the buzzer. Directly connecting the buzzer to an IO pin may cause damage to the pin. I have a similar looking buzzer. Whenever I turn it on, there is the order of hundreds of mA of current through my circuit. If you disconnect that buzzer and run your code without modification and it runs without reboot, you know it's the buzzer. Adding the resistor will make the sound very soft. Best is to use a transistor to drive it. Better than best is if you are already familiar with transistors and use two transistors and drive the buzzer with 5V.