Hà vừa thử chtr I2c: Master 16F877A, Slave 16F876A, cùng giao tiếp PC để kiểm tra dữ liệu đọc và viết của Master và Slave> Thấy rất tốt ! I2C hay thiệt! Nhiêm vụ bây giờ mình chỉ tạo giao thức dữ liệu, còn chtr service plug&play slave thì thấy hơi khó! Nhưng mònh cố gắn viết thử. Cảm ơn Hoanf, mọi người rất nhiều !!
Code:
**********************************************
Chtr Master, mình thay đổi chút ít từ chtr mẫu EX_EXTEE.
1.chỉ liên kết 2401.c (thay vì địa chỉ mặc đinh là 0xa0,
mình thay là 0x10).
2. Vẫn truyền lệnh từ PC
**********************************************
#include <16F877A.h>
#fuses XT,NOWDT,NOPROTECT,NOLVP
#use delay(clock=4000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)
#include <input.c>
#include <2401.c>
void main() {
BYTE value, cmd;
EEPROM_ADDRESS address;
init_ext_eeprom();
do {
do {
printf("\r\nRead or Write: ");
cmd=getc();
cmd=toupper(cmd);
putc(cmd);
} while ( (cmd!='R') && (cmd!='W') );
printf("\n\rLocation: ");
address = gethex1();
if(cmd=='R')
printf("\r\nValue: %X\r\n",READ_EXT_EEPROM( address ) );
if(cmd=='W') {
printf("\r\nNew value: ");
value = gethex();
printf("\n\r");
WRITE_EXT_EEPROM( address, value );
}
} while (TRUE);
}
Code:
**********************************************
Chtr Slave, thì có thay đổi chút ít từ chtr mẫu EX_Slave:
1. giám sát 3 ô nhớ trên PC
2. khai báo địa chỉ la 0x10.
**********************************************
#include <16F876A.h>
#fuses XT,NOWDT,NOPROTECT,NOLVP
#use delay(clock=4000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)
#use i2c(SLAVE, SDA=PIN_C4, SCL=PIN_C3, address=0x10)
BYTE address, buffer[0x10];
#INT_SSP
void ssp_interupt ()
{
BYTE incoming, state;
state = i2c_isr_state();
if(state < 0x80) //Master is sending data
{
incoming = i2c_read();
if(state == 1) //First received byte is address
address = incoming;
if(state == 2) //Second received byte is data
buffer[address] = incoming;
}
if(state == 0x80) //Master is requesting data
{
i2c_write(buffer[address]);
}
}
void main ()
{
enable_interrupts(GLOBAL);
enable_interrupts(INT_SSP);
while (TRUE) {
printf("\r\nValue0: %X\r\n",buffer[0]);
delay_ms(1000);
printf("\r\nValue1: %X\r\n",buffer[1]);
delay_ms(1000);
printf("\r\nValue2: %X\r\n",buffer[2]);
delay_ms(1000);
printf("\r\nValue3: %X\r\n",buffer[3]);
delay_ms(1000);
}
}
******************************************
Phần mạch điện có File đính kèm :