Bluetooth Controlled Siren Code

If you want to make a bluetooth controlled siren, make sure you have the BluetoothSerial.h library and make sure you are using the Arduino Bluetooth Control app.

I am using the pin 27 on the ESP32 to control the base pin on an NPN transistor to PWM control the GND pin. One wire is connected to one of the pins on the transistor and the other is connected to the VN pin on the ESP32. If you are using a motor bigger than a small N20 DC motor, I wouldn’t recommend connecting it to the VN on the board. You would probably want to connect it to a motor driver like an L293D IC.

Here is the code for my ESP32 Bluetooth controlled siren:

#include <BluetoothSerial.h>

BluetoothSerial SerialBT;

// PWM setup

const int sirenPin = 27;

const int pwmChannel = 0;

const int pwmFreq = 5000;     // 5 kHz

const int pwmResolution = 8;  // 0–255

bool pulseMode = false;

unsigned long lastPulseTime = 0;

int pulseValue = 120;

bool rampUp = true;

void setup() {

  Serial.begin(115200);

  SerialBT.begin(“ESP32_SIREN”);

  ledcSetup(pwmChannel, pwmFreq, pwmResolution);

  ledcAttachPin(sirenPin, pwmChannel);

  ledcWrite(pwmChannel, 0); // off

}

void loop() {

  // Handle incoming Bluetooth commands

  if (SerialBT.available()) {

    String cmd = SerialBT.readStringUntil(‘\n’);

    cmd.trim();

    cmd.toLowerCase();

    pulseMode = false; // default unless “pulse” is selected

    if (cmd == “growl test”) {

      startPulse();

      ledcWrite(pwmChannel, 60);

    } else if (cmd == “slow”) {

      startPulse();

      ledcWrite(pwmChannel, 120);

    } else if (cmd == “full”) {

      ledcWrite(pwmChannel, 255);

    } else if (cmd == “pulse”) {

      startPulse();

      pulseMode = true;

    } else if (cmd == “off”) {

      ledcWrite(pwmChannel, 0);

    } else {

      SerialBT.println(“Unknown command”);

    }

  }

  // Handle pulse mode ramping

  if (pulseMode) {

    unsigned long now = millis();

    if (now – lastPulseTime > 20) { // speed of ramping

      lastPulseTime = now;

      if (rampUp) {

        pulseValue++;

        if (pulseValue >= 255) rampUp = false;

      } else {

        pulseValue–;

        if (pulseValue <= 100) rampUp = true;

      }

      ledcWrite(pwmChannel, pulseValue);

    }

  }

}

void startPulse() {

  // Kickstart pulse: 60ms full power

  ledcWrite(pwmChannel, 255);

  delay(60);

}