Electrical – PIC16F1718 UART not working

picuart

I am currently trying to port the functionality of one of my projects from an Arduino to a PIC µC. To begin I wanted to establish a UART communication to my computer but I cannot get it to work. I tried with an TTL to USB converter and now with a logic analyzer to see if anything happens on the wire but there is nothing. I read in the datasheet the tx pin should be RC6 and I set all registers mentioned in the datasheet or in many tutorials and tried to understand them but I seem to forget something. Has anyone of you an idea?

main.c

#define _XTAL_FREQ 16000000
#include <stdio.h>
#include <stdlib.h>
#include <xc.h>

#include "uart.h"


int main(void)
{

    OSCCON = 0x7B;
    UART_Init(9600);

    while(1){              
        UART_Write('c');
        UART_Write('w');

    }
}

uart.h

char UART_Init(const long int baudrate)
{
  unsigned int x;
  x = _XTAL_FREQ/(64*baudrate)-1;               
  if(x>255){                                 
  x = _XTAL_FREQ/(16*baudrate)-1;               
  TX1STAbits.BRGH = 1;                          
  }
  if(x<256){                         
    TX1STAbits.TXEN = 1;                         
    TX1STAbits.SYNC = 0;                         
    RC1STAbits.SPEN = 1;                                                       
    SP1BRG = x;                               

    return 1;                             
  }
  return 0;                                     
}

void UART_Write(char data)
{
  while(!TX1STAbits.TRMT);
  TX1REG = data;
}

Best Answer

I think you've missed some setup register(s). I don't see BAUD1CON initialization for example.

PIC datasheets are quite good in that they summarize all the bits that can affect each peripheral. You should check that you've set each and every (non-shaded) bit or byte or word below exactly the way you want.

enter image description here

There's another similar set for asynchronous reception.


That's the proper and thorough way to do it. You can also try using MCC (Microchip Code Configurator) plugin in MPLAB-X which allows you to pick options with check boxes and so on, and generates configuration code. You can redirect STDIO to the UART.

Take care with this, I've often run into subtle bugs in this sort of aid.