Search code examples
cpicterminate

I cannot get the led to blink 6 times, then terminate the program in C


Why doesn't exit() work with the PIC16f877?

#include <htc.h>
#include <pic16f877.h>
#include <stdlib.h>

#define _XTAL_FREQ 4e6

int main(void){
    int count;
    int max_count = 6;
    TRISD = 0xBF;
    for (count=0; count<max_count; ++count){
        PORTD   = 0x40;
        __delay_ms(500);
        PORTD   = 0x00;
        __delay_ms(500);
    }
    exit(0);
}

Error message:

Error   [482] lab1_home.obj; 20. symbol "_exit" is defined more than once in "startup.obj"
Error   [482] lab1_home.obj; 20. symbol "_exit" is defined more than once in "startup.obj"

And what are the reasons that these code programs build successfully, but keep the led blinking forever?

Attempt1:

#include <htc.h>
#include <pic16f877.h>

#define _XTAL_FREQ 4e6

void main(void){
    int count;
    int max_count = 6;
    TRISD = 0xBF;
    for (count=0; count<max_count; ++count){
        PORTD   = 0x40;
        __delay_ms(500);
        PORTD   = 0x00;
        __delay_ms(500);
    }
    return;
}

Attempt2:

#include <htc.h>
#include <pic16f877.h>
#include <stdio.h>
#include <stdlib.h>

#define _XTAL_FREQ 4e6

int main(void){
    int count = 0;
    int max_count = 6;
    TRISD = 0xBF;
    do {
        count++;
        PORTD   = 0x40;
        __delay_ms(500);
        PORTD   = 0x00;
        __delay_ms(500);
    } while ( count != max_count );
    abort;
}

Is the loop not exiting? Or is the way I'm trying to terminate my program wrong? Also I've considered 1 thing else...does the WDT have anything to do with this loop repeating forever?


Solution

  • This code successfully called the sleep function and exited the infinite loop (Thanks to @francis):

    #include <htc.h>
    #include <pic16f877.h>
    
    #define _XTAL_FREQ 4e6
    #define SLEEP() asm("sleep")
    
    int main(void){
        int count = 0;
        int max_count = 6;
        TRISD = 0xBF;
        while(count<max_count){
            count++;
            PORTD   = 0x40;
            __delay_ms(500);
            PORTD   = 0x00;
            __delay_ms(500);
        }
        SLEEP();
    }