/*
 *  Waveform generator for curve tracer.
 *
 *  Outputs:
 *      D0-D7     ramp value
 *      D8-D10    step value
 *      A1        0 = 4 steps,  >0 = 8 steps
 */


#include "port_manipulation.h"

// first ramp level is 0 and increases up to 255,
// corresponding to ~5V
unsigned char ramp_level;

// ladder steps control variables
unsigned int step_number;
unsigned char old_a1;
unsigned int max_steps;
unsigned int delta_step;


void setup()
{
  // initialize pins for input and output
  SET_ALL_OUTPUTS(D);                 /* digital pins 0 to 7 */
  SET_PORT_MODE(B, B00000111);        /* digital pins 8 to 10 */

  ramp_level = 0;
  step_number = 1;
  max_steps = 8;
  old_a1 = 1;
  delta_step = 1;
}

void loop()
{
  unsigned char a1;
  unsigned char step_level;

  a1 = PIN_READ(C, 1);     // 1 is the position of A1 inside register C

  if (a1 == 0)        // 4 steps ladder
  {
    max_steps = 4;
    delta_step = 2;
  }
  else
  {
    max_steps = 8;    // 8 steps ladder
    delta_step = 1;
  }

  if (a1 != old_a1)
  {
    step_number = 1;
    ramp_level = 0;
    old_a1 = a1;
  }
  else
  {
    step_level = step_number * delta_step;

    PORT_WRITE(B, step_level);
    PORT_WRITE(D, ramp_level);

    ramp_level++;

    if(ramp_level == 0)
    {
      step_number++;
      if (step_number > max_steps)
      {
        step_number = 1;
      }
    }
  }
}
