// Demonstration sketch only.
// Shows the structure: input -> lookup/interpolation -> correction -> output.
const byte frequencyOutputPin = 7;
const byte voltageSensePin = A3;
const byte coilInputPin = 6;
struct LookupPoint {
float x;
float y;
};
LookupPoint rpmTable[] = {
{ 300, 10.02 },
{ 700, 89.54 },
{ 800, 126.45 },
{ 900, 171.45 },
{ 1500, 225.12 }
};
const int rpmTableSize = sizeof rpmTable / sizeof rpmTable[0];
float interpolate(LookupPoint table[], int tableSize, float input, int &x) {
for (int i = 0; i < tableSize - 1; i++) {
if (input >= table[i].x && input <= table[i + 1].x) {
float x0 = table[i].x;
float y0 = table[i].y;
float x1 = table[i + 1].x;
float y1 = table[i + 1].y;
x = i;
return y0 + (y1 - y0) * (input - x0) / (x1 - x0);
}
}
return 0; // input was outside the table range
}
void setup() {
Serial.begin(115200);
Serial.println("\n----\n");
pinMode(frequencyOutputPin, OUTPUT);
pinMode(voltageSensePin, INPUT);
pinMode(coilInputPin, INPUT);
digitalWrite(frequencyOutputPin, LOW);
}
void loop() {
static unsigned long cpounter;
Serial.print(cpounter); Serial.print(" ");
cpounter++;
// ----- INPUT -----
unsigned long upT, downT;
upT = pulseIn(coilInputPin, HIGH, 100000); // wait 0.1 seconds each
downT = pulseIn(coilInputPin, LOW, 100000);
if (!upT || !downT) {
Serial.println("no pulse");
delay(100);
return; // no valid pulse
}
// else
unsigned long pulseTime = upT + downT;
Serial.println(1000000.0 / pulseTime);
delay(100); //throttle/spem. do this right millis()-style
int analogReading = analogRead(voltageSensePin);
return; // testing just the input section
// ----- PROCESS -----
float rpm = 0;
// pulse HIGH + LOW in us
if (pulseTime > 0) {
rpm = 6000000.0 / pulseTime; // demo calculation, not necessarily correct for the real tach
}
int where;
float baseOutput = interpolate(rpmTable, rpmTableSize, rpm, where);
float voltageCorrection = analogReading / 1023.0;
int pwmOutput = baseOutput * voltageCorrection;
pwmOutput = constrain(pwmOutput, 0, 255);
// ----- OUTPUT -----
analogWrite(frequencyOutputPin, pwmOutput);
Serial.println("\n ar bo pt rpm pwm");
Serial.print(analogReading); Serial.print(" ");
Serial.print(baseOutput); Serial.print(" ");
Serial.print(pulseTime); Serial.print(" ");
Serial.print(rpm); Serial.print(" ");
Serial.print(pwmOutput);
Serial.print(" ("); Serial.print(where); Serial.print(") ");
Serial.println("\n");
delay(333);
}