Nerdegutta's logo

nerdegutta.no

PIC16F690 - Day 7: EEPROM Read & Write

23.11.25

Embedded

Goal:

Learn to store and retrieve non-volatile data using the internal EEPROM. We’ll store a number in EEPROM, increment it each reset or button press, and display it using LEDs.

Hardware:


Concepts:

EEPROM is non-volatile: data persists after power-off.
Use eeprom_read() and eeprom_write() (XC8 helpers). EEPROM has 256 bytes (0x00–0xFF) in PIC16F690.

Code 1: EEPROM Read at Startup, Increment and Save on Reset
#define _XTAL_FREQ 4000000
#include < xc.h >
#include < stdint.h >
#include < stdio.h >

// CONFIG
#pragma config FOSC = INTRCIO
#pragma config WDTE = OFF
#pragma config PWRTE = OFF
#pragma config MCLRE = OFF
#pragma config BOREN = OFF
#pragma config CP = OFF
#pragma config CPD = OFF

void main(void) {
    TRISB = 0xF0;  // RB0–RB3 as output for display
    ANSEL = 0;
    ANSELH = 0;

    // Read previous value
    uint8_t count = eeprom_read(0x00);

    // Increment and save back
    count++;
    eeprom_write(0x00, count);

    // Output lower 4 bits to LEDs
    PORTB = (PORTB & 0xF0) | (count & 0x0F);

    while (1) {
        // Static display of value
    }
}

Code 2: Increment EEPROM Value on Button Press (RA5)
#define _XTAL_FREQ 4000000
#include < xc.h >
#include < stdint.h >
#include < stdio.h >

// CONFIG
#pragma config FOSC = INTRCIO
#pragma config WDTE = OFF
#pragma config PWRTE = OFF
#pragma config MCLRE = OFF
#pragma config BOREN = OFF
#pragma config CP = OFF
#pragma config CPD = OFF

void main(void) {
    TRISB = 0xF0;  // RB0–RB3 as output
    TRISA5 = 1;    // RA5 as input
    ANSEL = 0;
    ANSELH = 0;
    PORTB = 0;

    uint8_t count = eeprom_read(0x00);
    PORTB = (PORTB & 0xF0) | (count & 0x0F);

    uint8_t btn_prev = 1;

    while (1) {
        if (RA5 == 0 && btn_prev == 1) {  // button press detected (active low)
            __delay_ms(30);              // debounce
            if (RA5 == 0) {
                count++;
                eeprom_write(0x00, count);
                PORTB = (PORTB & 0xF0) | (count & 0x0F);
            }
        }
        btn_prev = RA5;
    }
}