Teensy 4.0 - based Audio Guestbook

Switch issue

Thanks a lot for updating the code and for your help. The issue is still intermittent. When I lift the handset, I hear nothing. If I slightly depress the hook switch (not all the way) the greeting plays and I get the tone. Serial monitor is normal at that point, showing recording and the phone records to the SD card. To end recording, I need to depress the hook switch all the way and then release it. So it still seems like it is reversed. But if I switch around the risingEdge/fallingEdge statements that doesn't cure it. Leads back to wondering if the actual mechanical switch is not working. I will try to obtain another phone to test this. Wedding is in 12 days so running a little tight on time ;-).

I also had problems with intermittent hook switch. I ended up removing it and installed a micro switch which solved that issue. I had to print a mounting bracket and lever to strike the switch. 100_8598.jpg
 
It should be pretty simple to add #ifdef conditional compilation statements to the code so that the user just sets the logic for the switch hooks in one place and then the code is changed throughout the project as needed. I must say I dislike the awkwardness of finding / not being able to jump to .h files and .c function library files in the Arduino interface - any tips on that guys?
 
I use VisualMicro and Visual Studio. No problem they can sit side by side with the ino on the address bar.
 
Yea, I gather that it sort of sits on top of the Arduino environment. I think this is sort of confirmed by one of it's configuration options to "Re-scan Tool -chains and Libraries".
It just sort of sits there and manages the interface between Visual Studio and the Arduino Environment.
After having used it now for about 18 months, I can't ever imagine going back to the Arduino IDE. It also has none of the compatibility / configuration issues / complexity of PlatlformIO.
 
So I already had Arduino installed under mt Users/Documents folder. I installed Visual Studio 2022 and then used Extensions to install the Arduino plugin. Then I was able to open and edit the .ino file in the main VS window but when I right click on a #include statement e.. bounce.h and select open bounce.h it doesn't find it and I see a message saying that my VisualMicro license has expired at the bottom of VS; do I need to buy a VisualMicro license?
 
It should be free for a months trial. Is there anything which says something like "Activate free trial"?
I use the VMicro drop down followed by "Open existing Arduino Project / New Arduino Project" to open / create the ino file.
To open any .h files ( or .cpp ) I use the Visual Studio "File..Open..File".
 
I didn't install the C++ Workload first as the VisualMicro instructions ask for (they also ask for English to be installed but I haven't done that yet). After C++ Workload was installed, I did get the option to use a free trial so I can now compile and the Teensy program window pops up - although I get 2 errors saying that (math) libraries can't be found. The code for the Audio Guest Book project provides modified library files which I think is badly implemented as they have the same names e.g. bounce.h as the standard Arduino ones so I am now unsure which set are being used. I would have called them bounce2.h etc. The comments in the code say...

Code:
// INCLUDES
// The default "sketchbook" location in which Arduino IDE installs libraries is:
// C:\Users\alast\Documents\Arduino
// However, the TeensyDuino installer installs libraries in:
// C:\Program Files (x86)\Arduino\hardware\teensy\avr\libraries
// To ensure the correct libraries are used when targetting Teensy platform in Arduino IDE, go File->Preferences and change the sketchbook location to avoid conflicts with Arduino libraries.
// When targetting Arduino boards, change it back again to default

So I added C:\Program Files (x86)\Arduino\hardware\teensy\avr\libraries under the Optional Sketchbook Location

The screen shot here shows the 2 error caption...
 

Attachments

  • _ArdVS1.jpg
    _ArdVS1.jpg
    177.2 KB · Views: 92
I quite often use the full path to library files where possible alternatives exist as in
#include "C:\Arduino Programs\HomeHeatingManagement\HHMVars.h"
I also keep all my Arduino program files ( .ino and LIBRARIES ) in a directory called C:\Arduino Programs. I do this because I like to be in control of what is happening, especially when new Arduino or Teensyduino is installed / re-installed.
 
