có bạn nào lam về giao tếp I2C thì giúp mình với:
đoạn code sau của mình ko ghi đọc đc ROM.
Mình dùng con ROM 24c64
đoạn code sau của mình ko ghi đọc đc ROM.
Mình dùng con ROM 24c64
Code:
#include <AT89X51.H> #include <regx51.h> sbit SCL = P0^4; sbit SDA = P0^3; void Ack(void); void Delay(unsigned int loop); unsigned char ReadROM(unsigned int addr); void WriteROM(unsigned int addr, unsigned char); void WriteByte(unsigned char bytout); void Delay(unsigned int loop) { while(loop--) ; } void BaseClock(void) //tao xung nhip tren SCL { Delay(4); SCL = 1; Delay(4); SCL = 0; } void Ack(void) // tin hieu ACK tu Master { SDA = 0; BaseClock(); SDA = 1; } void StartBit(void) //Tao bit Start { SCL = 1; SDA = 1; Delay(4); SDA = 0; Delay(4); SCL = 0; } void StopBit(void) //Bit Stop { SCL = 0; SDA = 0; SCL = 1; Delay(4); SDA = 1; Delay(4); SCL = 0; } void SetupRom(void) // Thiet lap ROM { unsigned char i; SCL = 1; SDA = 1; Delay(2); for(i=0;i<8;i++) BaseClock(); StartBit(); } void NoAck(void) { SDA = 1; BaseClock(); } void WaitTwr(void) { Delay(400); } void WriteByte(unsigned char bytout) // Ghi 1 Byte len ROM { unsigned char i; for(i=0;i<8;i++) { if((bytout & 0x80) == 0x00) SDA = 0; else SDA = 1; BaseClock(); bytout = bytout << 1; } } unsigned char ReadByte(void) //Doc 1 Byte tu ROM { unsigned char i,bytin; bit read; bytin = 0; bytin = bytin | SDA; for(i=0;i<8;i++) { BaseClock(); read = SDA; bytin = bytin << 1; bytin = bytin | read; } return(bytin); } void WriteROM(unsigned int addr, unsigned char ch) //ghi ch vao ROM tai dia chi addr { StartBit(); WriteByte(0xA0); Ack(); WriteByte(addr&0xF0); Ack(); WriteByte(addr&0x0F); Ack(); WriteByte(ch); Ack(); StopBit(); WaitTwr(); } unsigned char ReadROM(unsigned int addr) //Doc ROM tu dia chi addr { unsigned char ch; StartBit(); WriteByte(0xA0); Ack(); WriteByte(addr&0xF0); Ack(); WriteByte(addr&0x0F); Ack(); StartBit(); WriteByte(0xA1); Ack(); ch = ReadByte(); NoAck(); StopBit(); return(ch); }
Comment