//=============================================================================
// (c) 2006 RAISONANCE
// PROJECT:   DRIVING BUZZER THROUGH ST7 TIMER PWM DEMO SYSTEM
// MODULE:    Ultralite.c
// COMPILER:  RCST7 Optimizing Compiler
// DATE:      July 2006
//-----------------------------------------------------------------------------
// DESCRIPTION:   Demonstration firmware for uRLink PRIMER
//   The uRLink will react to ambiant light variations by blinking
//   a red LED and playing a tune through its buzzer.
//=============================================================================
#include <intrins.h>            // intrinsic functions
#include <string.h>             // for memcpy

//#define DEBUG

#include <ST7\ST7LiteUs.h>      // registers and memory mapping file.
    //HW bit definitions (at the moment not included in the header files)
    at FCSR^0   hbit PGM ;
    at FCSR^1   hbit LAT ;
    at PADDR^0  hbit PADDR_0;
    at PAOR^0   hbit PAOR_0;
    at PADDR^4  hbit PADDR_4;
    at PAOR^4   hbit PAOR_4;
    at PWMCR^0  hbit PWMCR_0;
    at ATCSR^4  hbit ATCSR_4;


//*****************************************************************************
// Macro definitions
//*****************************************************************************
#define DUTYCYCLE_INIT  0xFF    // defines the wave duty cycle
#define LOWER_OCTAVE 1          // selects a lower octave

// Music instruction and note coding ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#define  _END_      0xFF        // music END.
#define  _PAUSE_    0xFE        // pause between different tunes
#define  _VOLd      0xF0        // music volume decrement.
#define  _VOLi      0xF1        // music volume increment.


// Note tone definition..........................
#define  _SI0       0x00        // SI-
#define  _DO        0x01        // DO
#define  _RE        0x02        // RE
#define  _MI        0x03        // MI
#define  _FA        0x04        // FA
#define  _SOL       0x05        // SOL
#define  _LA        0x06        // LA
#define  _SI        0x07        // SI
#define  _DO2       0x08        // DO+
#define  _M         0x09        // MUTE
#define  _RE2       0x0A        // RE
#define  _SOL2      0x0B        // SOL
#define  _FAd       0x0C        // FA#


// Note length definition........................
#define  sq         0x10        // Semiquaver notes.
#define  q          0x20        // Quaver notes.
#define  qp         0x30        // 1.5 quaver notes.
#define  c          0x40        // Crotchet notes.
#define  cn         0x60        // 1.5 crotchet notes.
#define  m          0x80        // Minim notes.

/*a note is defined here by a combination of a tone and a length, both parts
being easily retrievable with the AND binary operator: note = tone+length,
and tone&length=0*/

//*****************************************************************************
// RAM SEGMENT variables
//*****************************************************************************
unsigned char DutyCycle;        // DutyCycle of the wawe.
int Light;            // Value of the current ambiant light

/*global variable used as index for the array of notes: position in the tune*/
unsigned char current_note = 0;
/*global variable used as index for the array of notes if there is an adc init
(uRLink unplugged)*/
unsigned char current_note_init = 0;
/*global variable: shows whether an AVD interrupt already occured, or not   */
unsigned char AVDinit;

// ProgSaveScoreID: buffer that contains the programming routine
unsigned char ProgSaveScoreID[32];


//******************************************************************************
// ROM SEGMENT "constant variables"
//******************************************************************************
code unsigned char ScoreIdSaved = 0;

// Music note coding ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//     SI0  DO   RE   MI   FA   SOL  LA   SI   DO2  MUTE   RE2  SOL2  FA#

code unsigned char Note_h[]     // OCR1 high byte
#if LOWER_OCTAVE
    ={ 0x00,0x01,0x02,0x04,0x04,0x06,0x07,0x08,0x08,0x0f, 0x09, 0x0B, 0x05 };
#else
    ={ 0x08,0x08,0x09,0x0A,0x0A,0x0B,0x0B,0x0C,0x0C,0x0f, 0x0C, 0x0D, 0x0A };
#endif

code unsigned char Note_l[]     // OCR1 low byte
#if LOWER_OCTAVE
    ={ 0x30,0x10,0xB2,0x26,0xD0,0x08,0x1E,0x16,0x88,0xff, 0x58, 0x04, 0x6C };
#else
    ={ 0x18,0x88,0x59,0x13,0x68,0x04,0x8F,0x0B,0x44,0xff, 0xAC, 0x82, 0xB6 };
