Oh, cool!
40 miles/hour * 8000 pulses/mile =
320000 pulses/hour * 1 hour/3600000 ms =
0.088888889 pulses/ms =
1 pulse every 11.25 ms/pulse = 11250 us/pulse --- micros per pulse at 40 mph.
I threw in some hysteresis to keep the spoiler from flapping when speed is close to 40mph.
It goes up at 40+ but does not lower until 36-.
This compiles and likely void loop will run around 80-100 times per millisecond.
// Spoiler control with hysteresis sketch, free to use, by GFS 5/26/18
unsigned long startPulse;
unsigned long fortyMPH = 11250;
unsigned long thirtysixMPH = 12500; // micros timing
byte pulseState;
byte prevState;
byte pulsePin = 5;
byte analogPin = A0;
byte spoilerUp = 222;
byte spoilerDown = 0;
void setup()
{
pinMode( analogPin, OUTPUT ); // probably not necessary for analog write
}
void loop()
{
pulseState = digitalRead( pulsePin ); // will read the same pulse many times
if (( prevState == 0 ) && ( pulseState > 0 )) // pulse start detected
{
if ( micros() - startPulse <= fortyMPH ) // faster speed, less time
{
analogWrite( analogPin, spoilerUp );
}
else if ( micros() - startPulse >= thirtysixMPH ) // hysteresis
{ // keep the spoiler
analogWrite( analogPin, spoilerDown ); // from flapping!
}
startPulse = micros();
}
prevState = pulseState;
}
BTW, can the spoiler be positioned between fully up or down? At slower speeds you might want a higher angle, airfoil lift at AOA (if not stalled) increases by the square of speed as does drag.
Heck, do you want a lot of spoiler when driving straight or only on curves?