OPTA Pin A0 gives an error when interrupt

There is a protrusion on the electric motor housings. The sensor gives a signal when it sees this protrusion. I want to see the time of 1 revolution of the motor. The average motor speed is 100 rpm. I wrote the program as follows. I wrote the program with interrupt. When the program enters interruption or when I press the buttons a few times, the opta gives an error. The red led flashes, the com port communication is cut off. I need to reset the opta. Why do you think the opta gives an error?

volatile unsigned long  newTime = 0;
volatile unsigned long cycleTime = 0;
void setup()
{
pinMode (LED_D0, OUTPUT); //Motor
pinMode (LEDR, OUTPUT); //Active_Input
pinMode (LED_BUILTIN, OUTPUT); //PLC_Active
pinMode (D0, OUTPUT); //Motor
pinMode (A0, INPUT); //Sensor
pinMode (A1, INPUT); //Stop_B
pinMode (A2, INPUT); // Start_B
attachInterrupt(digitalPinToInterrupt(A0), devirBekcisi, RISING);
Serial.begin(9600);
}
void loop()
{
digitalWrite (LED_BUILTIN, HIGH);//If the PLC is working, the green LED will light up.
if (digitalRead(A0)==HIGH || digitalRead(A1)==HIGH || digitalRead(A2)==HIGH) // If any of the buttons are pressed, the red LED will light up.
{
digitalWrite (LEDR, HIGH);
}
if (digitalRead(A0)==LOW && digitalRead(A1)==LOW && digitalRead(A2)==LOW) //If the hand is removed from the button, the red LED will turn off.
{
digitalWrite (LEDR, LOW);
}
if (digitalRead(A1)==HIGH )
{
digitalWrite (D0, HIGH);
digitalWrite (LED_D0, HIGH);
}
if (digitalRead(A2)==HIGH)
{
digitalWrite (D0, LOW);
digitalWrite (LED_D0, LOW);
} 
}
void devirBekcisi()
{
cycleTime=millis()-newTime;
Serial.println(cycleTime); 
newTime=millis();
Serial.println("cycleTime");
}

Hi, you need to attach the interrupt before setting pinMode because of the issue Arduino Giga attachInterrupt() resets pinMode Pullup/Pulldown · Issue #780 · arduino/ArduinoCore-mbed · GitHub
However, I suspect your crash is due to using Serial inside the ISR. Try commenting out the prints and see if it still crashes.

Thanks
I will try adding the interrupt before the pin mode.
When I deleted it from the serial communication interrupt, it gave an error.

I solved the problem. The sensor was faulty and was giving parasitic voltage. I changed the sensor and it was fixed.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.