#define ANALOG_REFERENCE 5.0
#define POT_VALUE 10000L
#define STEP_OHMS POT_VALUE/99
#define PULSE_TIMED 10

const int pinUD = 8;
const int pinINC = 9;
const int CS = 10;
const int pinWiper = A1;

const int tapPoints = 100;
int sampleADC = 0;
float voltage = 0;
boolean countDirection  = true;
 
void setup() {
  pinMode (CS, OUTPUT);
  digitalWrite(CS,HIGH);
  pinMode (pinUD, OUTPUT); 
  pinMode (pinINC, OUTPUT);
  pinMode(pinWiper, INPUT);
  digitalWrite(pinWiper, LOW);

  Serial.begin(9600);
  digitalWrite(CS,HIGH);

  Serial.println("\n* X9C103P Basic Operation *\n");
  Serial.print("Nominal Resistive Element ");
  Serial.print(STEP_OHMS);
  Serial.println(" Ohms");
  Serial.print("Initial sample");
  voltage = g_PrintADC(pinWiper);
  Serial.println("\nSend any character to begin.\n");
}
 
void loop() {
  while (Serial.available() <= 0);

  for (int locTap=0; locTap<2; locTap++)
  {
    countDirection  = ! countDirection;
    digitalWrite(pinUD,countDirection);
    Serial.print("Wiper Direction ");
    if (countDirection) {
      Serial.println("UP");
    }else{
      Serial.println("DOWN");
    }
    tapDance(tapPoints);
    Serial.println("");
    delay(2000);
  }
  Serial.println("Wiper Tap Synchronized.");
  Serial.print("Re-sample");
  voltage = g_PrintADC(pinWiper);
  while(true);
}

void X9C103P_INC(int enable, int pulse){
  digitalWrite(pulse, HIGH);
  delay(PULSE_TIMED);
  digitalWrite(enable,LOW);
  digitalWrite(pulse, LOW);
  delay(PULSE_TIMED);
  digitalWrite(enable,HIGH);
}

void tapDance(int taplimits)
{
    for (int tap = 0; tap < taplimits; tap++) 
    {
      String stringOne ="0";
      String stringTwo ="";
      if (countDirection) {
        stringOne += String(tap);
        stringTwo = String(tap*STEP_OHMS);
      } else {
        stringOne += String(taplimits-tap-1);
        stringTwo = String((taplimits-tap-1)*STEP_OHMS,DEC);
      }

      Serial.print("Tap = " );
      Serial.print(stringOne.substring(stringOne.length()-2));
      voltage = g_PrintADC(pinWiper);
      Serial.print("   Tap Ohm = ");
      stringTwo +="     ";
      Serial.print(stringTwo.substring(0,6));
      Serial.print("  Law = ");
      Serial.println(float (POT_VALUE )*(voltage/ANALOG_REFERENCE),0);
   
      X9C103P_INC(CS,pinINC);
      delay(200);
    } 
}

float g_PrintADC(byte anaPin)
{
  int sampleADC = analogRead(anaPin);
  float volts = (sampleADC * ANALOG_REFERENCE)/ 1023.0;
  Serial.print("   ADC = ");
  Serial.print(sampleADC);     
  Serial.print("\tVoltage = ");
  Serial.print(volts,3);
  return volts;
}