Search code examples
cinfinite-looppicmplabxc8

Why is my C program continuously run forever without the usage of loop?


I am testing my microcontroller PIC18f4550 with the following circuit on Proteus simulation software.

enter image description here

My objective is to turn the led on for one second and turn it off.

Following is my code:

#include <xc.h>
#define _XTAL_FREQ 8000000
void delay(int t);
 
void main(void)
 {
   TRISB = 0x00; // set Port B as output
   LATB = 0x00; // set all 8 outputs on Port B to 0
   delay(20);
   LATB = 1b00000001; // set port B0 to 1
   delay(20);
   LATB = 1b00000000; // set port B0 to 0
    
 }
 
 void delay(int t)
 {
    for (int i=0; i<t ; i++)
    {
       __delay_ms(50); //using xc8 compiler internal delay function - it doesn't like it if delay is too big so it is used inside for loop
    }
 }

When the simulation is run, the LED keep blinking forever. I did not use any loop in my program and I only intend to turn the LED on for once. What is causing the LED to blink continuously?

[EDIT 1] I found a solution to my problem. I simply added while(1){} at the end of my code to stop the PIC from going into infinite loop.


Solution

  • You are programming for a microcontrollers. They don't have an extensive OS. Most of the cases, your IDE hides the fact that your main is running in a loop (like Arduino IDE does), or exiting your program makes the microcontroller reset, and will just start the program again.

    You labeled it "mplab" , if you check the documentation of it it states: "The compiler inserts special code at the end of main() which is executed if this function ends, i.e., a return statement inside main() is executed, or code execution reaches the main()’s terminating right brace. This special code causes execution to jump to address 0, the Reset vector for all 8-bit PIC devices. This essentially performs a software Reset. Note that the state of registers after a software Reset can be different to that after a hardware Reset. It is recommended that the main() function does not end."