Notifications
Clear all

Variables do not keep changes using ISR

5 Posts
2 Users
1 Likes
1,524 Views
LuigiCRD
(@luigicrd)
Member
Joined: 3 years ago
Posts: 6
Topic starter  

I'm making a project using an ESP32, in this project, there are some variables modified into an ISR and those changes do not survive after that the ISR returns.

I have declared those variables as volatile, but that didn't help.

The code is too long to post it here, you can see it on Github at this link:
https://github.com/LuigiCaradonna/Self-Driving-Car-ESP32

In the main.cpp file beside the pins setting and the other usual things, objects for "PID" (to control the motors speed), "Motors", "Encoders" and the "Car" classes are instantiated.

My problem is that the variable "intCount", a member of the Encoder class, is initialized to 0 and it is (or should be) increased by 1 inside the ISR() method of the same class each time that an optocoupler triggers an interrupt, but it always resets to 0 after that the interrupt service routine returns. I can say this because if I put a
Serial.println(intCount);
after the intCount++ instruction, it always prints 1.

I don't get what I am missing to have that variable to keep the updates.

Can anyone find what is my mistake?


   
Quote
(@yurkshirelad)
Member
Joined: 3 years ago
Posts: 493
 

This might be a silly question (because I don't know the code), but is there any chance the IF statement is invoked, which resets the variable to 0? I'm looking at line 52 in Encoder.cpp:

if (intCount >= (slots/2))
{
int interruptsPerSecond = (int)(slots * 1000 / (nowTime - startTime));
rpm = interruptsPerSecondToRPM(interruptsPerSecond);
startTime = nowTime;
// Reset the interrupt count
intCount = 0;
}

   
ReplyQuote
LuigiCRD
(@luigicrd)
Member
Joined: 3 years ago
Posts: 6
Topic starter  

Not a silly question, I also thought to that possibility and I put a println() inside there to test, but no, it is not executed, that if condition is never true because intCount is at most 1 while "slots/2" is 10.


   
ReplyQuote
LuigiCRD
(@luigicrd)
Member
Joined: 3 years ago
Posts: 6
Topic starter  

I've got the problem, I was creating and returning copies of the objects instead of references.


   
jker reacted
ReplyQuote
(@yurkshirelad)
Member
Joined: 3 years ago
Posts: 493
 

Glad to hear it. That was my next suggestion, honest! 😉 


   
ReplyQuote