View Single Post
Old 27-09-2012, 10:03 PM   #3
toancdt
Đệ tử 2 túi
 
toancdt's Avatar
 
Tham gia ngày: Apr 2011
Bài gửi: 31
:
Send a message via Yahoo to toancdt
Trích:
Nguyên văn bởi oattao View Post
Mình muốn ghi 1 byte (0xAA) vào ô nhớ 0xF1 trong Eeprom 24C00 qua I2C, sau đó đọc dữ liệu từ ô nhớ đó (0xF1) xuất ra PORTB, nhưng không hiểu sao kết quả toàn ra là PORTB = 0xFF.
Nhờ mọi người xem đoạn code của mình viết bằng CSS C có vấn đề gì không? Ngồi cả ngày mãi không được chán quá.

#include "C:\Users\oattao\Desktop\Draft\I2C.h"
void InitI2C();
void SendByte(int8 data, int8 address);
int8 ReadByte(int8 address);

void main()
{
TRISB = 0x00;
TRISC = 0xFF;
InitI2C();
SendByte(0xAA, 0xF1);
PORTB = ReadByte(0xF1);
while(1);
}
void InitI2C()
{
SSPEN = 1; // MSSP enalbe

SSPM3 = 1; // Master mode SSPM3 = ob1000
SSPM2 = 0;
SSPM1 = 0;
SSPM0 = 0;

CKE = 0;

SMP = 1; // Standard speed mode
SSPADD = 0x28;
}
void SendByte(int8 data, int8 address)
{
// Send start condition
SEN = 1;
while(!SSPIF);
SSPIF = 0;

// Select device
SSPBUF = 0b10101110;
while(!SSPIF);
SSPIF = 0;

// Selec address in device
SSPBUF = address;
while(!SSPIF);
SSPIF = 0;

// Move data to device
SSPBUF = data;
while(!SSPIF);
SSPIF = 0;

// Send stop conditon
PEN = 1;
while(!SSPIF);
SSPIF = 0;
}
int8 ReadByte(int8 address)
{
int8 data;
// Send start conditon
SEN = 1;
while(!SSPIF);
SSPIF = 0;

// Select device
SSPBUF = 0b10101110;
while(!SSPIF);
SSPIF = 0;

// Select address in device
SSPBUF = address;
while(!SSPIF);
SSPIF = 0;

// Send Restart bit
RSEN = 1;
while(!SSPIF);
SSPIF = 0;

SSPBUF = 0b10101111; // Select device
while(!SSPIF);
SSPIF = 0;

// Set RCEN
RCEN = 1;
while(!SSPIF);
SSPIF = 0;

data = SSPBUF;

// Send NACK bit
ACKEN = 1;
while(!SSPIF);
SSPIF = 0;

// Send stop bit
PEN = 1;
while(!SSPIF);
SSPIF = 0;

return data;
}
code ví dụ giao tiếp giữa 16f877a và 24c16 http://www.mediafire.com/?op7fw6p1bha53cr
__________________
[email]toancdt09@gmail.com
toancdt vẫn chưa có mặt trong diễn đàn   Trả Lời Với Trích Dẫn