#endif

code unsigned char DutyTime[]
    ={ 0x0C,0x0C,0x0D,0x0D,0x0D,0x0E,0x0E,0x0E,0x0E,0x00, 0x0E, 0x0F, 0x0E };


/*the actual tune sequence: an array of notes*/
code unsigned char tune[] =
    {
    _M+sq, _M+sq,   // two "buffer" mutes needed to manage smoothly
                    // the current_note/current_note_init comparison
                    // (see TBuzz_PlayTune)
    _DO+c,_RE+c,_MI+c,_FA+c,_SOL+c,_LA+c,_SI+c,_DO2+c,_M+m, _PAUSE_,

    //Comment out the following line to test uRLink
    _DO2+c,_SI+c,_LA+c,_SOL+c,_FA+c,_MI+c,_RE+c,_DO+c,_M+m, _PAUSE_,

    // Au clair de la Lune...----------------------------
    _M+m,_DO+qp,_M+sq,_DO+qp,_M+sq,_DO+qp,_M+sq,_RE+qp,_M+sq,_MI+m,_RE+m,
    _DO+qp,_M+sq,_MI+qp,_M+sq,_RE+qp,_M+sq,_RE+qp,_M+sq,_DO+m,_M+m, _PAUSE_,

    // Jai du bon tabac...------------------------------
   _M+m,_DO+q,_RE+q,_MI+q,_DO+q,_RE+qp,_M+sq,_RE+q,_MI+q,_FA+q,_M+q,
    _FA+q,_M+q,_MI+q,_M+q,_MI+q,_M+q,_DO+q,_RE+q,_MI+q,_DO+q,_RE+qp,
    _M+sq,_RE+q,_MI+q,_FA+c,_SOL+c,_DO+m,_M+m, _PAUSE_,

    // starwars -------------------------------------------
    _M+m,_RE+sq,_M+sq,_RE+sq,_M+sq,_RE+sq,_M+sq,_SOL+m,_M+sq,_RE2+m,_M+sq,_DO2+sq,_M+sq,_SI+sq,_M+sq,
    _LA+sq, _M+sq, _SOL2+m, _M+sq, _RE2+c,_M+sq,_DO2+sq,_M+sq,_SI+sq,_M+sq,
    _LA+sq, _M+sq, _SOL2+m, _M+sq, _RE2+m,_M+sq,_DO2+sq,_M+sq,_SI+sq,_M+sq,_DO2+sq,_M+sq,_LA+m, _M+sq,
    _RE+c, _M+sq, _RE+sq, _MI+m,_M+sq,_MI+sq,_M+sq,_DO2+q,_SI+q,_LA+q,
    _SOL+q, _M+sq, _SOL+q, _LA+q,_SI+q,_LA+q,_M+sq,_MI+sq,_M+sq,_FAd+m, _M+m,
    _END_   //_END_ marks to end of the tune --------------
    };


//******************************************************************************
// Function definitions
//******************************************************************************

// ----------------------------------------------------------------------------
// ROUTINE NAME: TBuzz_Init
// INPUT/OUTPUT: None.
// DESCRIPTION:  Init for the Buzzer
// ----------------------------------------------------------------------------
void TBuzz_Init ( void )
   {
   PADDR_0 = 1;         // configure PA0 as output (for the PWM)
   PAOR_0  = 1;         // PA0 Push pull output
   PWMCR_0 = 1;         // enable PWM

   ATRH    = 0;         // frequency-controlling register: ATR
   ATRL    = 0;
   DCR0H   = 0;         // dutytime-controlling register: DCR0
   DCR0L   = 0;
   DutyCycle = DUTYCYCLE_INIT;
   ATCSR_4 = 1;         // CPU clock for the timer
   current_note = ScoreIdSaved;
   }

// ----------------------------------------------------------------------------
// ROUTINE NAME: TLAVD_Init
// INPUT/OUTPUT: None.
// DESCRIPTION:  interrupt handling initialization
// ----------------------------------------------------------------------------
void TAVD_Init ( void )
   {
   AVDTHCR = 0x02;      // detect High value (4.2V)
   SICSR = 1;           // enable interrupt
   AVDinit = 0;
   }

// ----------------------------------------------------------------------------
// ROUTINE NAME: TLED_Init
// INPUT/OUTPUT: None.
// DESCRIPTION:  LED control initialization
// ----------------------------------------------------------------------------
void TLED_Init ( void )
   {
   PADDR_4 = 1;         // PA4 as output (for the LED)
   PAOR_4  = 1;         // PA4 Push pull output
   }

