Ada Wave Shield: Random Play in Button funktion

Liebe Gemeinde,

dank dieses Forums bin ich schon fast am Ziel meiner Träume, aber leider bin ich immer noch nicht schlau genug, mein nächstes Problem zu lösen. Ich habe ein altes analoges Telefon. Das klingelt mittels Relais randommäßig. Das Klingeln stoppt, sobald man den Hörer abhebt. (<-Danke Whandall!)

Wenn man den Hörer abhebt, soll nun ein Sound vom Ada Waveshield abgespielt werden.(ADA daphc-Sketch) Ich konnte den Ada-Sketch insoweit einbauen, dass alle Sounds von meiner Karte gespielt werden, aber ich kriege es nicht hin, dass nur EIN RANDOM Sound gespielt wird.

(Ich habe versucht, an mehreren Stellen im Sketch etwas zu ändern, aber dann ging immer gar nichts mehr.Ich kann einfach die Programmier-Grammatik nicht richtig. Leider.)

Vielleicht hat ja jemand Lust, mir zu helfen. Ich wäre sehr dankbar!

// https://github.com/thomasfredericks/Bounce2
#include <Bounce2.h>
/*
 * This example plays every .WAV file it finds on the SD card in a loop
 */
#include <WaveHC.h>
#include <WaveUtil.h>

SdReader card;    // This object holds the information for the card
FatVolume vol;    // This holds the information for the partition on the card
FatReader root;   // This holds the information for the volumes root directory
WaveHC wave;      // This is the only wave (audio) object, since we will only play one at a time

uint8_t dirLevel; // indent level for file/dir names    (for prettyprinting)
dir_t dirBuf;     // buffer for directory reads


/*
 * Define macro to put error messages in flash memory
 */
#define error(msg) error_P(PSTR(msg))

// Function definitions (we define them here, but the code is below)
void play(FatReader &dir);


const int buttonPin = 1;     // the number of the pushbutton pin
const int LedPin =  13;      // the number of the LED pin - not needed in the moment. Needed it for testing.

// variables:
int buttonState = 0;         // variable for reading the button status
int RelPin = 6;              // Relais connected to digital pin 6
unsigned long On = 1500;      // RING
unsigned long Off = 2000;     // PAUSE
unsigned long randOff;

Bounce button;

enum states {
  idle,
  rndWait,
  relOn1,
  relOff1,
  relOn2,
  relOff2,
  relOn3,
};
byte State = idle;
unsigned long LoopEntered;
unsigned long StartTime;

void setup() {
  button.attach(buttonPin, INPUT_PULLUP);
  pinMode(LedPin, OUTPUT);     // initialize the LED pin as an output - not needed in the moment. Needed it for testing.
  pinMode(RelPin, OUTPUT);      // sets the digital Relais pin as output
  randomSeed (analogRead (0));  // randomize
    Serial.begin(9600);           // set up Serial library at 9600 bps for debugging
  
  putstring_nl("\nWave test!");  // say we woke up!
  
  putstring("Free RAM: ");       // This can help with debugging, running out of RAM is bad
  Serial.println(FreeRam());

  //  if (!card.init(true)) { //play with 4 MHz spi if 8MHz isn't working for you
  if (!card.init()) {         //play with 8 MHz spi (default faster!)  
    error("Card init. failed!");  // Something went wrong, lets print out why
  }
  
  // enable optimize read - some cards may timeout. Disable if you're having problems
  card.partialBlockRead(true);
  
  // Now we will look for a FAT partition!
  uint8_t part;
  for (part = 0; part < 5; part++) {   // we have up to 5 slots to look in
    if (vol.init(card, part)) 
      break;                           // we found one, lets bail
  }
  if (part == 5) {                     // if we ended up not finding one  :(
    error("No valid FAT partition!");  // Something went wrong, lets print out why
  }
  
  // Lets tell the user about what we found
  putstring("Using partition ");
  Serial.print(part, DEC);
  putstring(", type is FAT");
  Serial.println(vol.fatType(), DEC);     // FAT16 or FAT32?
  
  // Try to open the root directory
  if (!root.openRoot(vol)) {
    error("Can't open root dir!");      // Something went wrong,
  }
  
  // Whew! We got past the tough parts.
  putstring_nl("Files found (* = fragmented):");

  // Print out all of the files in all the directories.
  root.ls(LS_R | LS_FLAG_FRAGMENTED);
  
}
// change state and record time of entry
void doStep(byte toState) {
  StartTime = LoopEntered;
  State = toState;
}
// if duration expired since StartTime, enter state and set relay
bool timedStep(unsigned long duration, byte toState, bool relay) {
  if (LoopEntered - StartTime > duration) {
    digitalWrite(RelPin, relay);
    doStep(toState);
    return true;
  }
  return false;
}

