I am currently trying to use hardware interrupts to generate a continuous loop of the following tasks:
- Turn an LED on to HIGH
- Turn off the LED to LOW after 7000 microseconds
- Turn on the LED to HIGH again after 15000 microseconds have passed since its HIGH state in number 1
- Turn it off to LOW after 7000 microseconds have elapsed.
- Wait 197.111+54.555 seconds before repeating steps from the beginning
Meanwhile an external pulse is used to trigger other devices which is being sent every 266667 microseconds in the background.
Here is the code:
#define microsInOneSecond 1000000UL
unsigned long waitBlink;
byte exState, exPin = 7;
unsigned long startEx, waitEx;
unsigned long fbstart;
unsigned long sbstart;
unsigned long sbstop;
byte ledState, ledPin = 13;
const unsigned long blinkdelay = 54555;
const unsigned long waitOffTime = 197111+ blinkdelay;
unsigned long pulsestart;
void setup() {
// put your setup code here, to run once:
Serial.begin( 115200 );
pinMode(exPin,OUTPUT);
digitalWrite(exPin,HIGH);
pinMode( ledPin, OUTPUT );
waitEx = 266666;
waitBlink = 15000;
pulsestart = micros();
}
void external()
{
if ( waitEx > 0 )
{
if ( micros() - startEx >= waitEx)
{
exState = !exState;
digitalWrite( exPin, exState );
startEx += waitEx;
}
}
else if ( exState > 0 )
{
digitalWrite( exPin, exState = LOW );
}
}
void firstBlinkStart()
{
if (micros()-pulsestart >= waitOffTime)
{
digitalWrite(ledPin,HIGH);
fbstart = micros();
Serial.println(micros());
}
}
void firstBlinkStop()
{
if(micros()-fbstart >= 7000)
{
digitalWrite(ledPin,LOW);
waitBlink = 15000;
}
}
}
void secondBlinkStart()
{
if(micros()-fbstart >= waitBlink)
{
digitalWrite(ledPin,HIGH);
sbstart = micros();
Serial.println(micros());
}
}
void secondBlinkStop()
{
if(micros()-sbstart >= 7000)
{
digitalWrite(ledPin,LOW);
pulsestart = micros();
}
}
void loop() {
// put your main code here, to run repeatedly:
external();
firstBlinkStart();
firstBlinkStop();
secondBlinkStart();
secondBlinkStop();
}
The problem right now is the timing is completely off. I am trying to make it so that in the serial monitor, I would be seeing 15,000 microseconds of difference between two numbers, followed by a difference of 251000 (197111+54555) then a difference of 15,000 again and so forth. But it is not doing that. (Note that the 7000 microseconds is just how long it is on for but does not have any bearing on the timing between each individual blink)
Thank you in advance.