// https://forum.arduino.cc/t/cosplay-blaster-prop-using-arduino-nano-and-adafruit-fx-soundboard/1182601
// https://wokwi.com/projects/379751701654688769

# include <SoftwareSerial.h>
# include "Adafruit_Soundboard.h"

# define SFX_TX 5
# define SFX_RX 6

# define SFX_RST 4

SoftwareSerial ss = SoftwareSerial(SFX_TX, SFX_RX);

Adafruit_Soundboard sfx = Adafruit_Soundboard(&ss, NULL, SFX_RST);

//Fire button connects to pin D2
const int fire = 2;
//Mode change button connects to pin D3
const int modechange = 3;

int count1 = 0;
int mode = 0;
int lastButtonState1;
int lastButtonState2 = 1;
long unsigned int lastPress1;
long unsigned int lastPress2;

int debounceTime = 20;

Adafruit_Soundboard ;

void setup() {
  pinMode(modechange, INPUT_PULLUP);
  pinMode(fire, INPUT_PULLUP);

  Serial.begin(9600);  // dont forget to set your serial monitor speed to whatever is set here
  Serial.println("Running");

  //Adafruit_Soundboard sfx
  Serial.begin(9600);
  //Adafruit_Soundboard sfx.begin(Serial, true);
  Serial.println("Setting volume to max");
  //Adafruit_Soundboard sfx.volume(204);  // Set volume 0 to 204 (max is 204)

  Serial.println("Play startup sound");
  //Adafruit_Soundboard sfx. ????

  lastButtonState1 = !digitalRead(fire);
}

void loop() {
//Serial.println(" loop "); delay(100);

  unsigned long now = millis();

  if (!digitalRead(modechange) != lastButtonState2) {
    if (now - lastPress2 > debounceTime) {

      lastPress2 = now;

      if (!lastButtonState2) {
        Serial.print("Mode: ");
        mode++; if (mode == 3) mode = 0;
        Serial.println(mode);
      }
      lastButtonState2 = !lastButtonState2;
    }
  }

  if (!digitalRead(fire) != lastButtonState1)
    if (now - lastPress1 > debounceTime) {

    lastPress1 = now;

    if (!lastButtonState1) {
      Serial.print("Fire: f/x ");
      Serial.print(mode); Serial.print("    ");
      count1++;
      Serial.println(count1);
    }
    lastButtonState1 = !lastButtonState1;
  }
}


void loopX() {
//Serial.println(" loop "); delay(100);

  unsigned long now = millis();

  if (!digitalRead(modechange) != lastButtonState2)  
    if (now - lastPress2 > debounceTime) {

      lastPress2 = now;

      if (!lastButtonState2) {
        Serial.print("Mode: ");
        mode++; if (mode == 3) mode = 0;
        Serial.println(mode);
      }
      lastButtonState2 = !lastButtonState2;
    }

    if (!digitalRead(fire) != lastButtonState1)
      if (now - lastPress1 > debounceTime) {

      lastPress1 = now;

      if (!lastButtonState1) {
        Serial.print("Fire: f/x ");
        Serial.print(mode); Serial.print("    ");
        count1++;
        Serial.println(count1);
      }
      lastButtonState1 = !lastButtonState1;
    }
}