/*  David Moleron Bermudez              */
/*  PIC Based Data Loger project.       */


#include <system.h>

/*char SSPCON@0x14;*/



void setup_hardware (void) {

 
    set_tris_b ( 0x00 ) ;
    set_tris_c (0x10);
    sspstat = 0x00;
    sspcon = 0x22;

}



void write_fram ( unsigned int addres,unsigned char data ) {
		
char hbyad;    
char lbyad;  	
	
hbyad =  addres/256;
lbyad =  addres%256;	
	
	clear_bit ( portc , 6 ); // paso 1
	
	sspbuf = 0x06; //2 Wren
	while (( sspstat & 0x01 ) == 0 ); // 2.2  
	set_bit (portc , 6 ); //3 enable pin
	
	clear_bit ( portc , 6 ); // paso 4
	
	sspbuf = 0x02;      // paso 5 Write

    while (( sspstat & 0x01 ) == 0 ); // 5.2
    
    sspbuf = hbyad;   // paso 6
    while (( sspstat & 0x01 ) == 0 ); // 6.2
    
    sspbuf = lbyad;   //7
    while (( sspstat & 0x01 ) == 0 ); // 7.2
    
    sspbuf = data;    //8
    while (( sspstat & 0x01 ) == 0 ); // 8.2
    
    
    set_bit (portc , 6 ); // 9
       
}//write
        
        
        
unsigned char read_fram ( 
    unsigned int addres ) {
    
char hbyadr;  
char lbyadr; 

hbyadr = addres/256;  
lbyadr = addres%256;

	clear_bit (portc , 6 ); // 1
    
    sspbuf = 0x03; //2 Read
    while (( sspstat & 0x01 ) == 0 ); // 2.2
	 
    sspbuf = hbyadr; //3
    while (( sspstat & 0x01 ) == 0 ); // 3.2
    
    sspbuf = lbyadr; //4
    while (( sspstat & 0x01 ) == 0 ); // 4.2
    
    sspbuf = 0xff; // 5 dummy value ??
    while (( sspstat & 0x01 ) == 0 ); // 5.2
    				
				
    							    
    return sspbuf
    ; //5.3 
      
    
}//read

void writeDac ( char hdata, char ldata ) {  //has Hight byte and low byte

 

	clear_bit (portc, 7);		//set to 0 is clear?? ,7 is enable pin for DAC.
	
	sspbuf = hdata;
	
	while (( sspstat & 0x01 ) == 0 );
	
	sspbuf = ldata; 	
	
	while (( sspstat & 0x01 ) == 0 );
	
	set_bit (portc, 7);


}//writeDac


// values for sin signal // how can I write neg numbers?? I don't put unsigned...
// DAC trabaja con 0x00 dos bytes de valor, 0x00 --> 0xff,
const char sin [8] = {  0x50, 0x75, 0xa0, 0x75, 0x50, 0x25, 0x00, 0x25 } ;




void main ( void ) 
{

int i = 0;
int j = 0;
int k = 0;
int l = 0;
char hval;   
char lval;


setup_hardware () ;

	for (i=0; i<8; i++ ) {

 
hval = sin [i] / 256; 
lval = sin [i] % 256;

	
		write_fram ( k , hval);	    // asi porque al DAC va valors de dos bytes 
		write_fram ( k+1 , lval); 	// pero la memoria es 8192 x 8 bits
									// 2 bytes dirreccion
	k= k+2;							// 1 byte dato
	}//for

	while (1){      // en principio interesa que repita, pero si no... se borra.
l = 0;
j = 0;
		
		for (j=0; j<8; j++ ) {
		
			
			writeDac ( read_fram (l) , read_fram (l+1) );    

			l= l+2;

		}//for
         
	}//while		// while de repeticion infinita


}//main  