void loop() {
  LoopEntered = millis(); // baseTime
  button.update();
  if (button.rose()) {  // picked up, cancel all
    digitalWrite(RelPin, LOW);
    root.rewind();
  play(root);
    State = idle;
    
  }
  switch (State) {
    case idle:
      if (button.fell()) {  // hung up
        randOff = random (10000, 20000);
        doStep(rndWait);
      }
      break;
    case rndWait: timedStep(randOff, relOn1, HIGH); break;
    case relOn1:  timedStep(On, relOff1, LOW);     break;
    case relOff1: timedStep(Off, relOn2, HIGH);    break;
    case relOn2:  timedStep(On, relOff2, LOW);     break;
    case relOff2: timedStep(Off, relOn3, HIGH);    break;
    case relOn3:
      if (timedStep(On, rndWait, LOW)) {
        randOff = random (120000, 600000); //not answered? Again after 2-10 minutes
      }
      break;
  }
}

/////////////////////////////////// HELPERS
/*
 * print error message and halt
 */
void error_P(const char *str) {
  PgmPrint("Error: ");
  SerialPrint_P(str);
  sdErrorCheck();
  while(1);
}
/*
 * print error message and halt if SD I/O error, great for debugging!
 */
void sdErrorCheck(void) {
  if (!card.errorCode()) return;
  PgmPrint("\r\nSD I/O error: ");
  Serial.print(card.errorCode(), HEX);
  PgmPrint(", ");
  Serial.println(card.errorData(), HEX);
  while(1);
}
/*
 * play recursively - possible stack overflow if subdirectories too nested
 */
void play(FatReader &dir) {
  FatReader file;
  while (dir.readDir(dirBuf) > 0) {    // Read every file in the directory one at a time
  
    // Skip it if not a subdirectory and not a .WAV file
    if (!DIR_IS_SUBDIR(dirBuf)
         && strncmp_P((char *)&dirBuf.name[8], PSTR("WAV"), 3)) 
         {
      continue;
    }

    Serial.println();            // clear out a new line
    
    for (uint8_t i = 0; i < dirLevel; i++) {
       Serial.write(' ');       // this is for prettyprinting, put spaces in front
    }
    if (!file.open(vol, dirBuf)) {        // open the file in the directory
      error("file.open failed");          // something went wrong
    }
    
    if (file.isDir()) {                   // check if we opened a new directory
      putstring("Subdir: ");
      printEntryName(dirBuf);
      Serial.println();
      dirLevel += 2;                      // add more spaces
      // play files in subdirectory
      play(file);                         // recursive!
      dirLevel -= 2;    
    }
    else {
      // Aha! we found a file that isnt a directory
      putstring("Playing ");
      printEntryName(dirBuf);              // print it out
      if (!wave.create(file)) {            // Figure out, is it a WAV proper?
        putstring(" Not a valid WAV");     // ok skip it
      } else {
        Serial.println();                  // Hooray it IS a WAV proper!
        wave.play();                       // make some noise!
        
        uint8_t n = 0;
        while (wave.isplaying) {// playing occurs in interrupts, so we print dots in realtime
          putstring(".");
          if (!(++n % 32))Serial.println();
          delay(100);
        }       
        sdErrorCheck();                    // everything OK?
        // if (wave.errors)Serial.println(wave.errors);     // wave decoding errors
      }
    }
  }
}

Ich habe versucht, an mehreren Stellen im Sketch etwas zu ändern, aber dann ging immer gar nichts mehr

Das ist schade, aber leider keine Beschreibung bei der du mehr als Mitleid kriegen kannst.

Die adafruit Beispiele sind wohl mächtig stolz auf ihre Fähigkeit, die ganze Karte zu scannen, für dich also unbrauchbar :wink:

Es gibt aber auch in der class FatReader:

  uint8_t open(FatReader &dir, char *name);
  uint8_t open(FatReader &dir, uint16_t index);

Wie/ob das mit einem Random - Index geht, keine Ahnung, aber wenn du die Dateinamen in deinem sketch wüsstest, oder sie dir ausrechnen könntest z.B. "SOUND_01.WAF" usw. und sie alle im root Verzeichnis sind:

int nr =random(100); // liefert 0 ..99
char filename[13];
sprintf(filename, "SOUND_%02d.WAF", nr);  // liefert SOUND_00.WAF etc. (2Ziffern mit führender 0)
FatReader file;
file.open(root, filename);
wave.create(file);
wave.play();    // make some noise!
...

Die Testausgaben und Fehlerabfragen hab ich mal weggelassen. Wäre zu überlegen, ob im Fehlerfall einfach mit einer anderen Random Zahl nochmal probiert wird.