// Producing a sine wave on the NXP LCP1768
// Dr. E.Huckert 09/2016 (modeled after my own Arduino program)
// Results:
//    incr=4: 3700 Hz 
//    incr=2: 1868 Hz 
//    incr=1: 943 Hz

#include "mbed.h"

unsigned   count = 0;
Timeout    tOut;
AnalogOut  aout(p18);  // output on pin 18
int        incr = 4;

// -------------------------------------------------------------------------------
void timeoutCallback() 
{
   printf("after 1 sec:count=%u\r\n", count);
   count = 0;
   tOut.attach(&timeoutCallback, 1.0);
}    
 
 // 91 byte values for the integer sine function
// source: http://forum.arduino.cc/index.php?topic=69723.0
uint8_t isinTable8[] = 
{
 0, 4, 9, 13, 18, 22, 27, 31, 35, 40, 44,
 49, 53, 57, 62, 66, 70, 75, 79, 83, 87,
 91, 96, 100, 104, 108, 112, 116, 120, 124, 128,
 131, 135, 139, 143, 146, 150, 153, 157, 160, 164,
 167, 171, 174, 177, 180, 183, 186, 190, 192, 195,
 198, 201, 204, 206, 209, 211, 214, 216, 219, 221,
 223, 225, 227, 229, 231, 233, 235, 236, 238, 240,
 241, 243, 244, 245, 246, 247, 248, 249, 250, 251,
 252, 253, 253, 254, 254, 254, 255, 255, 255, 255,
};

// ------------------------------------------------------------------------------------- 
void setup() 
{
}

// -------------------------------------------------------------------------------------
// Note: the value must be normalized between 0.0 and 1.0
void outputValue(int val)
{
  float f = (float)val;
  f       = f / 255.0;
  aout    = f;
}   // end outputValue()

// ---------------------------------------------------------------------------------------------
int main()
{
  printf("starting sine generation\r\n");
  tOut.attach(&timeoutCallback, 1.0);
  //
  while (1)
  {
    // 2 loops for the positive half wave
    // First 1/4 cycle
    for (int n=0; n < 91; n += incr)
    {
      outputValue(127 + (isinTable8[n] / 2));
    }
    // second 1/4 cycle
    // output the table values backwards
    for (int n=90; n >= 0; n -= incr)
    {
      outputValue(127 + (isinTable8[n] / 2));
    }
    // third 1/4 cycle
    // mirror the table values
    for (int n=0; n < 91; n += incr)
    {
      outputValue(127 - (isinTable8[n] / 2));
    }
    // fourth 1/4 cycle
    // output the mirrored table values backwards
    for (int n=90; n >= 0; n -= incr)
    {
      outputValue(127 - (isinTable8[n] / 2));
    }
    count = count + 1;
  }  // end while (1)
  return 0;
}   // end main()