// ----------------------------------------------------------------------------
// ROUTINE NAME: TLight_Init
// INPUT/OUTPUT: None.
// DESCRIPTION:  ADC init to mesure the ambiant light.
// ----------------------------------------------------------------------------
void TLight_Init ( void )
   {
   ADCCSR = 0x22;       // ADC ON, AIN2 channel
   }

// ----------------------------------------------------------------------------
// ROUTINE NAME: Read8adc
// INPUT/OUTPUT: None.
// DESCRIPTION:  Read ambiant light
// ----------------------------------------------------------------------------
#define COUNT 32
int READ_ADC ( void )
 {
 int x = 0;
 int y = 0;
 unsigned char i,j;

 for ( j = 0 ; j < COUNT ; j++ )
  {
  for ( i = 0 ; i < COUNT ; i++ )
     {
     while ( (ADCCSR&0x80) != 0x80 ) ;  // while busy wait
     x += (ADCDRH<<2)+(ADCDRL&3);       // return measured data
     }
    x = (unsigned) x / COUNT;
    y += x;
    }
  return (unsigned) y / COUNT;
  }

// ----------------------------------------------------------------------------
// ROUTINE NAME: TLight
// INPUT/OUTPUT: None.
// DESCRIPTION:  waits for light variation
// ----------------------------------------------------------------------------
#define SENSITIVITY    3      //1=>very high  50=>very low
void TLight ( void )
   {
   int x;

   while ( 1 )
      {
      x = READ_ADC();               //waiting until a light value is read

      if ( ( x > (Light + SENSITIVITY) ) || ( x < (Light - SENSITIVITY) ) )
         {
         Light = x;     //waiting until the light variation is significant
         return;
         }
      }
   }

// ----------------------------------------------------------------------------
// ROUTINE NAME: TBuzz_Wait
// INPUT/OUTPUT: Note duration (4bit MSB information) / None.
// DESCRIPTION:  Polling wait routine for note duration (based on 250ms delay).
//               duration: Quaver (2), crotchet (4) or minim (8) selection.
// ----------------------------------------------------------------------------
void TBuzz_Wait(unsigned char duration)
   {
   int i = 0;
   unsigned char uc = 0;

    while ( uc < duration )     // the following loop is run Y times
        {
        while ( i < 250 )      // this loop waits approximately 250 ms
            {
            i++;
            }
        i = 0;
        uc++;
        }
    }

// ----------------------------------------------------------------------------
// ROUTINE NAME: TBlinkLED
// INPUT/OUTPUT: none
// DESCRIPTION:  blinks a LED
// ----------------------------------------------------------------------------
void TBlinkLED ( void )
   {
   PADR = 0x10;         // light up a LED
   TBuzz_Wait(0x80);    // wait around one second
   PADR = 0;            // turn the LED off
   }

// ----------------------------------------------------------------------------
// ROUTINE NAME: TBuzz_ChgDuty
// INPUT/OUTPUT: Note Index / None.
// DESCRIPTION:  Change the PWM duty cycle in the TIMER for the volume.
//               Select the music volume for the current note.
// ----------------------------------------------------------------------------
void TBuzz_ChgDuty ( unsigned char Note ) // IN: Note Index / OUT: None.
   {
   unsigned ui = DutyCycle * DutyTime[Note];
         //the new duty cycle value is written in DCR0
   DCR0H = ui>>8; //DCR0H must be written first
   DCR0L = ui&0xff;
   }

// ----------------------------------------------------------------------------
// ROUTINE NAME: TBuzz_ChgFreq
// INPUT/OUTPUT: New note (4bit LSB information) / None.
// DESCRIPTION:  Change the PWM frequency in the TIMER for the music tone.
//               Select the music volume for the current note.
// ----------------------------------------------------------------------------
void TBuzz_ChgFreq ( unsigned char Note ) //IN: A=New note / OUT: None.
   {
   ATRH = Note_h [ Note ];  // The frequency is given by the PWM period
   ATRL = Note_l [ Note ];  // set through the OC2 registers.
   }

