// Version 8
const byte ThrottlePin = A0;
const byte CadenceInputPin = A2;
const byte TorqueInputPin = A3;
const byte TorqueOutputPin = A5;
const byte CadenceOutputPin = 13;
const byte TorqueAtRest = 198;
int pulseoff = 25; // milliseconds when D13 is low
int pulseon = 25; // milliseconds when D13 is high 4Hz
int cadencepulselength = 991; // in milliseconds
bool cadencestate = false;
bool pulse = false;
unsigned long startMillis;
unsigned long currentMillis;
void setup() {
pinMode(CadenceOutputPin, OUTPUT);
pinMode(TorqueInputPin, INPUT);
pinMode(TorqueOutputPin, OUTPUT); //ControllerTorquePin
pinMode(CadenceInputPin, INPUT); //PASCadencePin
digitalWrite(TorqueOutputPin, LOW);
startMillis = millis();
// Serial.begin(9600);
}
void loop() {
if (millis()>currentMillis) // run once every millisecond
{
currentMillis = millis();
// increment cadencepulselength
if (cadencepulselength < 1000) cadencepulselength++;
if (cadencestate)
{
// on cadencestate transtion from high to low, reset cadencepulselength
if (analogRead(CadenceInputPin) < 512)
{
cadencepulselength = 0;
cadencestate = false;
}
}
if (analogRead(CadenceInputPin) > 512) cadencestate = true;
// check throttle
int torqueval = analogRead(ThrottlePin) / 4; // Read the value from the throttle pin A0
if (torqueval < 75) // disable throttle if voltage < 1.5V
{
// I'm pedalling
int pastorque = analogRead(TorqueInputPin)/4; // torque input A3
if (pastorque < 80) pastorque = 80;
// replicate torque and cadence
if (analogRead(CadenceInputPin) > 512)
{
digitalWrite(CadenceOutputPin, HIGH);
// if I'm stopping for more than 1 second, set A5 to 3.8V to stop error 21
if (cadencepulselength > 100) pastorque = TorqueAtRest;
analogWrite(TorqueOutputPin, pastorque);
}
else
{
digitalWrite(CadenceOutputPin, LOW);
pastorque = 0;
// if I'm stopping for more than 1 second, set A5 to 3.5V to stop error 21
if (cadencepulselength > 100) pastorque = TorqueAtRest;
analogWrite(TorqueOutputPin, pastorque); // sync pulse
}
}
else
{
//I'm using the throttle
cadencepulselength = 991; // fix throttle release
pulse = true;
if (currentMillis > (startMillis + pulseon)) pulse = false;
if (currentMillis > (startMillis + pulseon + pulseoff)) startMillis = millis(); // reset timer clock
if (pulse) // SEND cadence and torque signal when D13 is high
{
digitalWrite(CadenceOutputPin, HIGH);
analogWrite(TorqueOutputPin, torqueval);
}
else
{
digitalWrite(CadenceOutputPin, LOW);
analogWrite(TorqueOutputPin, 0); // sync pulse
}
}
}
}