My Opera is closing 3rd of March

Raphael's Pflock

miscellaneous Opera, Debian, Media and German posts

Subscribe to RSS feed

[SDCC] Accessing EEPROM on PIC18 - simple example

Neither optimized (you could/should use inline assembler) nor most user-friendly (only writes single chars). However, sample code for sdcc is scarce :-)

// read and write eeprom of PIC18F2550 (and 18F2455, 18F4455, 18F4550)
// EEPROM size is 256 bytes
// (c) Raphael Wimmer. Licensed under GNU GPL v2 or higher

#include <pic18fregs.h>
#include <stdio.h>
#include <usart.h>

#pragma stack 0x300 0xff // set 64 byte stack at 0x300, needed by sdcc


void ee_write_byte(unsigned char address, unsigned char *_data){

    EEDATA = *_data;
    EEADR = address;
    // start write sequence as described in datasheet, page 91
    EECON1bits.EEPGD = 0;
    EECON1bits.CFGS = 0;
    EECON1bits.WREN = 1; // enable writes to data EEPROM
    INTCONbits.GIE = 0;  // disable interrupts
    EECON2 = 0x55;
    EECON2 = 0x0AA;
    EECON1bits.WR = 1;   // start writing
    while(EECON1bits.WR){
        _asm nop _endasm;}
    if(EECON1bits.WRERR){
        printf("ERROR: writing to EEPROM failed!\n");
    }
    EECON1bits.WREN = 0;
    INTCONbits.GIE = 1;  // enable interrupts
}

void ee_read_byte(unsigned char address, unsigned char *_data){
    EEADR = address;
    EECON1bits.CFGS = 0;
    EECON1bits.EEPGD = 0;
    EECON1bits.RD = 1;
    *_data = EEDATA;
}

void initUsart()
{
    usart_open(    // Use USART library to initialise the hardware
            USART_TX_INT_OFF
            & USART_RX_INT_OFF
            & USART_BRGH_HIGH
            & USART_ASYNCH_MODE
            & USART_EIGHT_BIT,
            10                      // '10' = 115200 Baud with 20 MHz oscillator and BRGH=1
            );
    stdout = STREAM_USART;
}



// very simple example. use on an erased eeprom

void main(){
    char save_me = 'x';
    char from_eeprom;

    initUsart();
    
    printf("EEPROM-Demo\n");
    ee_read_byte(0x00, &from_eeprom);
    printf("Char read from 0x00: %c\n", from_eeprom);
    
    ee_write_byte(0x00, &save_me);
    printf("Char written to 0x00: %c\n", save_me);
    
    ee_read_byte(0x00, &from_eeprom);
    printf("Char read from 0x00: %c\n\n", from_eeprom);
}