I got some tips in Project guidance forum and combined a Pulse counting sketch with the suggested code tips I received .
I tested the pulse counting sketch first with out modifications and it work perfect displaying serial pulse reads 0-200hz in monitor mode .
Arduino IDE would not let me put all values desired in array so I thought I would try the 5 values it would accept .
(I got an error message saying there were too many values when I tried to include them all )
After test code was added to enable PWM output the Monitor frequency read looks accurate but the PWM pin output is 0 at all speeds and the serial display for this output looks to be jibberish .
Any suggestions on what I messed up ?
// Frequency counter sketch, for measuring frequencies low enough to execute an interrupt for each cycle
// Connect the frequency source to the INT0 pin (digital pin 2 on an Arduino Uno)
volatile unsigned long firstPulseTime;
volatile unsigned long lastPulseTime;
volatile unsigned long numPulses;
const int PWMvalue[11] = { 0, 27, 43, 64, 85, }; // 107, 128, 148, 171, 192, 213, 235, 256 }
void isr()
{
unsigned long now = micros();
if (numPulses == 1)
{
firstPulseTime = now;
}
else
{
lastPulseTime = now;
}
++numPulses;
}
void setup()
{
Serial.begin(9600); // this is here so that we can print the result
// put a PWM signal on pin 3, then we can connect pin 3 to pin 2 to test the
counter removed (pinMode(3, OUTPUT);
// removed ( analogWrite(3, 128);) INJECTING MY OWN VARIABLE
SPEED VALUE VIA OPTICAL SENSOR/MOTOR D2 pin
}
// Measure the frequency over the specified sample time in
milliseconds, returning the frequency in Hz
float readFrequency(unsigned int sampleTime)
{
numPulses = 0; // prime the system to start a new reading
attachInterrupt(0, isr, RISING); // enable the interrupt
delay(sampleTime);
detachInterrupt(0);
return (numPulses < 3) ? 0 : (1000000.0 * (float)(numPulses - 2))/(float)(lastPulseTime - firstPulseTime);
}
void loop()
{
float freq = readFrequency(1000);
int bin = (freq+5/12);
PWMvalue[bin];
Serial.println(freq);
delay(1000);
Serial.println(PWMvalue[bin]);
delay(1000);
}
Modified_Frequency_counter_sketch.ino (1.61 KB)