// ----------------------------------------------------------------------------
// ROUTINE NAME: TBuzz_PlayTune
// INPUT/OUTPUT: None.
// DESCRIPTION:  Plays a music score (one tune at a time)
// ----------------------------------------------------------------------------
void TBuzz_PlayTune ( void ) // ; IN: None / OUT: None.
    {
    if ( !current_note )
        {
        // means that _END_ has never been reached since the uRLink was plugged
        // loading the position in the tune from flash memory
        // (saved from last unplugging)
        current_note_init = (*(unsigned char*)(&ScoreIdSaved));
        if(current_note_init > current_note)
            {
            // this is the case if the uRLink has been unplugged,
            // since current_note is init'd to 0
            current_note = current_note_init;
            }
        }
    while(1)
        {
        if(tune[current_note] == _END_)
            {
            /* end of the music, reset to beginning and save position in memory */
            current_note = 1;
            // 1 is a mute at the beginning of the array of notes; differs from 0
            // keep the value which will be saved upon adc init up-to-date
            current_note_init = 1;
            break;
            }
        else if(tune[current_note] == _PAUSE_)
            {
            // end of a tune, save the position in the music, stop playing
            current_note++;
            //keep the value which will be saved upon adc init up-to-date
            current_note_init = current_note;
            break;
            }
        else
            {
            unsigned char c1 = tune[current_note];
            /*loads a note (or mute) on the relevant registers*/
            /*the note information is carried only by the 4 lowest bits*/
            TBuzz_ChgFreq(c1&0x0F);
            TBuzz_ChgDuty(c1&0x0F);
            /*waits for the duration of the note*/
            /*the duration info is carried by the 4 highest bits*/
            TBuzz_Wait(c1&0xF0);
            /*progressing in the array of notes: the tune*/
            current_note++;
            //keep the value which will be saved upon adc init up-to-date
            current_note_init = current_note;
            }
        }
    }

//-----------------------------------------------------------------------------
// ROUTINES: SaveScoreID
// INPUT/OUTPUT : None.
// DESCRIPTION :  upon AVD interrupt, saving the position in the tune
//-----------------------------------------------------------------------------
void SaveScoreID ( unsigned char pos )
   {
   // enable WriteFlash controller
   FCSR = 0x56;   //1st RASS key
   FCSR = 0xAE;   //2nd RASS key
   //write operation
   LAT = 1;  //bset FCSR,#LAT

   // write the position in the tune
   (*(unsigned char*)(&ScoreIdSaved)) = pos;

   // start the flash writing
   PGM = 1;    // launch programming stage
   while ( PGM ) ;
   return;
   }

//-----------------------------------------------------------------------------
// ROUTINE: AVD_Inter (interrupt handler)
// INPUT/OUTPUT : None.
// DESCRIPTION :  Interrupt handler (IRQ7) for AVD (vector at 0xFFEC)
//                (AVD means "Auxiliary Voltage Detector"). See reference manual.
//-----------------------------------------------------------------------------
void AVD_Inter ( void ) interrupt 7
   {
   if ( AVDinit )
      {
      // if the uRLink is unplugged, save the current position
      // in the music on the flash memory
      PADDR = 0;
      ((void (*)(unsigned char))ProgSaveScoreID) (current_note_init)  ;
      }
   else
      {
      AVDinit = 1;
      }
   }

//-----------------------------------------------------------------------------
// ROUTINE: main
//  main entry
//-----------------------------------------------------------------------------
void main ( void )
   {
   _sim_();             // disable interrupts

    // disable all external interrupts by reconfiguring IO ports.
    EICR1 = 0xAA;
    EICR2 = 0xAA;
    PAOR = 0;
    EICR1 = 0x55;
    EICR2 = 0x55;


    // copy the programming function in Data,
    // (e.g. where code can be executed while programming flash)
    memcpy(ProgSaveScoreID, SaveScoreID, sizeof ProgSaveScoreID);

    // peripherals Initialization
    TLight_Init();      // init light sensor (ADC)
    TLED_Init();        // init LED (output port)
#ifndef DEBUG
    TBuzz_Init ();      // init TIMER peripheral.
    TAVD_Init();        // init AVD (low voltage detector irq)
    _rim_();            // enable interrupts
#endif


    // play the current score
    TBuzz_PlayTune();

    // read ambiant light
    Light = READ_ADC();

    while ( 1 )
        {
        // wait for light variation
        TLight();
        // blink the LED
        TBlinkLED();
#ifndef DEBUG
        // play a score
        TBuzz_PlayTune();
#endif
        // reinitialize the ambiant Light value
        Light = READ_ADC();
        }
    }

//---- end of file ----
