I am using a PIC24. After solving the issue with the PLL (PIC24 PLL module is always out of lock) I am struggling with large variation in the system frequency. I wrote a small code that is used to measure the system frequency using internal LPRC timer. The primary oscillator FOSC is 8 MHZ and with PLL its pushed to 32 MHz. The FCY is FOSC/2 (16MHZ). My code is reading an FCY of 15.522 MHz which is 3 percent off the actual expected frequency. As a result I am not able to connect my PC to the UART running at 38400 bps for debugging.
I think my computer's serial port is not able to tolerate such high a drift in the baud rate and hence causing a serial port framing error. Please suggest a way to improve my frequency.
Here is my uartInit function
#define peripheralPinSelectUnLock() do { OSCCON = 0x46; OSCCON = 0x57; OSCCONbits.IOLOCK = 0; } while(0)
#define peripheralPinSelectLock() do { OSCCON = 0x46; OSCCON = 0x57; OSCCONbits.IOLOCK = 1; } while(0)
#define UART1_BAUD_RATE (38400ul)
uint32_t ui32Fcy=16000000;
unsigned long int baudRateDivider = ((ui32Fcy/(4*UART1_BAUD_RATE))-1);
peripheralPinSelectUnLock(); // PPS Unlock
PPSInput(PPS_U1RX, PPS_RP30); // RF2/RP30 as U1RX
PPSOutput(PPS_RP16, PPS_U1TX); // RF3/RP16 as U1TX
TRISFbits.TRISF2 = 1; // RF2/RP30 is set for input (RX)
TRISFbits.TRISF3 = 0; // RF3/RP16 is set for output (TX)
peripheralPinSelectLock(); // PPS Lock
U1BRG = baudRateDivider; // Divides to UART_BAUD_RATE
U1MODEbits.UARTEN = 1; // UART2 is Enabled
U1MODEbits.ABAUD = 0; // auto baud is disabled
U1MODEbits.BRGH = 1; // Low baud rate ?
U1STAbits.UTXEN = 1;
IFS0bits.U1RXIF = 0; // clear interrupt flag of rx
IEC0bits.U1RXIE = 1;
IPC2bits.U1RXIP = 7; // enable rx recieved data interrupt
The value of U1BRG (watch variable) is 103 for a baudrate of 38400.
Thanks for any help.
Best Answer
You're using the LPRC to 'measure' your crystal? Usually that's done the other way around.
Have a look at the datasheet for your PIC - section 32.2, table 32-21.
You'll find the LPRC accuracy spec is +-20%, meaning it could be anywhere between 25kHz and 37kHz depending on various factors (temperature, supply voltage, ...).
I think your baud-rate troubles are coming from somewhere else and not from your crystal.
Show us your UART initialisation code as this is most likely where the trouble is.