r/microcontrollers • u/Km6677 • Apr 08 '20
PIC microcontroller assignment
Hello, i have an assignment due I've spent 20 hours on and as a very beginner i am not very good at it. I have a project that is running almost correctly but there's an issue with the second loop. This code is for a microcontroller that uses and LCD and makes a timer go off. Its suppose to loop back to 0 at 23hrs 59minutes and 59 seconds. But for some reason the code will only loop back to 0 on the first run, the second run continues until 30 and then resets. Is there an easy fix for this in the for loop? PS. since the LCD can only run single digit numbers i just put th, tm and ts for tens of hours, minutes and seconds. **Please excuse the NESTED LOOPS i am made to use them i cannot use timers and counters**
https://gist.github.com/keaganm66/21e75f5df261ed17e919cffd48c0f602
3
u/bradn Apr 09 '20 edited Apr 09 '20
I can see why this happens; after the first reset you just start another nested chunk of timer loop which has no proper termination condition embedded.
Instead of starting more nested FOR's, you could break out to the next instruction after the FOR loops with a goto. Wrap that whole chunk in a WHILE to make it start the FOR loop over again. This is the "I don't want to run division instructions" approach, which can be valid in some situations on microcontrollers because those instructions are much slower (though here it doesn't matter because the whole thing is dominated by the 10ms delay and LCD access).
But for the purpose of readable code, /u/ceojp has a good suggestion of not breaking the ones and 10's digit apart; this is also a contributing cause of your inner set of FOR's not terminating properly (but again you shouldn't have that inner set in the first place).
Note that your outer loop also has the same problem as the inner loop; after the inner loop finishes running, it will go back to the outer loop and try to make the same mistake there - the timer will run once properly, the second timing will overrun to 30 hours inside the inner FOR's, and then the outer FOR's will try to keep running but since the termination conditions are still terminating at that point, it'll fall out of the outer FOR's and your main() will return (which should never happen on a microcontroller!). The fact that main() runs again to restart your timer is just due to compiler design luck. It would be just as valid for the whole program to crash or halt at that point. But anyway the point that I was making was that if you did correct the termination conditions within your inner loop, you'd have to fix it in the outer loop too or it would go up to 30 hours there too.