Electronic – PIC18F UART transmit not stopping

microchipmicrocontrollerpictransmituart

I am trying out the UART on the PIC18f45k50 for a project but when I try to transmit, it seems that the PIC keeps on transmitting "Hello World" indefinitely. I have tried turning off the transmit enable bit but this doesnt seem to have any effect. I then added the while(1) loop to trap the microcontroller in it to keep it busy however even with this it transmits the data twice before stopping.
I am viewing the transmitted data on my PC with termite and am using an rs232 to usb converter. The code is as follows:

UPDATE: The issue was that when it finishes executing the main method, it restarts the code execution and it repeats twice only when it is reprogrammed.

// Configuration Bits
#pragma config FOSC = INTOSCIO  //OscillatorSelection 
#pragma config WDTEN = OFF      //WatchdogTimerEnablebits 
#pragma config LVP = OFF        //Single-SupplyICSPEnablebit 

#define _XTAL_FREQ 16000000

#include <xc.h>
#include <string.h>
#include <stdint.h>


void USART_Init(long baudrate)
{
    float temp;
    unsigned int Baud_Value = (_XTAL_FREQ - baudrate*16)/(baudrate*16);;
    BRGH = 1;
    TRISC6=0;                       /*Make Tx pin as output*/
    TXSTA1bits.SYNC = 0;                                    //Setting Asynchronous Mode, ie UART
    RCSTA1bits.SPEN = 1;
    temp=Baud_Value;     
    SPBRG=(int)temp;                /*baud rate=9600, SPBRG = (F_CPU  /(64*9600))-1*/
    //TXSTAbits.TXEN=1;                     /*Transmit Enable(TX) enable*/ 
}

 void USART_TxChar(char out)
{        
    while(!TRMT);            /*wait for transmit flag*/
    TXREG=out;                 /*wait for transmit flag to set which indicates TXREG is ready
                                    for another transmission*/ 
        
        
}

void USART_SendString(const char *out)
{
   while(*out!='\0')
   {            
        USART_TxChar(*out);
        out++;
   }
}

void main(void) {
   
    uint32_t dly;
    OSCCONbits.IRCF = 0b111;
    OSCCON2bits.INTSRC = 1;
    OSCCONbits.SCS = 0b10;
    ANSELD = 0; //digital
    TRISDbits.RD1 = 0;
    
    USART_Init(115200 );

    for(dly = 0;dly<100000;dly++);
    USART_TxChar(0x22);           /*Transmit character '"'  */
    USART_SendString("Hello World");    /*Transmit String*/
    USART_TxChar(0x22);           /*Transmit character '"'*/
    for(dly = 0;dly<100000;dly++);
    

    RCSTA1bits.SPEN = 0;
    TXSTA=0x00; 
    while(1){};
    
    return;
}
```

Best Answer

The code execution repeats after returning from main(), which explains the repeating transfer, and the while loop stops that.

The execution happens twice if the programming interface resets the chip twice during programming.