For a previous project involving stepper motors, I wanted the microcontroller to remember exactly where the stepper motor was even after power loss. There wasn’t enough time to attempt it then, so I thought I’d try something similar now.
Here is the code :
// Written by Shane Ormonde 10th Feb 2014 #include #include #include #pragma config FOSC=IRC,MCLRE=OFF,WDTEN=0,LVP=OFF,BOREN=OFF //Functions void setup(void); void ee_write(char address, char data); char ee_read(char address); //Variables int val = 1; void main(void) { setup(); val = ee_read(0); // read eeprom address 0 if(val == 1) LATBbits.LATB7 = 1; if(val == 2) LATCbits.LATC7 = 1; if(val == 3) LATCbits.LATC6 = 1; if(val == 4) LATCbits.LATC3 = 1; val++; // increment val if(val > 4) val = 1; // if val goes past 4, reset it ee_write(0,val); // write the new val into address 0 while(1); } void setup(void) { OSCCON = 0b01100011; //internal oscillator block, 8MHz clock speed. TRISC = 0b00000000; TRISB = 0b00000000; LATB = 0b00000000; LATC = 0b00000000; } void ee_write(char address, char data) { EEADR = address; EEDATA = data; EECON1bits.WREN = 1; // enable eeprom write EECON1bits.EEPGD = 0; //access data eeprom memory EECON1bits.CFGS = 0; // access data eeprom memory (both bits must be cleared) EECON2 = 0x55; // datasheet says to do this EECON2 = 0xaa; // datasheet says to do this EECON1bits.WR = 1 ; // start eeprom write while( PIR2bits.EEIF == 0 ); // wait for the write to finish PIR2bits.EEIF = 0; // reset the write finished flag EECON1bits.WREN = 0; //disable eeprom writes } char ee_read(char address) { EEADR = address; EECON1bits.EEPGD = 0; // access eeprom memory EECON1bits.RD = 1; // eeprom read enable bit return EEDATA; }
Each time the PIC starts, it checks the value saved in EEPROM address 0. Depending on this value, it turns on one of four LEDs. Then the variable val is incremented by one and overwrites the previous value in EEPROM address zero. When the PIC is reset this process repeats.
The video is terrible quality so here is a pic of the circuit:
