// exper10b.c

#include "exper10a.h"

enum
{
  MainMotor,
  LED1,
  LED2,
  LASTSLOT
};

void main(void)
{
  int x;
  double dc,oldfreq,newfreq;

  oldfreq = 1193180.0/65536.0;

  set_up_new_timer(1000.0);

  newfreq = get_frequency();

  printf("old frequency = %f new frequency = %fHz\n"
  ,oldfreq,newfreq);

  x = (int)InitializeAnalog();

  printf("init ana = %X\n",x);

  // make everthing an output
  set_up_ppi(Aout_CUout_Bout_CLout);

  x = TurnOnAnalog(0, // analog channel number
                   1, // 0=no digital control, 1=forward, 2=bi-directional
                   MainMotor, // output control array number
                   PA0, // port bit for forward control
                   1); // current and last reading must differ by
                       // this much for PWM change to take place

  Blink(LED1,PA1, .03, .02);

  Blink(LED2,PA2, .3, .2);

  printf("TurnOnAnalog(..); = %d\nPress any key to continue then any key to quit -- no Ctr-C!\n",x);

  getch();

  while(!kbhit())
    CheckAnalog(0);

  portaoff();

  // be sure to restore the timer!
  restore_old_timer();
}

void CheckAnalog(int anachan)
{
  if(abs(AnalogChannel[anachan].current_value -
         AnalogChannel[anachan].last_value) > 
         AnalogChannel[anachan].NoiseBand)
    {
//      printf("last = %d current = %d\n"
//      ,AnalogChannel[anachan].current_value
//      ,AnalogChannel[anachan].last_value);

	  AnalogChannel[anachan].last_value = 
      AnalogChannel[anachan].current_value;

      if(AnalogChannel[anachan].controls_PWM == 1) // unidirectional
      {
        UniPwmDuty(AnalogChannel[anachan].arraynumber,
                   AnalogChannel[anachan].PWM_channel,
                  (double)AnalogChannel[anachan].current_value/255.0);
//        printf("duty=%4.3f",(double)AnalogChannel[anachan].current_value/255.0);
//        show(anachan);
      }
    }
}

// end exper10b.c

