I cut down your code a line at a time to a bare minimum, to try and isolate the issue. In the code below the problem still exists.
volatile int ISRCounter = 0;
float RPMin = 0;
unsigned long Time = millis();
void setup()
{
Serial.begin(115200);
Serial.println("Start");
}
void loop()
{
Serial.println(millis());
if (millis() - Time > 2000)
{
Serial.println("2 seconds");
delay(50); // To allow serial prints to complete before the crash...
RPMin = (60 * ISRCounter / 20) / (1 / 48); // Simpler calculations seem to work.
Serial.println(RPMin); // This never returns.
}
}
The issue seems to be related to the calculation of RPMin, and then trying to display it... kills the Serial interface. Nothing gets printed after the attempt to print RPMin.
Also of note is that the problem does not occur if ISRCounter is not declared as "volatile".
I do not know why this is occurring, but now that the issue is a lot narrower someone on here may be able to explain what is happening.
1. Your sketch of post #1 is working fine which I have tested injecting 5-Hz interrupting signal at INT0-pin of the NANO. The process is nicely detecting changes in the properties of the interrupting signal (HIGH to LOW and LOW to HIGH; because the triggering mode is: CHNAGE).
OUTPUT:
11:37:56.361 -> Pulsos por segundo:10
11:37:56.361 -> Revoluciones por minuto:30
11:37:57.366 -> Pulsos por segundo:10
11:37:57.366 -> Revoluciones por minuto:30
2. Describe in Text what addition function(s) you want to add with the original sketch that you have collected from online. It is difficult to know from the codes you have provided.
Yes I agree, that is definitely the trigger, but still weird that...
If no attempt is made to print the variable it runs ok.
If variable is not declared as volatile it runs ok.
An even simpler example
volatile int x = 0; // If not volatile runs ok.
void setup()
{
Serial.begin(115200);
Serial.println("Start");
delay(100);
float f = x / 0;
Serial.println("Before");
delay(100);
Serial.println(f); // If comment this print runs ok.
delay(100);
Serial.println("After");
}
void loop()
{}
Divide by zero in the example is not a mistake... what it is trying to demonstrate is the odd behaviour that occurs in this sketch as a result of the invalid divide by zero.
Specifically...
Serial.print causes the sketch to freeze.
Defining x as volatile cause the sketch to freeze.
@red_car:
My post was not aimed at you, I clicked the green reply block at the bottom.
I would like to know which encoder with 20 PPM driven with a DC motor.
If ISRcounter is not declared as volatile, it is equal to 0.
The compiler might then derive that 0/something is 0.
In this case that is not really the case as something is also zero...
Without Serial.print, the value of ISRcounter is never used. So calculation is simply not implemented ...
And hence no crash.