UKHAS Wiki

UK High Altitude Society

User Tools

Site Tools


code:i2c_eeprom

This is an old revision of the document!


I2Cmem.c

#include "i2cmem.h"
//note that with microchip EEPROM at least, the internal buffer is only 64 bytes in size, so write_data can only accept a maximum of 64 as the size
 
void init_i2c()
{
	TWBR=(u08)((float)F_CPU/(2*SCL)-8.0);	//sets the correct clock rate defined as SCL
}											//we dont need to enable the hardware - its done in write
 
u08 i2cstart()
{
	TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);	//send start
	while (!(TWCR & (1<<TWINT)));			//wait for a start to be transmitted
	if (((TWSR & 0xF8) != TW_START)&&((TWSR & 0xF8) != TW_REP_START))
	return 1;								//error
	return 0;								//worked ok
}
 
#define i2cstop TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWSTO)
 
u08 i2cwrite(char c)
{
	TWDR = c;								//load the data
	TWCR = (1<<TWINT)|(1<<TWEN);
	while (!(TWCR & (1<<TWINT)));			//wait for it to be sent
	if ((TWSR & 0xF8) !=TW_MT_SLA_ACK)
	return 2;								//error
	return 0;						
}
 
 
u08 write_data(char * c, u16 address, u08 datasize)
{
	u08 n,err;
	err|=i2cstart();
	err|=i2cwrite(SLA_W);
	err|=i2cwrite((u08)(address>>8));			//address write MSB
	err|=i2cwrite((u08)address);				//address write LSB
	for(n=0;n<datasize;n++)
	{
		err|=i2cwrite(c[n]);					//the data
	}
	i2cstop;									//send stop
	return err;									//worked ok, no error
}
 
u08 read_data(char * destination, u16 address, u08 datasize)
{
	u08 n,err;
	datasize--;
	err|=i2cstart();
	err|=i2cwrite(SLA_W);
	err|=i2cwrite((u08)(address>>8));			//address write MSB
	err|=i2cwrite((u08)address);				//address write LSB
	err|=i2cstart();							//repeated start
	TWDR=SLA_R;									//slave read mode
	TWCR = (1<<TWINT)|(1<<TWEN);
	while (!(TWCR & (1<<TWINT)));				//wait for it to be sent
	if ((TWSR & 0xF8) !=TW_MR_SLA_ACK)
	err|=4;										//error
	for(n=0;n<datasize;n++)
	{
		TWCR=((1<<TWINT)|(1<<TWEN)|(1<<TWEA));
		while (!(TWCR & (1<<TWINT)));			//wait for it to be recieved - NOTE there is no error handling
		destination[n]=TWDR;					//get the data with AK returned
		if((TWSR & 0xF8) !=TW_MR_DATA_ACK)
		err|=8;
	}
	TWCR=((1<<TWINT)|(1<<TWEN));
	while (!(TWCR & (1<<TWINT)));				//wait for it to be recieved - NOTE there is no error handling
	destination[datasize+1]=TWDR;				//send NAK for the last byte recieved
	if((TWSR & 0xF8) !=TW_MR_DATA_NACK)
	err|=16;
	i2cstop;									//send stop
	return err;
}

I2Cmem.h

#include <util/twi.h>						//I2C registers
#include "avrlibtypes.h"
 
#define SLA_W 0b10100000					//microchip 24LC512  
#define SLA_R 0b10100001
#define SCL 100000
 
void init_i2c();
u08 i2cstart();
u08 i2cwrite(char c);
u08 write_data(char * c, u16 address, u08 datasize);
u08 read_data(char * destination, u16 address, u08 datasize);
code/i2c_eeprom.1225070571.txt.gz · Last modified: 2008/10/27 01:22 by laurenceb

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki