DIY Audio Projects Forum
 NEW  Matt presents bias and operation data for the 6V6 tube in SE operation - 6V6 Single-Ended (SE) Ultra Linear (UL) Bias Optimization.

DIY Audio Projects Forum

Welcome to the DIY Audio Projects Message Forum. Use these forums to discuss Hi-Fi audio and to share your DIY Audio Projects. Registration is free and required to post messages and view the file attachments. Registration will only take a minute and registered users do not see any advertisements. After you have completed the online registration process, check your email (including spam/junk folder) for the verification email to activate your account. New members are under moderation - so your posts will not be visible until approved by a moderator. See the Read Me 1st, Forum RULES and Forum FAQ to get started on the forum.

It is currently 06 Dec 2019, 20:06

All times are UTC - 6 hours [ DST ]




Post new topic Reply to topic  [ 1 post ] 
Author Message
PostPosted: 11 Feb 2015, 22:48 
Offline
User avatar

Joined: 14 Oct 2014, 03:56
Posts: 5
Location: Salt Lake City, UT
Hello all,

I've just about finished up a tube amp project here at the DIY (Mini Block Ultra-Linear Class-A Push-Pull EL84 (6BQ5) Valve (Tube) Amp) and that group suggested that my incorporated Arduino should share its sketch here. Not sure myself, but here it is.

This was my first foray into the Arduino world but it was a lot of fun, frustration, and ultimately triumph. All of the code works without glitches except for the FM radio. I tried a couple TEA5767 chips and a sparkfun breakout but to no avail. Yet...

I hope that it helps out someone out there. At first glance it seems that you might be able to cut and paste your way to a finished sketch, but you soon realize that there are a lot of interconnected issues to avoid and work around. Here is what worked for me, not necessarily textbook(especially in the MP3 sketch), but again in those cases the textbook didn't work. This did. After a lot of work.

Code:

/*
This code is used to control an audio tube amp's power and input selection.  An Arduino Mega2560 activates a relay that provides
5VDC to a block of relays that in turn control (by setting the repective pins to low) the input selection and AC power to the tube amp. 
Interface with the arduino will be with; 5 capacitive touch input buttons, one power(amp), mute, as well as an up button and a down button for FM tuning.
These are controlled by an adafruit 12 input capacitive touch MPR121 breakout.
Oh yeah, the arduino will be running a TEA5767 FM breakout.
An Adafruit .56" LED seven segment backpack shows the FM station and a clock. Brightness is set by a photoresistor so that at night the display dims appropriately.
An IR sensor RadioShack 38KHz recieves signals from a simple Apple remote controlling 120AC power for tube amp, inputs, volume up, down, and mute, a left and right arrow for FM tuning and/or MP3 functions   
The volume is controlled by a Bourns motorized 100k potentiometer by remote or manually at the amp.  This is a mono tube amp running a single speaker, so the inputs are run through an edcor stereo
to mono transformer, and then to the volume. 
I tried my best to incorporate the Adafruit Music Maker MP3 breakout into the exsisting arduino functions but in the end it was a bit buggy so I removed the MP3 breakout to another arduino(Uno).
The MP3 shield plays songs at random from the SD card, pauses, and stops by recieving digital input on two pins. There is an micro SD extension cable so that is can be accessed from the outside of Amp.  I will experiment further to increase functions available.

IR library and code  http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html A big thank you to Ken Shirriff!
MPR121 cap. touch sensor breakout from Adafruit. Library and code  https://learn.adafruit.com/adafruit-mpr121-12-key-capacitive-touch-sensor-breakout-tutorial/wiring
Code for MP3 VS1053 shield from Adafruit https://learn.adafruit.com/adafruit-music-maker-shield-vs1053-mp3-wav-wave-ogg-vorbis-player/installing-software
** The code and hardware ideas for motor control came from http://www.hifivision.com/diy/44275-simple-ir-remote-motorized-alps-pot-directly-using-arduino.html
** Arduino FM receiver with TEA5767 https://www.electronicsblog.net/  I have not gotten this to work to my satisfaction yet.
** DS3231 Real Time Clock derived from code by Red Byer for DS3231   www.redstoyland.com   Find code on github  under mizraith
*/

#include <IRremote.h>              // Include the IR library
#include <SPI.h>                   // Something uses this
#include <Adafruit_MPR121.h>       // Cap.touch breakout
#include <Wire.h>                  // Everything uses this
#include "Adafruit_LEDBackpack.h"  // Seven segment LED
#include "Adafruit_GFX.h"          // Seven segment LED
#include <RTClib.h>                // DS3231 clock
#include <RTC_DS3231.h>            // DS3231 clock
#include <math.h>                  // Math for Thermistor

//  TEA5767 FM breakout             // Caution--I haven't gotten the hardware to cooperate with me.  The code does seem to work..I can hear the stations, but the signal very small.
int highCount=450;                  // This variable determines the number of loops through the FM portion beofre the LED reverts to default Clock
int DisplayOn=highCount;            // Setting FM/clock display counter for startup.
int station=1;                      // This starts the presets counter at station 1.  90.9 FM
int maxpresets=3;                   // This limits the station presets sequence.  Add one to number of stations.
double preset1=90.9;                // KRCL ----use doubles here to match the type (frequency)
double preset2=90.1;               
double frequency=preset1;
unsigned char frequencyH = 0;
unsigned char frequencyL = 0;
unsigned int frequencyB;

//LED brightness
int brightness=0;                               // Sets LED brightness 0-10, 10 is brightest, set by phototransistor output
Adafruit_7segment matrix = Adafruit_7segment(); // LED

// Clock
int time;                               // Used to calculate time for printing
RTC_DS3231 RTC;                         // Real Time Clock

// Sensors (photo and thermo)
int sensorPin=A4;                       // Pin for phototransistor
int runningTemp=0;                      // Three variables to calculate average (200 read values) temp.  My thermistor fluctuated by about 20 degrees.  This leveled things out.
int tempCounter=0;
int tempAverage=0;
int overTemp=100;                        // ...overTemp then fan turns on to cool power supply.  Over 100 degrees initiates fan for example

//remote input
IRrecv irrecv(49);                      // Receiving IR on pin 49
int Mute=0;                             // This is a counter to toggle the mute function. Mode 9
int Mode=1;                             // This is the default (starting input mode) which is FM radio.
int maxMode=5;                          // This is a counter to advance the input sequence. I have 5 inputs
int modeHold=1;                         // Placeholder for Mode while using Mode functions other than inputs like power, volume, mute etc.
long lastRemoteValue;                   // This value will save the last meaningful remote input for later recall.
int volDelay = 175;                     // This value can be changed to move volume knob in shorter/longer increments.
const long remoteInput=0x77E17A47;      // My particular remote's code when I push the "input" button
const long remotePower=0x77E14047;      // Remote's "power" code
const long remoteVolumeUp=0x77E1D047;   // Remote's "Volume up" code
const long remoteVolumeDown=0x77E1B047; // Remote's "Volume down" code
const long remoteRepeat=0xFFFFFFFF;     // Remotes's "repeat" code
const long remoteNext=0x77E1E047;       // Remote's ">" button code
const long remotePrevious=0x77E11047;   // Remote's "<" button code
const long remoteMute=0x77E1BA47;       // Remote's center button code

//Motor functions defined

void MotorOff()
{
  digitalWrite(36,LOW);
  digitalWrite(37,LOW);    // These voids set the functions for each mode of movement for the volume's motorized potentiometer.
  digitalWrite(39,LOW);    // Motor draws 100mA max and each pin can provide or sink 40mA, hence 3 pins per side.

  digitalWrite(40,LOW);
  digitalWrite(41,LOW);    // Motor operates on 5VDC and has a slip clutch so that there is no need to program a stop point. 
  digitalWrite(38,LOW);
}

void MotorUp()
{
  digitalWrite(36,HIGH);
  digitalWrite(37,HIGH);
  digitalWrite(39,HIGH);

  digitalWrite(40,LOW);
  digitalWrite(41,LOW);
  digitalWrite(38,LOW);
}


void MotorDown()
{
  digitalWrite(36,LOW);
  digitalWrite(37,LOW);
  digitalWrite(39,LOW);

  digitalWrite(40,HIGH);
  digitalWrite(41,HIGH);
  digitalWrite(38,HIGH);
}



//digital pins

int relayOne=24;       // FM Right Channel
int relayTwo=25;       // FM Left Channel
int relayThree=26;     // MP3 Right Channel
int relayFour=27;      // MP3 Left Channel
int relayFive=28;      // Bluetooth Right Channel
int relaySix=29;       // Bluetooth Left Channel
int relaySeven=30;     // RCA right Channel
int relayEight=31;     // RCA left Channel
int relayNine=32;      // 3.5mm Right Channel
int relayTen=33;       // 3.5mm Left Channel
int relayEleven=35;    // Amp power 120V AC--yellow
int relayTwelve=34;    // 5v to the other relay boards and bluetooth--blue
int relayThirteen=48;  // 5v to fan
int playNew=45;        // Used to send the Uno/MP3 player signal to pin 10
int playPause=47;      // pin 2 on Uno

void relaysHigh()      // Input relays are turned off with this function.
{
  digitalWrite(relayOne, HIGH); 
  digitalWrite(relayTwo, HIGH);
  digitalWrite(relayThree, HIGH); 
  digitalWrite(relayFour, HIGH);
  digitalWrite(relayFive, HIGH);
  digitalWrite(relaySix, HIGH); 
  digitalWrite(relaySeven, HIGH);
  digitalWrite(relayEight, HIGH);
  digitalWrite(relayNine, HIGH); 
  digitalWrite(relayTen, HIGH);
}

double Thermistor(int RawADC)                     // This function does the math on the thermistor readings.
{
  double Temp;
  Temp = log(10000.0*((1024.0/RawADC-1)));
  //         =log(10000.0/(1024.0/RawADC-1))      // for pull-up configuration
  Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
  Temp = Temp - 273.15;                           // Convert Kelvin to Celcius
  Temp = (Temp * 9.0)/ 5.0 + 32.0;                // Convert Celcius to Fahrenheit
  return Temp;
}


Adafruit_MPR121 cap = Adafruit_MPR121();          // Capacitive touch
decode_results results;                           // IR

//////////////////////////////////////////////////////////

void setup()
{
  pinMode(relayOne,   OUTPUT);        // Blocks the pins from entering default mode (Input) upon Arduino startup (that turns on the relays, I don't want that).
  pinMode(relayTwo,   OUTPUT);
  pinMode(relayThree, OUTPUT);
  pinMode(relayFour,  OUTPUT);
  pinMode(relayFive,  OUTPUT);
  pinMode(relaySix,   OUTPUT);
  pinMode(relaySeven, OUTPUT);
  pinMode(relayEight, OUTPUT);
  pinMode(relayNine,  OUTPUT);
  pinMode(relayTen,   OUTPUT);
  pinMode(relayEleven,OUTPUT);
  pinMode(relayTwelve,OUTPUT);
  pinMode (relayThirteen,OUTPUT);
  relaysHigh();                     // Set signal input (1-10) relays high to start.  High is off.
  digitalWrite(relayEleven, HIGH);  // Set AC supply relay off.
  digitalWrite(relayTwelve, HIGH);  // 5VDC general power supply (relays, bluetooth reciever) relay off.
  digitalWrite(relayThirteen, HIGH);// 5VDC fan power supply relay off.

  pinMode (playNew, OUTPUT);        // Set these two MP3 pins.  They provide simple dicrete signals to an Arduino Uno that houses the MP3 player
  pinMode (playPause, OUTPUT);
  digitalWrite(playNew, LOW);         
  digitalWrite(playPause, HIGH);     

  pinMode(36,OUTPUT);
  pinMode(37,OUTPUT);                // Setting motor impulse pins to output.
  pinMode(39,OUTPUT);
  pinMode(40,OUTPUT);
  pinMode(41,OUTPUT);
  pinMode(38,OUTPUT);
  MotorOff();                        // All motor pins to low

  cap.begin(0x5A);                                      // This starts the MPR121 breakout using address            0x5A
  matrix.begin(0x70);                                   // Initialize LED at address                                0x70
  Wire.begin();                                         // This is for communication with I2C
  setFrequency();                                       // Initialize FM TEA5767 radio at                           0x60
  RTC.begin();                                          // Real time clock (wire.begin also necessary)              0x57
  DateTime now = RTC.now();
  // DateTime compiled = DateTime(__DATE__, __TIME__);  // **** enable these two lines and upload to allow clock to snyc with computer's clock
  // RTC.adjust(DateTime(__DATE__, __TIME__));          // ******** Disable these two lines and re-upload to allow clock to function correctly in the event of resets or power outages. 
  irrecv.enableIRIn();                                  // Initialize the IR receiver
  Serial.begin(9600);                                   // Initialize serial. *** Be aware that serial introduces glitches in cap.touch if included in the cap-touch/Mode-assignment section.
}

void(* resetFunc) (void) = 0;//declare reset function at address 0  // Used to reset Arduino


//loop///////////////////////////////////

void loop()

  // This section is for the remote   
  if (irrecv.decode(&results))      // Have any IR codes been recieved?  If so,
  {
    if (results.value==remoteInput && Mode!=9) // Then, if it was the "input mode" button that was pushed on the remote and we are not muted, then
    {
      lastRemoteValue=remoteInput;  // Set the remote's placeholder equal to the "input mode" button's IR hex code, and
      Mode=++Mode;                  // Advance the amp's input mode, and
      if (Mode==maxMode) Mode=1;    // Reset input mode to 1 after it has cycled through all of the other inputs ( 1...2...3...4...1.etc..).  Maxmode=5  I have bypassed mode 5/FM radio until it works.         
      DisplayOn=highCount;          // DisplayOn counts down from from set value each time through Mode section.  When it reaches zero, the clock display comes back on
    }
    if (results.value==remoteRepeat && lastRemoteValue==remoteVolumeUp) // Or if a remote button is being held down and the last signal received before the repeat signal that
    {                                                                   // was the "volume up", then logic says the button you are holding down is the "volume up" button, so
      MotorUp();                                                        // run the motorized potentiometer clockwise
      delay(volDelay);                                                  // for this many milliseconds, then
      MotorOff();                                                       // turn off the motor.
    }
    if (results.value==remoteRepeat && lastRemoteValue==remoteVolumeDown)   
    {                                                                     
      MotorDown();
      delay(volDelay); 
      MotorOff();
    }
    if (results.value==remotePower && Mode!=9)     // Or if it was the Amp's "power" button that was pushed on the remote and we are not muted then...
    {
      lastRemoteValue=remotePower;                 // Set the remote's placeholder equal to the "power" button's IR hex code, and
      modeHold=Mode;                               // Set the placeholder for the current input mode so we don't lose our place in the input sequence.
      Mode=6;                                      // Setting Mode to 6 will send it through power on/off below.       
    }
    if (results.value==remoteVolumeUp)             // Or if it was the remote's up volume button that was pushed, then
    {
      lastRemoteValue=remoteVolumeUp;              // set the remote's placeholder equal to the "volume up" button's hex code, and
      MotorUp();                                   // run the motorized potentiometer clockwise
      delay(volDelay);                             // for this many milliseconds, then
      MotorOff();                                  // turn off the motor.
    } 
    if (results.value==remoteVolumeDown)
    {
      lastRemoteValue=remoteVolumeDown;
      MotorDown();                           
      delay(volDelay);                 
      MotorOff();                       
    }
    if (results.value==remoteNext && Mode!=9)     // Or if it was the remote's "next" button that was pushed and we are not muted, then
    {
      lastRemoteValue=remoteNext;                 // set the remote's placeholder equal to the "Next" button's hex code, and
      Mode=7;                                     // set Mode to 7.
    } 
    if (results.value==remotePrevious && Mode!=9) 
    {
      lastRemoteValue=remotePrevious;   
      Mode=8;                           
    }
    if (results.value==remoteMute)      // Or if it was the remote's "Mute" button that was pushed, then
    {
      lastRemoteValue=remoteMute;       // set the remote's placeholder equal to the "Mute" button's hex code, and
      ++Mute;                           // Advance Mute counter
      Mode=9;                           // set Mode to 9.
    }
    irrecv.resume();                    // Ready to receive the next IR code

  } ////////////////////////////////////////////////end of large remote if statement

  //This section is for the Capacitive touch breakout
  if (cap.touched())                                          // If a Capacitive touch sensor is touched...
  {                                                         
    if (cap.touched() & (1 << 0))
    {
      Mode=1;                                                 // ...and that was button one then set Mode to one and... (Mode one is set as default above)                           
      DisplayOn=highCount;
    }
    if (cap.touched() & (1 << 1))
    {
      Mode=2;                   
      DisplayOn=highCount;
    }

    if (cap.touched() & (1 << 2))
    {
      Mode=3;                                                 // The numbering of the touch buttons is off because the breakout begins numbering at 0 but I count the Modes as 1,2,3,4...
      DisplayOn=highCount;
    }
    if (cap.touched() & (1 << 3))
    {
      Mode=4;                   
      DisplayOn=highCount;
    }
    /* if (cap.touched() & (1 << 4))                          // Mode 5/FM radio disabled until bugs worked out.
     {
     Mode=5;                   
     DisplayOn=highCount;
     }
     
     */
    if (cap.touched() & (1 << 5)) Mode=6;                     // Mode 6 is for turning the Amp's power on.
    if (cap.touched() & (1 << 6)) Mode=7;                     // MP3 next or FM channel next
    if (cap.touched() & (1 << 7)) Mode=8;                     // MP3 next or FM channel previous.  Haven't figured out the MP3 previous function yet...
  }/////////////////////////////////////////////////End of cap. touch segment

  // This section takes the Mode# from the remote or cap. touch sections and operates the relays, MP3, and FM functions in the proper way.
  switch(Mode)                              // If Mode equals...
  {
  case 1:                                   // ...one then switch on MP3 input relays and turn off the other inputs...
    digitalWrite(relayOne,   HIGH); 
    digitalWrite(relayTwo,   HIGH);
    digitalWrite(relayThree,  LOW); 
    digitalWrite(relayFour,   LOW);
    digitalWrite(relayFive,  HIGH);
    digitalWrite(relaySix,   HIGH); 
    digitalWrite(relaySeven, HIGH);
    digitalWrite(relayEight, HIGH);
    digitalWrite(relayNine,  HIGH); 
    digitalWrite(relayTen,   HIGH);

    digitalWrite(playPause,   LOW);          // signal MP3 player to unpause
    modeHold=Mode;                           // I use this placeholder to keep track of our place in the input sequence (1,2,3,4,5...  1,2...),
    break;                                   // Skip to the end of the switch statement.

  case 2:   
    digitalWrite(relayOne,   HIGH);          //Bluetooth
    digitalWrite(relayTwo,   HIGH);
    digitalWrite(relayThree, HIGH); 
    digitalWrite(relayFour,  HIGH);
    digitalWrite(relayFive,   LOW);
    digitalWrite(relaySix,    LOW); 
    digitalWrite(relaySeven, HIGH);
    digitalWrite(relayEight, HIGH);
    digitalWrite(relayNine,  HIGH); 
    digitalWrite(relayTen,   HIGH); 

    digitalWrite(playPause,  HIGH);
    modeHold=Mode;
    break;   

  case 3:   
    digitalWrite(relayOne,   HIGH);          // RCA jacks
    digitalWrite(relayTwo,   HIGH);
    digitalWrite(relayThree, HIGH); 
    digitalWrite(relayFour,  HIGH);
    digitalWrite(relayFive,  HIGH);
    digitalWrite(relaySix,   HIGH); 
    digitalWrite(relaySeven,  LOW);
    digitalWrite(relayEight,  LOW);
    digitalWrite(relayNine,  HIGH); 
    digitalWrite(relayTen,   HIGH); 

    digitalWrite(playPause,  HIGH);
    modeHold=Mode;   
    break;

  case 4:   
    digitalWrite(relayOne,   HIGH);          // 3.5mm jack
    digitalWrite(relayTwo,   HIGH);
    digitalWrite(relayThree, HIGH); 
    digitalWrite(relayFour,  HIGH);
    digitalWrite(relayFive,  HIGH);
    digitalWrite(relaySix,   HIGH); 
    digitalWrite(relaySeven, HIGH);
    digitalWrite(relayEight, HIGH);
    digitalWrite(relayNine,   LOW); 
    digitalWrite(relayTen,    LOW);

    digitalWrite(playPause,  HIGH);
    modeHold=Mode;
    break;

  case 5:   
    digitalWrite(relayOne,    LOW);          // FM radio--not operational
    digitalWrite(relayTwo,    LOW);
    digitalWrite(relayThree, HIGH); 
    digitalWrite(relayFour,  HIGH);
    digitalWrite(relayFive,  HIGH);
    digitalWrite(relaySix,   HIGH); 
    digitalWrite(relaySeven, HIGH);
    digitalWrite(relayEight, HIGH);
    digitalWrite(relayNine,  HIGH); 
    digitalWrite(relayTen,   HIGH);

    digitalWrite(playPause,  HIGH);
    setFrequency();                           // Set this frequecy on FM breakout
    modeHold=Mode;
    break;

  case 6:                                     // six, then either the Amp's "power" button or the remote's "power button" was pushed, so 
    if (digitalRead(relayTwelve)==1)          // If the power relay is off, then
    {                                                   
      digitalWrite(relayEleven, LOW);         // turn 120VAC to Amp on, and
      digitalWrite(relayTwelve, LOW);         // 5VDC on, and
      delay (600);                            // pause, and
      Mode=modeHold;                          // Reset Mode to modeHold (preserves our input sequence).
      return;
    }                                   
    if (digitalRead(relayTwelve)==0)
    {
      resetFunc();                             // To keep from messing up the clock, we reset the board just before power off.  This seemed needed to preserve the clock's correct time.
      digitalWrite(relayEleven, HIGH);
      digitalWrite(relayTwelve, HIGH);
      delay(600);                              // Pause here because Mode will still be 6 if you keep your finger on cap.touch button
      Mode=modeHold;                           // and one of the if's (1 or 0) will always be true and this will toggle the relay very fast without a delay.
      return;
    }

  case 7:                                      // The "next" button was pushed (remote or cap. touch), so   
    if (modeHold==5)
    {
      ++station;                               // If we were just in FM mode, move up one in the preset station sequence.   
      if (station==maxpresets) station=1;      // If needed reset the station sequence to 1
      switch(station)                          // Station is a counter to cycle through the preset channels.  Preset at one for startup.
      {
      case 1:                                  // If station is one then set frequency to preset1.  I moved the presets up to the top so they would be easy to find and change.
        frequency=preset1;
        break;
      case 2:
        frequency=preset2;
        break;
      }
      setFrequency();                           // Now that we have our new station, run through this subroutine to set it on the FM radio
      delay (300);
      DisplayOn=highCount;                      // Set the display counter to high so that the LED displays freq. for a while                                   
      delay (10);
    }
    if (modeHold==1)                            // If the "next" button was pushed and we were in MP3 mode, we send a high signal for 10 ms to the Uno/Mp3. 
    {                                           // This will choose a new random MP3 and play it, skipping the rest of the current song
      digitalWrite(playNew, HIGH);             
      delay(10);
      digitalWrite(playNew, LOW);
    }
    Mode=modeHold;                               // Return to proper mode (1 or 2)
    break;


  case 8:                                        // The "previous" button was pushed, so
    if (modeHold==5)                             // Move back one preset in the station sequence.
    {
      --station;
      if (station==0) station=maxpresets-1;      // If needed roll back the station sequence from 1 to max-1
      switch(station)                           
      {
      case 1:                                   
        frequency=preset1;
        break;
      case 2:
        frequency=preset2;
        break;
      }
      setFrequency();
      delay (300);
      DisplayOn=highCount;                                   
      delay (10);         
    }
    if (modeHold==1)
    {
      digitalWrite(playNew, HIGH);
      delay(10);
      digitalWrite(playNew, LOW); 
    }
    Mode=modeHold;                               // Return to proper mode (1 or 2)
    break; 

  case 9:                                        // The remote's mute button was pushed 
    relaysHigh();                                // Remove input signal from Amp.
    digitalWrite(playPause, HIGH);               // This pauses MP3 player until further notice.
    if (Mute==2)                                 // This is a remote only function.  The counter is moved up one in the remote receive section.
    {                                            // First time through is the mute function, so we muted everything and we go back to receiving IR codes.
      Mode=modeHold;                             // Second time through we return to the previous mode which will reset the relays properly
      Mute=0;                                    // Reset the counter
      digitalWrite(playPause, LOW);              // Unpause MP3 player
      delay(10); 
    }
    break;                                 
  }  /////////////////////////////////end of switch statement

  // Thermistor/Fan section
  runningTemp=runningTemp+(int(Thermistor(analogRead(0))));
  ++tempCounter;
  if (tempCounter==200)
  {
    tempAverage=runningTemp/200;
    runningTemp=0;
    tempCounter=0;
    if (tempAverage>=(overTemp))   digitalWrite (relayThirteen,LOW);       // Turn on fan when temp exceeds set limit.
    if (tempAverage<=(overTemp-6)) digitalWrite (relayThirteen,HIGH);      // Turn off fan when temp falls
  }

  //  LED function               
  if (DisplayOn>0)                               // If DisplayOn counter hasn't reached zero yet, keep printing station freq. or Mode on LED
  {
    --DisplayOn;                                 // Decrease DisplayOn counter by one each time through this section
    if (Mode==5) matrix.println(frequency);      // Sets LED to print station frequency
    else if (Mode<=5) matrix.println(Mode);      // Sets LED to print Mode#
    matrix.writeDisplay();                       // Sends print data to LED chip
  }
  if (DisplayOn==0)                              // If counter is down to zero then we start displaying the time
  {
    DateTime now = RTC.now();
    if (now.hour() >= 13)  time=((now.hour()-12)*100+now.minute());   // Convert from military time to domestic.
    else if ((now.hour())==0)  time=(1200+now.minute());              // Makes the midnight hour read 12 to soothe my sensibilities
    else time=((now.hour())*100+now.minute());                        // Takes hours and shifts them to the left 2 digits, then adds minutes
    matrix.println(time);                                             // Prepare print message
    matrix.drawColon(true);                                           // Use the colon when printing clock
    matrix.writeDisplay();                                            // Send time to LED breakout for display                                       
  }

  // Phototransistor section
  brightness = analogRead(sensorPin)/250;               
  matrix.setBrightness(brightness);                     // This sets brightness of LED display. 0 is dimmest, 10 brightest. I used a 10k resistor on the transistor
  delay (10);

}  //end of loop/////////////////////////////




