All pastes #56713 Raw Edit

Someone

public text v1 · immutable
#56713 ·published 2006-05-17 23:23 UTC
rendered paste body
#include <util/twi.h>
#include "usart.h"
#include "i2c.h"

void i2cInit(long cpuf, long sclf){

TWSR = 0x00; // no prescaler

//SCLF = CPU_F /(16+ (2(TWBR))) -4^TWPS , where SCLF is the clock frequency of the SCL SDA lines, 1000000 or 4000000,
// so to calculate twbr, solve for it... We can get rid of "-4^TWPS", as no prescaler is involved
TWBR = (((cpuf/sclf)-16)/2);


}

int i2cStart(char address){

	TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN); // send start signal
	
	while(!(TWCR & (1<<TWINT))); // wait until it is done
	
	
	if ((TWSR & 0xF8) != TW_START){ //check to see if start signal was succesfully sent	
		debug("Error: i2c.c in i2cStart(): Start signal not successfully sent..."); 
		return 0; 
	}
	
	
	//now, send the device address...
	TWDR = address;
	TWCR = (1<<TWINT) | (1<<TWEN); // clear the two bits to start sending
	
	while(!(TWCR & (1<<TWINT))); // wait untill the data has been sent AND acknowledged, we know it when TWINT is set

	if ((TWSR & 0xF8)!=TW_MT_SLA_ACK){// make sure the device recieved the address
		debug("Error: i2c.c in i2cStart(): Device did not recieve address...");
		return 0;
	}
	usartsend("\n\rStarted\n\r");
	return 1;
	
}	


void i2cStop(void)
{
    // send stop signal
	TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);
	
	while(TWCR & (1<<TWSTO)); //wait until it does

}

int i2cSend(char data){

	TWDR = data; // put data in TWDR
	TWCR = (1<<TWINT) | (1<<TWEN); // clear the bits to send the data

	// wait until data has been sent
	while(!(TWCR & (1<<TWINT)));

	// check value of TWI Status Register. Mask prescaler bits
	
	if( (TWSR & 0xF8) != TW_MT_DATA_ACK){
		debug("Error: i2c.c in i2cSend(): Device did not recieve data...");
		return 0;
	}
	
	return 1;
debug("Success"); 
}

char i2cRecieve(int ack){
	if(ack){ // if we want more data sent after this... "ACK"
		TWCR = (1<<TWEN) | (1<<TWINT)  | (1<<TWEA); // 1. enable Two wire interface t 2. clear TWDR 3. make the device a slave reciever
	
		while(!(TWCR & (1<<TWINT)));    // wait untill we recieve something...
		
		return TWDR; //return the data
	}
	else{// otherwise, tell the device to end after giving us something.. "NO ACK"
	
	
		TWCR = (1<<TWINT) | (1<<TWEN); //note that TWEA is not set
		// wait..
		while(!(TWCR & (1<<TWINT)));
		return TWDR; // got it...
	}


}