Wednesday, 29 October 2008

Temperatures in my appartment

Just got an I2C temperature sensor and I decided to connect it to my NintendoDS to measure the temperature for two whole days.

The two spikes on the left is the sun entering through two different windows and hitting the sensor directly. The other two spikes on the right is exactly the same thing but for the second day.

Thats it.

Tuesday, 14 October 2008

I2C on an AVR using bit banging

As a exercise I tried to talk to a I2C temperature sensor using bit banging, it was not as easy as I thought so I decided to post the code in case anyone needs to see the solution, if you happen to use my code drop me a line since that will encourage me to post more code :-)

```// Port for the I2C
#define I2C_DDR DDRD
#define I2C_PIN PIND
#define I2C_PORT PORTD

// Pins to be used in the bit banging
#define I2C_CLK 0
#define I2C_DAT 1

#define I2C_DATA_HI()\
I2C_DDR &= ~ (1 << I2C_DAT);\
I2C_PORT |= (1 << I2C_DAT);
#define I2C_DATA_LO()\
I2C_DDR |= (1 << I2C_DAT);\
I2C_PORT &= ~ (1 << I2C_DAT);

#define I2C_CLOCK_HI()\
I2C_DDR &= ~ (1 << I2C_CLK);\
I2C_PORT |= (1 << I2C_CLK);
#define I2C_CLOCK_LO()\
I2C_DDR |= (1 << I2C_CLK);\
I2C_PORT &= ~ (1 << I2C_CLK);

void I2C_WriteBit(unsigned char c)
{
if (c > 0)
{
I2C_DATA_HI();
}
else
{
I2C_DATA_LO();
}

I2C_CLOCK_HI();
delay(1);

I2C_CLOCK_LO();
delay(1);

if (c > 0)
{
I2C_DATA_LO();
}

delay(1);
}

{
I2C_DATA_HI();

I2C_CLOCK_HI();
delay(1);

unsigned char c = I2C_PIN;

I2C_CLOCK_LO();
delay(1);

return (c >> I2C_DAT) & 1;
}

// Inits bitbanging port, must be called before using the functions below
//
void I2C_Init()
{
I2C_PORT &= ~ ((1 << I2C_DAT) | (1 << I2C_CLK));

I2C_CLOCK_HI();
I2C_DATA_HI();

delay(1);
}

// Send a START Condition
//
void I2C_Start()
{
// set both to high at the same time
I2C_DDR &= ~ ((1 << I2C_DAT) | (1 << I2C_CLK));
delay(1);

I2C_DATA_LO();
delay(1);

I2C_CLOCK_LO();
delay(1);
}

// Send a STOP Condition
//
void I2C_Stop()
{
I2C_CLOCK_HI();
delay(1);

I2C_DATA_HI();
delay(1);
}

// write a byte to the I2C slave device
//
unsigned char I2C_Write(unsigned char c)
{
for (char i = 0; i < 8; i++)
{
I2C_WriteBit(c & 128);

c <<= 1;
}

return 0;
}

// read a byte from the I2C slave device
//
{
unsigned char res = 0;

for (char i = 0; i < 8; i++)
{
res <<= 1;
}

if (ack > 0)
{
I2C_WriteBit(0);
}
else
{
I2C_WriteBit(1);
}

delay(1);

return res;
}```