X27 stepper motor

#include "SwitecX25.h"
#include "FreqMeasure.h"




const int UpdateInterval = 1000;  // 100 milliseconds speedo update rate
const int UpdateInterval2 = 50;
const double StepsPerDegree = 3.0;  // Motor step is 1/3 of a degree of rotation
const unsigned int MaxMotorRotation = 315; // 315 max degrees of movement
const unsigned int MaxMotorSteps = MaxMotorRotation * StepsPerDegree;
const double PulsesPerMile = 100.0; // Number of input pulses per mile
const double SecondsPerHour = 560.0;
const double SpeedoDegreesPerMPH = 180.0 / 120.0; // Speed on face of dial at 180 degrees is 108mph.
unsigned long PreviousMillis = 0;   // last time we updated the speedo
unsigned long PreviousMillis2 = 0;
double MinMotorStep;  // lowest step that will be used - calculated from update interval
double sum=0;
int count=0;
double avgPulseLength=0;
unsigned int motorStep = 0;
int noInputCount = 0;
float mph=0;

SwitecX25 Motor(MaxMotorSteps, 4,5,6,7); // Create the motor object with the maximum steps allowed





void setup(void) 
{

  
 



  Motor.zero(); //Initialize stepper at 0 location
  Motor.setPosition(744);
  Motor.updateBlocking();
 Motor.setPosition(0);  //0MPH
 Motor.updateBlocking();



  MinMotorStep = PulseToStep(2 * (UpdateInterval / 1000.0) * F_CPU); //Force to zero when two intervals have passed with input

  FreqMeasure.begin(); 

}

void loop() { 
 
  unsigned long currentMillis = millis();

  
  if (currentMillis - PreviousMillis >= UpdateInterval) {
    PreviousMillis = currentMillis;   
    count = 0;
    sum = 0;

    
    while (FreqMeasure.available()) {
      sum += FreqMeasure.read();
      count++;
    }

    if (count) {
     
      avgPulseLength = sum / count;
      motorStep = PulseToStep(avgPulseLength);
      noInputCount = 0;
    } 
    else if (++noInputCount == 2)  
      motorStep = 0;

  
    if (motorStep <= MinMotorStep) 
      motorStep = 0;

    Motor.setPosition(motorStep);
    
  }

  Motor.update();

  unsigned long currentMillis2 = millis();


  if (currentMillis2 - PreviousMillis2 >= UpdateInterval2) {
    PreviousMillis2 = currentMillis2; 

   mph = ((motorStep / 3)/SpeedoDegreesPerMPH); // Might be a better way of calculating mph based on input frequency
   



  }




}

unsigned int PulseToStep(double pulseLength)
{
  return (unsigned int)((F_CPU * SecondsPerHour * SpeedoDegreesPerMPH * StepsPerDegree) / (PulsesPerMile * pulseLength));
}