Hi all,
I am trying the code below and I am having some strange output behaviour. Can anyone please guide me to with could be causing this? I know that 99.9% this is not the correct way of how this should be coded, but I am not a seasoned programmer and I want to keep the code as simple as possible. Attached please also find samples of when the pulse is not showing correctly. The pulses should all look alike (same delay and same on-time). Please note that the ISRs are never triggered simultaneously.
How the program should work: I have two inputs and two outputs. The input 1 will trigger ISR OutputPin_1_ISR, while input 2 will trigger ISR OutputPin_2_ISR. Once the respective ISR is executed, it will trigger the respective output according to the pre-defined delay (defined by Pulse_Delay_currentTime and Pulse_Delay_lastTime) and on-time/pulse-high (defined by Pulse_currentTime and Pulse_lastTime).
#define Input_Pin_1 2
#define Input_Pin_2 3
#define Output_Pin_1 8
#define Output_Pin_2 9
int pulseWidth = 2500;
unsigned long Pulse_currentTime_1 = 0;
volatile unsigned long Pulse_lastTime_1 = 0;
unsigned long Pulse_currentTime_2 = 0;
volatile unsigned long Pulse_lastTime_2 = 0;
volatile int Flag_Pulse_1 = 0;
volatile int Flag_Pulse_2 = 0;
unsigned long Pulse_Delay_currentTime_1 = 0;
volatile unsigned long Pulse_Delay_lastTime_1 = 0;
unsigned long Pulse_Delay_currentTime_2 = 0;
volatile unsigned long Pulse_Delay_lastTime_2 = 0;
volatile int Flag_Pulse_Delay_1 = 1;
volatile int Flag_Pulse_Delay_2 = 1;
unsigned long delay_time = 500;
void setup()
{
pinMode(Input_Pin_1, INPUT_PULLUP);
pinMode(Input_Pin_2, INPUT_PULLUP);
pinMode(Output_Pin_1, OUTPUT);
pinMode(Output_Pin_2, OUTPUT);
attachInterrupt(digitalPinToInterrupt(Input_Pin_1), OutputPin_1_ISR, FALLING);
attachInterrupt(digitalPinToInterrupt(Input_Pin_2), OutputPin_2_ISR, FALLING);
}
void loop()
{
// PULSE OUTPUT 1
if (Flag_Pulse_1 == 1)
{
Pulse_Delay_currentTime_1 = micros();
if ((Pulse_Delay_currentTime_1 - Pulse_Delay_lastTime_1) >= delay_time)
{
Flag_Pulse_Delay_1 = 0;
}
if(Flag_Pulse_Delay_1 == 0)
{
digitalWrite(Output_Pin_1, HIGH);
Pulse_currentTime_1 = micros();
if ((Pulse_currentTime_1 - Pulse_lastTime_1) >= pulseWidth)
{
digitalWrite(Output_Pin_1, LOW);
Flag_Pulse_1 = 0;
Flag_Pulse_Delay_1 = 1;
}
}
}
// PULSE OUTPUT 2
if (Flag_Pulse_2 == 1)
{
Pulse_Delay_currentTime_2 = micros();
if ((Pulse_Delay_currentTime_2 - Pulse_Delay_lastTime_2) >= delay_time)
{
Flag_Pulse_Delay_2 = 0;
}
if(Flag_Pulse_Delay_2 == 0)
{
digitalWrite(Output_Pin_2, HIGH);
Pulse_currentTime_2 = micros();
if ((Pulse_currentTime_2 - Pulse_lastTime_2) >= pulseWidth)
{
digitalWrite(Output_Pin_2, LOW);
Flag_Pulse_2 = 0;
Flag_Pulse_Delay_2 = 1;
}
}
}
}
void OutputPin_1_ISR()
{
Flag_Pulse_1 = 1;
Flag_Pulse_Delay_1 = 1;
Pulse_lastTime_1 = micros();
Pulse_Delay_lastTime_1 = micros();
}
void OutputPin_2_ISR()
{
Flag_Pulse_2 = 1;
Flag_Pulse_Delay_2 = 1;
Pulse_lastTime_2 = micros();
Pulse_Delay_lastTime_2 = micros();
}