Background
I'm posting out of desperation in the hope that someone can shed some light on my PWM / RPM issue using an UNO
I'm writing a rather mammoth sketch in pieces to start with and at some point in the future ill piece it all together. Below is some code to PWM a 4 Pin 12v DC fan at 25khz and at the same time read back the RPM of the fan over the Tachometer wire.
Most of the cleverness is hidden inside the PWM.h code which can be found here PWM frequency library - Libraries - Arduino Forum
Everything works as expected when the PWM value is at 255, The RPM value returned to the console is correct
Problem
My issues seem to occur when I PWM at anything other than 0 or 255. Say I PWM at 250 I get RPM readings which are in the thousands and massively wrong.
Ground wires are connected.
I cant find anyone else but this post to help me out Problem reading RPM when using PWM on 4-pin fan - Project Guidance - Arduino Forum that said the solution they found, A didnt work in my case and B Im not sure anyone can explain the reason its works at all...
Any help appreciated.
//fan speed sensor wire attached to digital pin 2 with a 10kohm pullup resistor
//fan PWM control wire attached directly to digital pin 9
#include <PWM.h> //include PWM library http://forum.arduino.cc/index.php?topic=117425.0
volatile int half_revolutions; //allow half_revolutioins to be accesed in intterupt
int rpm; //set rpm as an integer
void setup()
{
InitTimersSafe(); //not sure what this is for, but I think i need it for PWM control?
bool success = SetPinFrequencySafe(9, 25000); //set frequency to 25kHz
pwmWrite(9, 150); // 51=20% duty cycle, 255=100% duty cycle
pinMode(2,INPUT); //set RPM pin to digital input
half_revolutions = 0;
rpm = 0;
Serial.begin(9600);
}
void loop()
{
sei(); //enable intterupts
attachInterrupt(digitalPinToInterrupt(2), fan_rpm, RISING); //record pulses as they rise
delay(10000);
detachInterrupt(digitalPinToInterrupt(2));
cli(); //disable intterupts
rpm = (half_revolutions/2)*6;
Serial.print("SPEED: ");
Serial.print(rpm);
Serial.println("rpm");
Serial.println();
rpm = 0;
half_revolutions = 0;
}
void fan_rpm()
{
++half_revolutions; //increment before returning value
}