PIC16F877A-HITECHC Part-2 UART & EEPROM

Photo of author

By Jackson Taylor

Home » Programming » PIC16F877A-HITECHC Part-2 UART & EEPROM

As an Amazon Associate we earn from qualifying purchases.

This is part 2 of our PIC16F877A series using the HI-TECH C compiler. Here we cover two peripherals you will use in almost every project: the UART for serial communication and the internal data EEPROM for storing values that survive a power cycle. Each section gives the register steps first, then a working example.

All examples assume a 16 MHz crystal, which is why the code defines _XTAL_FREQ as 16000000. If you use a different crystal, the baud rate value changes too.

Serial communication with the UART

The PIC16F877A has one hardware USART. In asynchronous mode it needs only two pins: TX on RC6 and RX on RC7. If you want a more detailed walkthrough of UART in HI-TECH C, we have a separate post on it, and the register settings below are the core of it.

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video

Setting the baud rate

With SYNC = 0 (asynchronous) and BRGH = 0 (low speed), the baud rate is:

Baud rate = Fosc / (64 × (SPBRG + 1))

At 16 MHz, SPBRG = 25 gives 16,000,000 / (64 × 26), which is about 9615 baud. That is within roughly 0.2% of 9600, close enough for reliable communication.

UART registers and bits used

  • SPEN: enables the serial port and configures RC6/RC7 for serial use.
  • SYNC: 0 selects asynchronous mode.
  • BRGH: 0 selects the low-speed baud rate generator.
  • SPBRG: holds the baud rate divisor.
  • TXEN: enables transmission.
  • CREN: enables continuous reception.
  • TX9 / RX9: 0 keeps the data length at 8 bits.
  • TRMT: reads 1 when the transmit shift register is empty.
  • RCIF: set when a received byte is waiting in RCREG.

The datasheet also asks you to set TRISC bits 6 and 7 to 1 when using the USART, so the examples below do that with TRISC = 0xC0.

UART transmission

This program sends the letter A repeatedly. It checks TRMT before writing to TXREG so a new byte is never loaded while the previous one is still being shifted out.

#include<pic.h>
#define _XTAL_FREQ 16000000
void main() {
    TRISC = 0xC0;      // RC6 (TX) and RC7 (RX) set as per datasheet
    SPEN = 1;          // enables serial port
    SYNC = 0;          // setting in asynchronous mode
    BRGH = 0;          // selects low speed baud rate
    SPBRG = 25;        // setting baud rate @ 9600
    TXEN = 1;          // enables transmission
    TX9 = 0;           // sets transmission in 8-bit mode
    while (1) {
        if (TRMT == 1) // check status of transmit shift register for empty
        {
            TXREG = 'A'; // writes ascii value of letter A
        }
    }
}

Connect the TX pin to a PC through a level shifter such as a MAX232, or through a USB-to-serial adapter that works at the right voltage level, then open a terminal at 9600 baud, 8 data bits, no parity, 1 stop bit. You should see a stream of the letter A.

See also
PIC16F877A-HITECH C- PWM

UART reception

In this example the received character is shown on PORTB so you can see it on LEDs. Subtracting 0x30 converts an ASCII digit to its numeric value, so sending the character 5 lights the pattern for binary 0101.

#include<pic.h>
#define _XTAL_FREQ 16000000
void main()
{
    TRISC = 0xC0;      // RC6 and RC7 as per datasheet
    SPEN = 1;          // enables serial port
    SYNC = 0;          // setting in asynchronous mode
    BRGH = 0;          // selects low speed baud rate
    SPBRG = 25;        // setting baud rate @ 9600
    CREN = 1;          // enables reception
    RX9 = 0;           // sets reception in 8-bit mode
    TRISB = 0;         // PORTB as output
    PORTB = 0;
    while (1)
    {
        if (RCIF == 1)                 // a byte has been received
        {
            PORTB = (RCREG - 0x30);    // show the received digit on PORTB
        }
    }
}

The original version of this code read RCREG in a loop without checking for new data. Checking RCIF first makes sure you only act on bytes that have actually arrived. If reception stops working after a burst of data, the overrun error flag (OERR) may be set; toggling CREN off and on clears it.

