Hi,
I'm trying to make 2 LEDs alternately blink at a very fast rate - up to about 350 Hz. I also need to control the duty cycle of blinking. Unfortunately, I haven't been able to do it yet with everything I've tried. I'm using the Timer library by Simon Monk (
http://www.simonmonk.org), and my code is:
#include <Timer.h>
#include <Event.h>
#include <Print.h>
const int LEDpin1 = 5; //Red LED 1
const int LEDpin2 = 11; //Green LED 1
int LEDstate1 = LOW;
int LEDstate2 = LOW;
//long previousTime = 0;
bool last = true; // Stores which LED is to be turned (updated every time led flashes)
float freq1 = 329;//Hertz = 1/second
float dc = 0.40; //duty Cycle ON (100*dc)% of the time
Timer t1; //On timer for 1
void setup()
{
/* Pin setup */
pinMode(LEDpin1, OUTPUT);
pinMode(LEDpin2, OUTPUT);
/* Timer setup */
t1.every(1000.0/freq1,flashOn);
t1.after(dc*1000.0/freq1, delaySetup);
}
void delaySetup()
{
t1.every(1000.0/freq1,flashOff);
}
void loop()
{
t1.update();
}
void flashOn()
{
//digitalWrite(LEDpin1, HIGH);
if (last)
{
// LED 1
digitalWrite(LEDpin1, HIGH);
}
else
{
// LED 2
digitalWrite(LEDpin2, HIGH);
}
}
void flashOff()
{
//digitalWrite(LEDpin1, LOW);
if (last)
{
// LED 1
digitalWrite(LEDpin1, LOW);
last = false;
}
else
{
// LED 2
digitalWrite(LEDpin2, LOW);
last = true;
}
}
I'm using a Timer to set a time to turn the LED on, and another to turn it off (after a delay). Other than that, I think the code is pretty simple. A frequency I have to use is 82.407 Hz. When I run the program, I get a flashing rate of 77.1 Hz. Any ideas on why this could be happening? And what can I do to try to flash at the correct frequency? Could using 1 timer for everything cause this?
Thank you very much for any help,
Dhruv