Hi.
I have to work with attiny20 and LIS3DH. Since attiny20 doesn't support Wire.h, I am trying to set up the communication without Wire.h in atmel studio 7.0.
I came up with following code and have modified it according to my purpose but it doesn't seem to work.
0x18 - device address
0x38 - register address
0x15 - value to be written
------------------------------------------- i2c.h --------------------------------------------------------
/* Header File for I2C */
#include <avr/io.h> //--- Reg file of ATmega16
#define F_CPU 8000000UL //--- CPU Clock Frequency
//--- I2C Initialize ---//
void i2c_init()
{
TWBR = 0x20; //--- Baud rate is set by calculating the of TWBR see Details for Reference
TWCR = (1<<TWEN); //--- Enable I2C
TWSR = 0x00; //--- Prescaler set to 1
}
//--- I2C Start Condition ---//
void i2c_start()
{
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTA); //--- Start Conditon
while (!(TWCR & (1<<TWINT))); //--- Check for Start condition successful
}
//--- I2C Stop Condition ---//
void i2c_stop()
{
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); //--- Stop Conditon
while (!(TWCR & (1<<TWINT))); //--- Check for Start condition successful
}
void i2c_write(char x)
{
TWDR = x; //--- Move value to I2C reg
TWCR = (1<<TWINT) | (1<<TWEN); //--- Enable I2C and Clear Interrupt
while (!(TWCR & (1<<TWINT))); //--- Write Successful with TWDR Empty
}
//--- I2C Read Condition ---//
uint8_t i2c_read()
{
TWCR = (1<<TWEN) | (1<<TWINT); //--- Enable I2C and Clear Interrupt
while (!(TWCR & (1<<TWINT))); //--- Read successful with all data received in TWDR
return TWDR;
}
//--- End of Header ---//
------------------------------------- main.c --------------------------------------------------------------
/*
- i2c_ioexpander.c
- Created: 12/11/2017 2:10:55 PM
- Author : Ayush
*/
#include <avr/io.h> //--- Reg file of Atmega16
#include "i2c.h" //--- Header file for i2c which we created
#include <util/delay.h> //--- Delay Header
#include <stdio.h>
int main(void)
{
DDRB = 0xFF; //--- PORTB as OUTPUT
PORTB = 0xFF;
i2c_init(); //--- Initiate I2C comm
i2c_start(); //--- Start Condition to Slave device
i2c_write(0x18); //--- Write address of Slave into I2C to select slave
while(1)
{
i2c_write(0x38); //--- Write data to IO Expander
_delay_ms(1000); //--- 1sec Delay
i2c_write(0x15); //--- Write data to IO Expander
_delay_ms(1000); //--- 1sec Delay
}
}