If you prefer another compiler, here is the same UART setup in MikroC. And if you need serial on pins that have no hardware UART, see the http://jimmyjosep.blogspot.in/2013/11/under-standing-uartsoft.html page, or our own soft UART explained article.

Using the internal EEPROM

The PIC16F877A has 256 bytes of data EEPROM. Unlike RAM, it keeps its contents when power is removed, which makes it a good place for settings, counters and calibration values. For a longer look at EEPROM in HI-TECH C on this chip, see our dedicated post. The same idea exists on other chips too; for example, here is how it works for EEPROM on AVR chips.

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works

Steps to read a byte

  1. Put the memory location in EEADR (EEADR = 4;).
  2. Clear the EEPGD bit to select data memory (EEPGD = 0;).
  3. Set the RD bit to start the read (RD = 1;).
  4. Read the value from the EEDATA register (unsigned char a = EEDATA;).
See also
BLINKING - 8051

Step 3 was missing from the original list. The datasheet requires the RD bit to be set before the data is available in EEDATA.

Steps to write a byte

  1. Wait until any earlier write has finished (WR reads 0).
  2. Put the memory location in EEADR (EEADR = 4;).
  3. Put the value in EEDATA (EEDATA = 7;).
  4. Clear the EEPGD bit (EEPGD = 0;).
  5. Set WREN to allow writes (WREN = 1;).
  6. Disable interrupts so the next two steps are not interrupted (GIE = 0;).
  7. Write 0x55 to EECON2 (EECON2 = 0x55;).
  8. Write 0xAA to EECON2 (EECON2 = 0xAA;).
  9. Set the WR bit to start the write (WR = 1;).
  10. Re-enable interrupts and clear WREN.

The 0x55 and 0xAA sequence is a safeguard against accidental writes, and it must be done in this exact order.

EEPROM example code

The program below writes the character ‘1’ to address 4, reads it back and shows it on PORTB. The configuration word 0x3F7A selects an HS oscillator and turns off the watchdog timer and low-voltage programming. Check it against the datasheet if your setup differs.

#include<pic.h>
#define _XTAL_FREQ 16000000
__CONFIG(0x3f7a);

unsigned char eeread(unsigned char addr);
void eewrite(unsigned char addr, unsigned char data);

void main()
{
    eewrite(4, '1');
    unsigned char a = eeread(4); // data from eeprom
    TRISB = 0;
    PORTB = a;
    while (1) ;
}

unsigned char eeread(unsigned char addr)
{
    EEADR = addr;
    EEPGD = 0;
    RD = 1;
    return EEDATA;
}

void eewrite(unsigned char addr, unsigned char data)
{
    while (WR) ;       // wait for any previous write to finish
    EEADR = addr;
    EEDATA = data;
    EEPGD = 0;
    WREN = 1;
    GIE = 0;           // no interrupts during the unlock sequence
    EECON2 = 0x55;
    EECON2 = 0xAA;
    WR = 1;
    GIE = 1;
    WREN = 0;
}

Compared with the original, the functions now have explicit return types, use unsigned char for byte values, take the address as a parameter in both functions, and wait for the previous write to complete. A write takes a few milliseconds, so the wait matters when you write several bytes in a row.

See also
BLUETOOTH CONTROLLED FIRE ROBOT

Common mistakes

  • Using a baud rate value calculated for a different crystal frequency, which produces garbage characters in the terminal.
  • Connecting TTL-level TX/RX directly to a PC RS-232 port without a level shifter.
  • Forgetting to set RD before reading EEDATA.
  • Writing to EEPROM in a tight loop. EEPROM has a limited number of write cycles, so write only when a value actually changes.
  • Leaving interrupts enabled during the 0x55/0xAA unlock sequence.

FAQ

What baud rate does SPBRG = 25 give at 16 MHz?

With BRGH = 0 and SYNC = 0, it gives about 9615 baud, which is close enough to 9600 for normal serial communication.

Why does my terminal show random characters?

The usual causes are a wrong SPBRG value for your crystal, a terminal set to a different baud rate, or a missing level shifter between the PIC and the PC.

How much EEPROM does the PIC16F877A have?

It has 256 bytes of data EEPROM, so valid addresses run from 0 to 255.

Do I need to wait after writing to EEPROM?

Yes. The write is not instant, so check that the WR bit has returned to 0 before starting another write or before reading the same location back.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works