//... UNO. so use the universal pin names
# define frequency_output 6 // PD2 (2) is not a PWM pin on the UNO. Use 3, 5, 6, 9, 10 or 11
# define coil_neg A4 // PC4
# define pot_in A3 // PC3
//... deserves a name
# define inputPulse A5 //... anywhere, I avoid pin 13 (SCK)
double df; // Default Rpm base output //... is zero by default
double rt; // Rpm time / Pure engine Rpm //... is zero by default
int pot; //... is zero by default
float potcorrect= 0.001; //... must use a float, and what means: to turn the pot from -1 to 1
//... this global is unused, as you define it locally
// unsigned long pulse_time(0);
void setup() {
//... remove this gratuitous comment: put your setup code here, to run once:
Serial.begin(115200);
Serial.println("\nhello, world");
pinMode(frequency_output, OUTPUT);
pinMode(coil_neg, INPUT);
//... unecessary pinMode(pot_in, INPUT);
//... it's already LOW by deafaut digitalWrite(frequency_output, LOW);
}
void loop() {
// noInterrupts();
//... remove this gratuitous comment: put your main code here, to run repeatedly:
// Voltage measuring
long pulse_time;
//... SCK? WTF. that's pin 13, just use that
//... true: SCK false pulseIn, does the same thing better
//...
bool byHand = false; //... try both. pulseIn will not hang like your while/while/while can. Will.
if (byHand) {
//... you actually need to read the pin
while (digitalRead(inputPulse) == LOW)
; //wait for High on Pin2 of PORTB
unsigned long start = micros();
while (digitalRead(inputPulse) == HIGH)
; //wait for Low
while (digitalRead(inputPulse) == LOW)
; //wait for High
pulse_time = micros() - start;
}
else { // use pulseIn
pulse_time = pulseIn(inputPulse, HIGH);
pulse_time += pulseIn(inputPulse, LOW);
}
// Rpm interpolation
//.. valid variable definition and initialisation but
//... you don't often see this around here
// double rt(60 * (1000 / (pulse_time * 4)));
// double df(pulse_time * (potcorrect * pot));
//... use floating point in you expressions or the caculation is done w/ integer maths
// double is the same as float on the UNO; using float is more honest
double rt = 60.0 * (1000000.0 / (pulse_time * 4)); // 1000000 for microseconds
pot = analogRead(pot_in); //... this comes before the next line, otherwise your pot is stale.
double df = pulse_time * (potcorrect * pot);
//Output //... formatting and additional variables
analogWrite(frequency_output, df); // Output PWM
Serial.print("df (PWM): ");
Serial.print(df, 2);
Serial.print(" rt: ");
Serial.print(rt, 2);
Serial.print(" pot: ");
Serial.print(pot);
Serial.println("");
}