void setFrequency()                                    // This is the frequency set funcition for the FM radio breakout.
{
  frequencyB = 4 * (frequency * 1000000 + 225000) / 32768;
  frequencyH = frequencyB >> 8;
  frequencyL = frequencyB & 0XFF;
  delay(100);
  Wire.beginTransmission(0x60);
  Wire.write(frequencyH);
  Wire.write(frequencyL);
  Wire.write(0xB0);
  Wire.write(0x10);
  Wire.write((byte)0x00);
  Wire.endTransmission();
  delay(100);
}





This next sketch controls an Arduino Uno that runs an Adafruit MP3 music maker breakout. It's a bit of a trick to get it work at all. I would advise great patience/knowledge in order to get anything worthwhile out of it. The Uno recieves two discrete signals from the Mega. Code is derived from the official adafruit offering and this fellow's outstanding work. https://forums.adafruit.com/viewtopic.p ... aker+track Bottom of page.

Code:
// include SPI, MP3 and SD libraries
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>

//////////////////////////////////////////////////////////////////////////////////////////////////////
// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)
#define CARDCS 4     // Card chip select pin
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin
Adafruit_VS1053_FilePlayer musicPlayer =  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);
int playPause=2;
int playNew=10;
int vol=30;            // Volume level 40 is good for earbuds, smaller is louder

