//user define's
#define ACK PIN_E1
#define AD PIN_E0
#define WE PIN_E2
#define BUS input_d
#define DBUS output_d
#define DNS PIN_E3
//end user defines
#define ON output_low
#define OFF output_float
#define IN input
//RAM DATA
int DIR,DD;
short int d;
/*Function: wait_ack();
Requires: NONE.
Returns : NONE.
User Function?: NO.
This Function will wait the ACK.
*/
void wait_ack(){
while(IN(ACK)){}
}
/*Function: rst_bus();
Requires: NONE.
Returns : NONE.
User Function?: NO.
This Function will float the bus.
*/
void rst_bus(){
OFF(PIN_D0);
OFF(PIN_D1);
OFF(PIN_D2);
OFF(PIN_D3);
OFF(PIN_D4);
OFF(PIN_D5);
OFF(PIN_D6);
OFF(PIN_D7);
}
/*Function: send_ack();
Requires: NONE.
Returns : NONE.
User Function?: NO.
This Function send the ACK, that requires the protocol.
*/
void send_ack (){
ON(ACK);
delay_cycles(4);
OFF(ACK);
}
/*Function: write_bus(x,y);
Requires: Data to send (x) & Address of the target (y).
Returns : NONE
User Function?: YES.
This Funtion will send a 8-bit data to 8-bit address target.
*/
void write_bus (int data,int address){
d=0x1;
ON(WE);
ON(AD);
DBUS(address);
wait_ack();
OFF(AD);
DBUS(data);
wait_ack();
rst_bus();
OFF(WE);
d=0x0;
}
/*Function: enumerate(); [to be eliminated]
Requires: NONE.
Returns : NONE.
User Function?: NO, automatically detect a new pic and enum.
The DNS pic will automatically detect a new pic and enum.
*/
void enumerate(){
write_bus(DD,0x00);
DD++;
}
/*Function: read_bus();
Requires: NONE.
Returns : Data of the Bus if the data is to this direccion.
User Function?: NO, it will be automatically called when another PIC is writing on the data bus, but you can call, if you need.
This function will read the data bus, and compare the address target with the address in the RAM, if they match, the function will send the ACK
and will store the 8 bit data.
*/
BYTE read_bus(){int data;
if(!IN(AD))
{
if(input_d()==DIR)
{
send_ack();
if(IN(AD))
{
data=BUS();
send_ack();
if(DIR==0xFF&&data==0x00){enumerate();}
}
}
}
return data;
}
/*Function: init_bus();
Requires: NONE.
Returns : NONE.
User Function?: YES.
This function will comunicate with the "DNS" for receive a valid address, if the "DNS" not response, this function will wait forever for the address.
If the DNS pin is low, the PIC will act as DNS, if is high will act as a Slave.
*/
void init_bus(){
enable_interrupts(INT_EXT);
enable_interrupts(GLOBAL);
ext_int_edge( H_TO_L );
rst_bus();
while(1){
if(!IN(DNS)){DIR=0xFF;DD=0x01;break;}
else{write_bus(0x00,0xFF);
DIR=read_bus();
break;}
}
}
#int_EXT //you need to connect the WE pin with the External Interrupt pin
void EXT_isr(void)
{
if(d==0x0){read_bus();}
}