You're welcome. It sounds like your switch hook (the switch that operates when you lift your phone) is faulty. Try putting another switch in the circuit and test that it operates correctly; if it does then you need to figure out how to fix your switch. One idea that occurs to me is that there are other components attached to your switch e.g. capacitors; if that's the case then you will probably fix the issue by isolating those components perhaps by cutting their leads or by cutting the PCB tracks and isolating the switch. If it's an old style phone then you may be able to bend the metal work to make the switch hook operated correctly for your needs. Can you post a close up photo of the switch on your phone? I will try to advise what you can do (I'm an EE who was a phone guy back in the day).

I found that my buzzing sound was caused by the mic wire placement too close to the wires carrying the digital switching signals; when I put the Teensy PCBs into the phone properly (it's a rat's nest right now), I will try to keep the mic wires short and away from the other wires. FYI, I fully tested the rest of the code and it all seems to work playing back with beeps etc (my beeps were too loud so I changed the 0.9 numbers to 0.5 and it's better).

One idea I had for improvement was to make the playback work in reverse order - anyone here got experience with the Teensy file drivers that might comment on how to find the newest recording? If the newest played first then the user could press the playback button and review their recording, if they didn't like it, they could record another message.

Here are some images of the board and the hook switch. It doesn't appear to be broken mechanically, has a little rust but its superficial.

IMG_3131.jpg
IMG_3133.jpg
IMG_3134.jpg
IMG_3135.jpeg
IMG_3136.jpg
 
It's almost certainly a bad switch. Things you could try:

1. Bend the metal arm slightly (we did this all the time when I worked for POTS company)
2. Squirt some contact cleaner inside the switch if possible
3. Remove the switch from the PCB, take it apart, and clean the contacts
4. Replace the switch with a new one (probably impossible to find exact replacement)
5. Mount a microswitch alongside the original switch and somehow make the switch operate from the metal lever
 
It's almost certainly a bad switch. Things you could try:

1. Bend the metal arm slightly (we did this all the time when I worked for POTS company)
2. Squirt some contact cleaner inside the switch if possible
3. Remove the switch from the PCB, take it apart, and clean the contacts
4. Replace the switch with a new one (probably impossible to find exact replacement)
5. Mount a microswitch alongside the original switch and somehow make the switch operate from the metal lever

Thanks for the advice.
Quick questions, the switch appears to have two positions when I depress it, so it goes click and then I depress it more and it clicks again. Should it sit past the first 'click' when the handset is down? I can bend the metal to make that work, but want to check.

Second question, the microswitch, does that require any changes to the code? I am confident I can create a 3d print to make a microswitch work like Rik has done above.

EDIT: It must be the switch. The code works great. If I take the two switch cables and touch them off each other it immediately terminates the recording, saves the file and starts the greeting again. Microswitch it is.
 
All the system needs is a switch that operates correctly; your edit shows that you have proved it's the switch.

A microswitch will not require any code changes. Microswitches are usually single pole, double throw so you just need to mimic the present switch logic - either open or closed when phone is off the hook. Pretty much any microswitch that will fit should work.
 
All the system needs is a switch that operates correctly; your edit shows that you have proved it's the switch.

A microswitch will not require any code changes. Microswitches are usually single pole, double throw so you just need to mimic the present switch logic - either open or closed when phone is off the hook. Pretty much any microswitch that will fit should work.

Okay, the electronics place just had single pole, change over, which won't really work as intended I guess? I have ordered spdt switches from Amazon as backup in case I can't get this to work.
 
Last edited:
Okay, the electronics place just had single pole, change over, which won't really work as intended I guess? I have ordered spdt switches from Amazon as backup in case I can't get this to work.

A single pole changeover is just what you want, it's the same as SPDT. If you connect the common (center) connection to the switch input, one end will be normally closed and the other normally open.
 
A single pole changeover is just what you want, it's the same as SPDT. If you connect the common (center) connection to the switch input, one end will be normally closed and the other normally open.

Thank you so much for your help. I really appreciate it. Not only do I now have a working phone, but I’ve learned a lot from this thread. The kindness of strangers on the internet never stops amazing me. Thanks again!
 
Rats, I have it all put together now and I get a high pitched buzzing on all my recordings, I've tried screening the mic cables but it hasn't gone away. Any ideas?
 
Update. I investigated the handset wiring and found that there was an electret condenser mic in it but the black wire was not ground (never assume!) so the polarity of the supply to the mic was reversed and there was probably some sort of oscillation happening so, for anyone who has the buzzing issue, try reversing the mic wires to the Audio PCB. THe audio is also a bit higher level now.
 
So the latest full code is at the bottom of this post. I still have a small issue that may be to do with the way the wav player works. Here's the issue (see snippet below).

Code:
 case Mode::GreetingIsPlaying:
    // Wait for greeting to end OR handset to be replaced
    if (playWav1.isPlaying()) {         // still playing
      // Check whether the handset is replaced
      buttonRecord.update();
      if(buttonRecord.fallingEdge()) {
        // Handset is replaced
        playWav1.stop();
        mode = Mode::Ready;
        // return; // NO NO NO!
      }
    }

User picks up handset and after 1 second delay, the greeting message is played but, if the handset is replaced while the message is playing, the message does not stop playing which means that the snippet above is not working. Any ideas?

Ted

Code:
/**
 * Audio Guestbook, Copyright (c) 2022 Playful Technology
 * Modified by Ted of tedtronic.com Jul 2022
 * Tested using a Teensy 4.0 with Teensy Audio Shield, although should work 
 * with minor modifications on other similar hardware
 * 
 * When handset is lifted, a pre-recorded greeting message is played, followed by a tone.
 * Then, recording starts, and continues until the handset is replaced.
 * Playback button allows all messages currently saved on SD card through earpiece 
 * 
 * Files are saved on SD card as 44.1kHz, 16-bit, mono signed integer RAW audio format
 * These can be loaded directly into Audacity (https://www.audacityteam.org/). Or else, converted to WAV/MP3 format using SOX (https://sourceforge.net/projects/sox/)
 * 
 **/

// INCLUDES
// The default "sketchbook" location in which Arduino IDE installs libraries is:
// C:\Users\alast\Documents\Arduino
// However, the TeensyDuino installer installs libraries in:
// C:\Program Files (x86)\Arduino\hardware\teensy\avr\libraries
// To ensure the correct libraries are used when targetting Teensy platform in Arduino IDE, go File->Preferences and change the sketchbook location to avoid conflicts with Arduino libraries.
// When targetting Arduino boards, change it back again to default
#include <Bounce.h>
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <TimeLib.h>

// DEFINES
// Define pins used by Teensy Audio Shield
#define SDCARD_CS_PIN    10
#define SDCARD_MOSI_PIN  7
#define SDCARD_SCK_PIN   14
// And those used for inputs
#define HOOK_PIN 0
#define PLAYBACK_BUTTON_PIN 1

// GLOBALS
// Audio initialisation code can be generated using the GUI interface at https://www.pjrc.com/teensy/gui/
// Inputs
AudioSynthWaveform      waveform1; // To create the "beep" sfx
AudioInputI2S           i2s2; // I2S input from microphone on audio shield
AudioPlaySdRaw          playRaw1; // Play .RAW audio files saved on SD card
AudioPlaySdWav          playWav1; // Play 44.1kHz 16-bit PCM greeting WAV file
// Outputs
AudioRecordQueue         queue1; // Creating an audio buffer in memory before saving to SD
AudioMixer4              mixer; // Allows merging several inputs to same output
AudioOutputI2S           i2s1; // I2S interface to Speaker/Line Out on Audio shield
// Connections
AudioConnection patchCord1(waveform1, 0, mixer, 0); // wave to mixer 
AudioConnection patchCord2(playRaw1, 0, mixer, 1); // raw audio to mixer
AudioConnection patchCord3(playWav1, 0, mixer, 2); // wav file playback mixer
AudioConnection patchCord4(mixer, 0, i2s1, 0); // mixer output to speaker (L)
AudioConnection patchCord5(i2s2, 0, queue1, 0); // mic input to queue (L)
AudioControlSGTL5000     sgtl5000_1;

uint32_t wait_start = 0; 
// Filename to save audio recording on SD card
char filename[15];
// The file object itself
File frec;

// Use long 40ms debounce time on hook switch
Bounce buttonRecord = Bounce(HOOK_PIN, 40);
Bounce buttonPlay = Bounce(PLAYBACK_BUTTON_PIN, 8);

// Keep track of current state of the device
enum Mode {Initialising, Ready, WaitHandsetEar, WaitGreetingStart, GreetingIsPlaying, PlayingGreetingBeep, Prompting, Recording, Playing};
Mode mode = Mode::Initialising;

void setup() {

  // Note that Serial.begin() is not required for Teensy - 
  // by default it initialises serial communication at full USB speed
  // See https://www.pjrc.com/teensy/td_serial.html
  // Serial.begin()
  Serial.println(__FILE__ __DATE__);
  
  // Configure the input pins
  pinMode(HOOK_PIN, INPUT_PULLUP);
  pinMode(PLAYBACK_BUTTON_PIN, INPUT_PULLUP);

  // Audio connections require memory, and the record queue
  // uses this memory to buffer incoming audio.
  AudioMemory(60);

  // Enable the audio shield, select input, and enable output
  sgtl5000_1.enable();
  // Define which input on the audio shield to use (AUDIO_INPUT_LINEIN / AUDIO_INPUT_MIC)
  sgtl5000_1.inputSelect(AUDIO_INPUT_MIC);
  sgtl5000_1.volume(0.9); 
  // Mic volume     ^^^ was 0.5

  // Play a beep to indicate system is online
  waveform1.begin(WAVEFORM_SINE);
  waveform1.frequency(440);
  waveform1.amplitude(0.8);
  // beep volume      ^^^ was 0.9
  wait(250);
  waveform1.amplitude(0);
  delay(1000);

  // Initialize the SD card
  SPI.setMOSI(SDCARD_MOSI_PIN);
  SPI.setSCK(SDCARD_SCK_PIN);
  if (!(SD.begin(SDCARD_CS_PIN))) {
    // stop here if no SD card, but print a message
    while (1) {
      Serial.println("Unable to access the SD card");
      delay(500);
    }
  }

  // Value in dB
  sgtl5000_1.micGain(40);
  //                 ^^ was 15

  // Synchronise the Time object used in the program code with the RTC time provider.
  // See https://github.com/PaulStoffregen/Time
  setSyncProvider(getTeensy3Time);
  
  // Define a callback that will assign the correct datetime for any file system operations
  // (i.e. saving a new audio recording onto the SD card)
  FsDateTime::setCallback(dateTime);

  mode = Mode::Ready;
}

void loop() {
  // First, read the buttons
  buttonRecord.update();
  buttonPlay.update();

  switch(mode){
    case Mode::Ready:
      // Rising edge occurs when the handset is lifted
      if (buttonRecord.risingEdge()) {
        Serial.println("Handset lifted");
        mode = Mode::Prompting;
      }
      else if(buttonPlay.fallingEdge()) {
        playAllRecordings();
      }
      break;

  case Mode::Prompting:
    // Wait for users to put the handset to their ear
    wait_start = millis();
    mode = Mode::WaitHandsetEar;
    break;

  case Mode::WaitHandsetEar:
    // should check for button changes here, and every case
    if (millis() - wait_start > 1000) {   // give them a second
      // Play the greeting inviting them to record their message
      playWav1.play("greeting.wav");    
      mode = Mode::WaitGreetingStart;
    }
    break;
    
  case Mode::WaitGreetingStart:
    if (playWav1.isPlaying()) {         // WAV file has started playing
      mode = Mode::GreetingIsPlaying;
    }
    break;
     
  case Mode::GreetingIsPlaying:
    // Wait for greeting to end OR handset to be replaced
    if (playWav1.isPlaying()) {         // still playing
      // Check whether the handset is replaced
      buttonRecord.update();
      if(buttonRecord.fallingEdge()) {
        // Handset is replaced
        playWav1.stop();
        mode = Mode::Ready;
        // return; // NO NO NO!
      }
    }
    else {
      waveform1.frequency(440);
      waveform1.amplitude(0.8);
      wait_start = millis();
      mode = Mode::PlayingGreetingBeep;
    }
    break;
    
  case Mode::PlayingGreetingBeep:
    if (millis() - wait_start > 250) {      // 250ms beep
      // beep is done, stop it
      waveform1.amplitude(0);
      // Start the recording function
      startRecording();
    }
    break;


    case Mode::Recording:
      // Handset is replaced
      if(buttonRecord.fallingEdge()){
        // Debug log
        Serial.println("Stopping Recording");
        // Stop recording
        stopRecording();
        // Play audio tone to confirm recording has ended
        waveform1.frequency(523.25);
        waveform1.amplitude(0.8);
        wait(50);
        waveform1.amplitude(0);
        wait(50);
        waveform1.amplitude(0.8);
        wait(50);
        waveform1.amplitude(0);
      }
      else {
        continueRecording();
      }
      break;

    case Mode::Playing:
      break;  
  }   
}

void startRecording() {
  // Find the first available file number
  for (uint8_t i=0; i<9999; i++) {
    // Format the counter as a five-digit number with leading zeroes, followed by file extension
    snprintf(filename, 11, " %05d.RAW", i);
    // Create if does not exist, do not open existing, write, sync after write
    if (!SD.exists(filename)) {
      break;
    }
  }
  frec = SD.open(filename, FILE_WRITE);
  if(frec) {
    Serial.print("Recording to ");
    Serial.println(filename);
    queue1.begin();
    mode = Mode::Recording;
  }
  else {
    Serial.println("Couldn't open file to record!");
  }
}

void continueRecording() {
  // Check if there is data in the queue
  if (queue1.available() >= 2) {
    byte buffer[512];
    // Fetch 2 blocks from the audio library and copy
    // into a 512 byte buffer.  The Arduino SD library
    // is most efficient when full 512 byte sector size
    // writes are used.
    memcpy(buffer, queue1.readBuffer(), 256);
    queue1.freeBuffer();
    memcpy(buffer+256, queue1.readBuffer(), 256);
    queue1.freeBuffer();
    // Write all 512 bytes to the SD card
    frec.write(buffer, 512);
  }
}

void stopRecording() {
  // Stop adding any new data to the queue
  queue1.end();
  // Flush all existing remaining data from the queue
  while (queue1.available() > 0) {
    // Save to open file
    frec.write((byte*)queue1.readBuffer(), 256);
    queue1.freeBuffer();
  }
  // Close the file
  frec.close();
  mode = Mode::Ready;
}


void playAllRecordings() {
  // Recording files are saved in the root directory
  File dir = SD.open("/");
  
  while (true) {
    File entry =  dir.openNextFile();
    if (!entry) {
      // no more files
      entry.close();
      break;
    }

    int8_t len = strlen(entry.name());
    if (strstr(strlwr(entry.name() + (len - 4)), ".raw")) {
      Serial.print("Now playing ");
      Serial.println(entry.name());
      // Play a short beep before each message
      waveform1.amplitude(0.5);
      wait(250);
      waveform1.amplitude(0);
      // Play the file
      playRaw1.play(entry.name());
      mode = Mode::Playing;
    }
    entry.close();

    while (playRaw1.isPlaying()) {
      buttonPlay.update();
      buttonRecord.update();
      // Button is pressed again
      if(buttonPlay.risingEdge() || buttonRecord.fallingEdge()) {
        playRaw1.stop();
        mode = Mode::Ready;
        return;
      }   
    }
  }
  // All files have been played
  mode = Mode::Ready;
}

// Retrieve the current time from Teensy built-in RTC
time_t getTeensy3Time(){
  return Teensy3Clock.get();
}

// Callback to assign timestamps for file system operations
void dateTime(uint16_t* date, uint16_t* time, uint8_t* ms10) {

  // Return date using FS_DATE macro to format fields.
  *date = FS_DATE(year(), month(), day());

  // Return time using FS_TIME macro to format fields.
  *time = FS_TIME(hour(), minute(), second());

  // Return low time bits in units of 10 ms.
  *ms10 = second() & 1 ? 100 : 0;
}

// Non-blocking delay, which pauses execution of main program logic,
// but while still listening for input 
void wait(unsigned int milliseconds) {
  elapsedMillis msec=0;

  while (msec <= milliseconds) {
    buttonRecord.update();
    buttonPlay.update();
    if (buttonRecord.fallingEdge()) Serial.println("Button (pin 0) Press");
    if (buttonPlay.fallingEdge()) Serial.println("Button (pin 1) Press");
    if (buttonRecord.risingEdge()) Serial.println("Button (pin 0) Release");
    if (buttonPlay.risingEdge()) Serial.println("Button (pin 1) Release");
  }
}
 
I'm new to Teensy and not very familiar with Arduino but am good with PSoC Creator. Seems to me that, rather than use the in line coding of the buttonxxx functions, I could set up a timer ISR called say 16 times a second and test button states there. Any suggestions or thoughts on why this would not be a better way to go?
 
Update. I investigated the handset wiring and found that there was an electret condenser mic in it but the black wire was not ground (never assume!) so the polarity of the supply to the mic was reversed and there was probably some sort of oscillation happening so, for anyone who has the buzzing issue, try reversing the mic wires to the Audio PCB. THe audio is also a bit higher level now.

So I have had the same problem - I switched the wiring around on the inputs and I still get a slight buzz / hum , albeit no where near as bad as it was.
Not sure if i'm missing something else to try, but it would be great to eliminate completely, don't suppose you have any ideas?

Thanks in advance
 
So I have had the same problem - I switched the wiring around on the inputs and I still get a slight buzz / hum , albeit no where near as bad as it was.
Not sure if i'm missing something else to try, but it would be great to eliminate completely, don't suppose you have any ideas?

Thanks in advance

The reverse wiring on the mic did cure all my buzzing but I had already taken great care to route the mic wires away from all the others, especially the wires to the buttons. You can also try twisting the wires from the Audio PCB to the mic connection on the phone, twisted wires are better at avoiding hum pickup.
 
The reverse wiring on the mic did cure all my buzzing but I had already taken great care to route the mic wires away from all the others, especially the wires to the buttons. You can also try twisting the wires from the Audio PCB to the mic connection on the phone, twisted wires are better at avoiding hum pickup.
Hi. Thanks for the reply - much appreciated.
I have twisted the wiring and it has improved somewhat so thanks for the suggestion. There is still a slight humming - wondering if it’s from the solder connection between old wiring and new wires (to allow for a bit of easier tinkering). I’ve never tried ferrite beads with audio cabling, do you think this would improve it? Thanks again
 
Hi everyone! I’m looking to troubleshoot a problem I’m having with my guestbook. I’m using a decotel cradle phone (pictured).

I’ve successfully wired everything to the phone and the code works seamlessly. My issue is that when I replace the handset to the cradle, it doesn’t trigger continuity between the hook switch contacts, so the code never shuts off. I can manually depress the hook switch plunger and trigger the handset to be “replaced”. This leads me to believe my issue is related to the hook switch itself - likely to the spring on the cradle. I have tried tightening the existing spring, and also tried replacing the spring with 4 different new springs without any luck. Not sure if there is a separate issue with the hook switch contacts, or if I’m just not yet successful in the right spring tension that will allow the phone to depress the hook switch to just the right spot. Does anyone have a similar phone they’re using or have any idea what I can do to fix my problem? Any advice would be greatly appreciated !

decotel.jpeg
 
Back
Top