/* 

 * File:   PICSramTest.c

 * Author: I_R_on

 *

 * Created on 29 December 2014, 23:59

 */



#include <stdio.h>

#include <stdlib.h>



#include <xc.h>



#pragma config PWRTE=OFF

#pragma config LVP=OFF

#pragma config CPD=OFF

#pragma config DEBUG=OFF

#pragma config FOSC=HS

#pragma config CP=OFF

#pragma config WDTE=OFF



#define LED1 PORTBbits.RB0

#define CLOCK PORTBbits.RB1 //Clock signal



#define CS PORTBbits.RB2

#define WE PORTBbits.RB3

#define OE PORTBbits.RB4

#define MR PORTBbits.RB5



#define _XTAL_FREQ 4000000



#define AMT 50000





void DelayMsInner(int s)// only to 3 decimals

{

    int milli_Equiv,i,j;  // milli second equivalent integer

    int milli_Equiv=1000*s;

    for(j=1;j<=milli_Equiv;j++);

}



void DelayMs(int s) {

    for (int i = 0;i<s;i++) DelayMsInner(50);

}



//Writes a byte to the memory addressed by current counter location

void writeByteToSRAM( unsigned char i) {

    CS = 0;

    WE = 0;

    OE = 1;

    PORTD = i;

    WE = 1;

    CS = 1;

    OE = 1;

}



//Reads a byte from the memory addressed by current counter location

unsigned char  readByteFromSRAM( ) {

    unsigned char memByte;

    CS = 0;

    WE = 1;

    OE = 0;

    memByte  = PORTD;

    WE = 1;

    CS = 1;

    OE = 1;

    return memByte;

}



void main(void)

{

    //Disble analog ports

    ADCON0 = 0x40;

    ADCON1 = 0x46;



    TRISBbits.TRISB0 = 0;

    TRISBbits.TRISB1 = 0;

                                                    

    TRISBbits.TRISB2 = 0;

    TRISBbits.TRISB3 = 0;

    TRISBbits.TRISB4 = 0;

    TRISBbits.TRISB5 = 0;



    //Set C port that drive the leds as output

    TRISC = 0;



    unsigned char readByte;



    long x;

    unsigned char a = 73;

    PORTC = 0;

    LED1 = 0;

    MR = 1; //Start from address 0

    _delay(AMT);

    MR = 0;

    //Set D port as Input

    TRISD = 0;

    while(x<4096)

    {

        CLOCK = 1; // clock input to counter

        writeByteToSRAM(a);

        CLOCK = 0;

        a = a ^ (a>>1);

        x = x + 1;

    }



    x = 0;

    MR = 1; //Start from address 0

    _delay(AMT);

    MR = 0;

    _delay(AMT);



    //Set D port as Input

    TRISD = 0xFF;



    int failCount = 0;



    unsigned char eqVal = 73;



    while(x<4096)

    {

        CLOCK = 1; // clock input to counter

        readByte = readByteFromSRAM();

        x = x + 1;

        if (readByte != eqVal) failCount++;

        eqVal = eqVal ^ (eqVal>>1);

        if (x == 4096) PORTC = eqVal;

        CLOCK = 0;

    }



    if (failCount>0) {

        LED1 = 1;

    } else {

        LED1 = 0;

    }



    while(1) {

    }

}



