Chris Aung
Chris Aung

Reputation: 9522

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.

Upvotes: 0

Views: 1039

Answers (3)

Mufaddal Darbar
Mufaddal Darbar

Reputation: 68

I suggest you to use the debugger (inside simulator) tool provided in MPLAB X IDE and look how single instructions are being executed. Check if microprocessor is not getting reset by any peripherals.

Upvotes: 0

Merty
Merty

Reputation: 61

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."

Upvotes: 3

the busybee
the busybee

Reputation: 12653

The C runtime environment may call main() in an endless loop. This can happen deliberately like this:

/* some other stuff... */
for (;;) {
    main();
}

Or it can happen because after the return of main() the next bytes in the program memory make the processor restart, for example because of an exception, or other code following the call.

You might like to use a simulator that shows the assembly level of your program to follow the flow of control.

Another option is to use your tools to disassemble the executable.

Upvotes: 1

Related Questions