Giúp mình tí nha. Đang tìm hiểu về I2C nên mới viết vài lệnh đơn giản để hiểu nó làm gì. Đã truyền được data từ master sang slave tuy nhiên có rắc rối nhỏ khi slave nhận được thì nó không thực hiện chương trình chính trong main() nữa. Mọi người giúp cách khắc phục.
master: Nhấn button ở RB0 => truyền data2
Code:
#include<16F877A.h>
#use delay(clock=1000000)
#include<def_877a.h>
#use i2c (master,SCL=PIN_C3,SDA=PIN_C4)
#use fast_io(d)
int data,data2;
#int_EXT
void ngat_RB0()
{
i2c_start();
i2c_write(0x10); // slave address
i2c_write(data2); // Data to slave
delay_ms(100);
i2c_stop();
portd =data2;
data2++;
}
void main()
{
ENABLE_INTERRUPTS(INT_EXT);
ENABLE_INTERRUPTS(GLOBAL);
setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
trisd=0;
portd=0xF0;
data2 = 0x5;
if (data2==255) data2 = 0;
while (true)
{
}
}
slave: Nhận data2 hiển thị portD, port B thực hiện dịch bit. Nhưng khi nhận thì portB không dịch bit nữa
Code:
#include<def_877a.h>
#use i2c (slave,SCL=PIN_C3,SDA=PIN_C4,address =0x10)
#use fast_io(d)
#use fast_io(b)
int a,value,b;
#INT_SSP
void i2c_isr()
{
int8 state;
state = i2c_isr_state();
if(state < 0x80)
{
value = i2c_read(0);
}
if(state == 0x80)
{
i2c_write(b);
}
portb = value;
}
main()
{
enable_interrupts(GLOBAL);
enable_interrupts(INT_SSP);
trisd=0;
a=1;
b=0b10101010;
trisb=0;
portb=0;
while (true)
{
portd =a;
delay_ms(500);
if (a==128)
{
a=1;
}
else
{
a=a<<1;
}
}
}
Sẵn đây hỏi luôn làm sao để master đọc từ slave về. Và khi slave truyền bằng i2c_write() thì nó truyền dữ liệu nào?? i2c_write(b) thì nó truyền giá trị của "b" ???