void setup()
{
  pinMode (playNew, INPUT);
  pinMode (playPause, INPUT);
  uint32_t seed = 0;  // Generate random seed start
  for ( uint8_t i = 10 ; i ; i-- ) {
    seed = ( seed << 5 ) + ( analogRead( 0 ) * 3 );
  }
  randomSeed( seed );  //set random seed
  musicPlayer.begin();
  SD.begin(CARDCS);
  musicPlayer.setVolume(vol, vol);
  musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT);
  Serial.begin(9600); 
}

void playAnother()
{
  if (digitalRead (playPause)==0 && !musicPlayer.playingMusic)              // If un-paused and not playing music, play some music
  {
    File path = SD.open("/");
    File results;
    char* MP3 = selectRandomFileFrom( path, results );
    delay(250);                                            // Delay is necessary for good operation
    musicPlayer.startPlayingFile(MP3);
    Serial.println ("playing MP3");
  }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
void loop()
{   
playAnother();
  playAnother();
   playAnother();

  do                                                       // do these things while music is playing, it runs through once even if music is not playing, since the while is at the end of statement
  {
    // Serial.print("  ok ");
   // Serial.print (digitalRead (playNew));
    while (digitalRead (playPause)==1) musicPlayer.pausePlaying(true);       // if Pause signal is recieved, pause player until further notice (while is necessary here)
    if (digitalRead(playNew)==1)                                             // if New signal is recieved, we delay, then check again to reduce transient errors 
    {
      delay (6);
      if (digitalRead(playNew)==1)                                           // if "New" signal is still being recieved, stop player and start a new track. 
      {
        musicPlayer.stopPlaying();
        delay (7);
        File path = SD.open("/");
        File results;
        char* MP3 = selectRandomFileFrom( path, results );
        delay(250);     
        musicPlayer.setVolume(1000, 1000);                                    // Setting volume to low level for a moment so "glitch" noise is not broadcast
        musicPlayer.startPlayingFile(MP3);
        delay (500);
        Serial.println ("playing NEW MP3");
        musicPlayer.setVolume(vol, vol);                                      // Volume back to normal
      }
    }
    if (digitalRead (playPause)==0)  musicPlayer.pausePlaying(false);         // If un-pause signal recieved, unpause player
    //int i = random(255);                                                      // "random" # generator for track selection
  }
  while (musicPlayer.playingMusic);                                           // Last part of "do/while" statement
  playAnother();
   playAnother();
    playAnother();

}

/// File listing helper
void printDirectory(File dir, int numTabs)
{
  while (true)
  {
    File entry =  dir.openNextFile();
    if (! entry)
    {
      // no more files
      //Serial.println("**nomorefiles**");
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++)
    {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory())
    {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    }
    else
    {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

// Function to select random mp3
char* selectRandomFileFrom( File dir, File result)
{
  File entry;
  int count = 0;
  dir.rewindDirectory();
  while ( entry = dir.openNextFile() )
  {
    if ( random( count ) == 0 )
    {
      result = entry;
    }
    entry.close();
    count++;
  }
  return result.name();   // returns the randomly selected file name}

}



Cheers,
Luke


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 1 post ] 

All times are UTC - 6 hours [ DST ]


Who is online

Users browsing this forum: No registered users and 5 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron
DIY Tube Projects :: DIY Tube Amp Kits :: DIY Speaker Projects :: DIY Solid State Projects :: DIY IC / Op-amp Projects :: DIY Phono Projects :: DIY Cable Projects :: Hi-Fi Audio Schematics
© diyAudioProjects.com - Terms of Service - Privacy Policy