// https://wokwi.com/projects/463632973167872001
// https://forum.arduino.cc/t/writing-code-for-an-analogue-tachometer-powered-by-attiny85/1443125
# include <TinyDebug.h>
// hack for wokwi development lose all this and all serial printing for ATTiny
# define Serial Debug
// Demonstration sketch only.
// truncated and running on the ATTiny w/ wokwi Debug
// Shows the structure: input -> [lookup/interpolation -> correction ->] output.
const byte frequencyOutputPin = 7; // ?? not yet. what ATTiny pin?
const byte voltageSensePin = A3;
const byte coilInputPin = PB2;
//... status LEDs, lose 'em if
const byte good = PB1; // pulses be being seen
const byte bad = PB4; // nothing valid to -> PWM
void setup() {
Debug.begin();
Debug.println(F("Hello, TinyDebug!"));
pinMode(good, OUTPUT);
pinMode(bad, OUTPUT);
// pinMode(frequencyOutputPin, OUTPUT);
pinMode(voltageSensePin, INPUT);
pinMode(coilInputPin, INPUT);
}
void loop() {
static unsigned long cpounter;
Serial.print(cpounter); Serial.print(" ");
cpounter++;
// ----- INPUT -----
digitalWrite(good, LOW);
digitalWrite(bad, LOW);
int analogReading = analogRead(voltageSensePin);
unsigned long upT, downT;
upT = pulseIn(coilInputPin, HIGH, 200000); // wait 0.2 seconds each
downT = pulseIn(coilInputPin, LOW, 200000);
if (!upT || !downT) {
Serial.println("no pulse");
digitalWrite(bad, HIGH);
delay(100); // spam - goes away with a timed loop execution rate
return; // no valid pulse, nothing else to do
}
// else
digitalWrite(good, HIGH);
unsigned long pulseTime = upT + downT;
// PROCESS - nothing here yet
// OUTPUT
// frequency
if (0) { // 1 will show pulse frequency, who cares? It works
Serial.print("Hz: ");
Serial.print(1000000.0 / pulseTime, 1);
}
// RPM
Serial.print(" RPM: ");
Serial.print(60000000.0 / pulseTime, 1);
if (0) { // 1 will show analog reading, who cares? It works
Serial.print(" voltageSensePin: ");
Serial.print(analogReading);
}
Serial.println("");
delay(100); // throttle/spam: do this right millis()-style - execute loop every X milliseconds
}