This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

I2C random read.

Hi,

I need to read and write to the location address of unsigned int.Means location beyond the unsigned char i.e 255.

I am pasting the code.It works fine for the writing and reading to the location in the range of unsigned char.

#include <AT89X51.H>
#include <stdio.h>
#include <intrins.h>

#define uchar unsigned char
#define uint unsigned int
#define Byte unsigned char
#define Word unsigned int
#define bool bit
#define true 1
#define false 0

void I2CStart(void);
void I2CStop(void);
bool WaitAck(void);
void SendAck(void);
void SendNotAck(void);
void I2CSendByte(Byte);
Byte I2CReceiveByte(void);


void inoutstat(uchar);
void timetag(uchar);

#define SomeNOP(); _nop_();_nop_();_nop_();_nop_();


void read_mem(uchar );
void write_mem(uchar );

void inoutstat(void);
void timestamp(void);

sbit SDA = P2^0;
sbit SCL = P2^1;


uchar stat,buff[10],wr_buff[10],byte_address[2];


void main(void)
{
uchar i=0,SOP;


SCON = 0x50; /* SCON: mode 1, 8-bit UART, enable rcvr */
TMOD |= 0x20; /* TMOD: timer 1, mode 2, 8-bit reload */
TH1 = 0xfd; /* TH1: reload value for 1200 baud @ 16MHz */
TR1 = 1; /* TR1: timer 1 run */
TI = 1;

while(1)
{
SOP=getchar();
if(SOP=='R')
{
byte_address[0]=getchar();
read_mem(1);
printf("%c",buff[0]);

inoutstat(); // Change the Status (IN -> OUT and OUT -> IN

timestamp(); // Time Stamp the Status Change for attendance

read_mem(7);

for(i=0;i<7;i++)
printf("%c",buff[i]);

SOP=0;
}

}
printf("\n");
}


void inoutstat(void)
{
read_mem(1);
stat=buff[0];
if(stat=='I')
stat='O';
else
stat='I';

wr_buff[0]=stat;
write_mem(1);
}

void timestamp(void)
{
uchar id,hr,sec,date,month,yr;
id=byte_address[0];
hr=9;
sec=7;
date=5;
month=11;
yr=4;

wr_buff[0]=id;
wr_buff[1]=hr;
wr_buff[2]=sec;
wr_buff[3]=date;
wr_buff[4]=month;
wr_buff[5]=yr;
wr_buff[6]=stat;

byte_address[0]=1;
read_mem(1);
byte_address[0]=11;
write_mem(7);
}

void write_mem(uchar count)
{
int i;
I2CStart();
I2CSendByte(0xA2);
WaitAck();
I2CSendByte(byte_address[0]);
WaitAck();
for(i=0;i<count;i++)
{
I2CSendByte(wr_buff[i]);
WaitAck();
}
I2CStop();
}

void read_mem(uchar count)
{
uchar i;
I2CStart();
I2CSendByte(0xA2);
WaitAck();
I2CSendByte(byte_address[0]);
WaitAck();
I2CStart();
I2CSendByte(0xA3);
WaitAck();
for (i=0;i<count;i++)
{
buff[i]=I2CReceiveByte();
if (i!=count-1) SendAck();
}
SendNotAck();
I2CStop();
}

0