Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Arduino.h>
- #include <vector>
- #include <string>
- #include "BluetoothSerial.h"
- // https://randomnerdtutorials.com/esp32-bluetooth-classic-arduino-ide/
- class Actor {
- public:
- int actPin;
- Actor(int pin): actPin (pin) {}
- virtual void act() {}
- };
- class Clicker {
- private:
- int clickerPin;
- std::vector<Actor*> actors;
- bool enabled;
- public:
- Clicker(int pin) {
- this->clickerPin = pin;
- this->enabled = true;
- }
- bool isClicked() {
- return digitalRead(clickerPin) == LOW;
- }
- void addActor(Actor* newActor) {
- this->actors.push_back(newActor);
- }
- void watchClicks() {
- Serial.println("watching clicks");
- if (this->isClicked()) {
- for (Actor* actor: this->actors) {
- actor->act();
- }
- }
- }
- void enable() {
- this->enabled = true;
- }
- void disable() {
- this->enabled = false;
- }
- };
- class SoundDevice: public Actor {
- public:
- SoundDevice(int pin): Actor (pin) { }
- void playSound(int del) {
- digitalWrite(this->actPin, HIGH);
- delay(del);
- digitalWrite(this->actPin, LOW);
- }
- void playLoudSound(int del) {
- int arr[10] = {25, 50, 25, 50, 25, 50, 25, 50, 25, 50};
- for (int i = 0; i<10; i++) {
- analogWrite(this->actPin, arr[i]);
- delay((int)(del/2));
- analogWrite(this->actPin, 1);
- delay( (int)(del/2));
- }
- }
- void act() override {
- Serial.println("sound device acting");
- playSound(150);
- }
- };
- class MessageController {
- private:
- BluetoothSerial serial;
- Clicker* clicker;
- SoundDevice* soundDevice;
- std::string message;
- public:
- MessageController(BluetoothSerial s,
- Clicker* clicker,
- SoundDevice* soundDevice):
- clicker(clicker), soundDevice(soundDevice) {
- message = "";
- this->serial = s;
- this->serial.begin("ESP32Kirill");
- }
- void parseCommand() {
- if (this->serial.available()){
- char incomingChar = this->serial.read();
- if (incomingChar != '\n'){
- this->message += String(incomingChar);
- } else {
- this->message = "";
- }
- Serial.write("Got char: ");
- Serial.write(incomingChar);
- }
- if (message =="buzz") {
- this->soundDevice->playSound(150);
- }
- else if (message =="clicker_on") {
- digitalWrite(ledPin, LOW);
- }
- }
- }
- uint64_t count = 0;
- Clicker* clicker;
- SoundDevice* soundDevice;
- BluetoothSerial SerialBT;
- MessageController* messageController;
- void setup() {
- Serial.begin(115200);
- int clickerPin = 4;
- int soundPin = 13;
- int soundLen = 300;
- pinMode(clickerPin, INPUT);
- pinMode(soundPin, OUTPUT);
- clicker = new Clicker(clickerPin);
- soundDevice = new SoundDevice(soundPin);
- clicker->addActor(soundDevice);
- messageController = new MessageController(
- SerialBT,
- clicker,
- soundDevice,
- );
- Serial.println("Setup finished");
- }
- void loop() {
- messageController->parseCommand();
- clicker->watchClicks();
- delay(100)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement