mostafa_wahba
Newbie level 5
I'm working on a project on Atmega16
and i send data throw I2C from slave to master and the problem here is that the slave receive the address and don't send the data to the master
i want to know the error in the code
the code of the master
the code of the slave
and i send data throw I2C from slave to master and the problem here is that the slave receive the address and don't send the data to the master
i want to know the error in the code
the code of the master
Code:
#include <avr/io.h>
#include <util/delay.h>
#include <compat/twi.h>
#define MAX_TRIES 50
#define I2C_START 0
#define I2C_DATA 1
#define I2C_DATA_ACK 2
#define I2C_STOP 3
#define ACK 1
#define NACK 0
/* START I2C Routine */
unsigned char i2c_transmit(unsigned char type) {
switch(type) {
case I2C_START: // Send Start Condition
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
//TWSR=0x08;
break;
case I2C_DATA: // Send Data with No-Acknowledge
TWCR = (1 << TWINT) | (1 << TWEN);
break;
case I2C_DATA_ACK: // Send Data with Acknowledge
TWCR = (1 << TWEA) | (1 << TWINT) | (1 << TWEN);
break;
case I2C_STOP: // Send Stop Condition
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
return 0;
}
while (!(TWCR & (1 << TWINT)));
return (TWSR & 0xF8);
}
char i2c_start( unsigned char dev_addr, unsigned char rw_type)
{
unsigned char n = 0;
unsigned char twi_status;
char r_val = -1;
twi_status=i2c_transmit(I2C_START);
TWDR=(dev_addr| rw_type);
twi_status=i2c_transmit(I2C_DATA_ACK);
// Check the TWSR status
if ((twi_status == TW_MT_SLA_NACK) || (twi_status == TW_MT_ARB_LOST)) goto i2c_retry;
if (twi_status != TW_MT_SLA_ACK) goto i2c_quit;
r_val=0;
i2c_quit:
return r_val;
}
void i2c_stop(void)
{
unsigned char twi_status;
// Transmit I2C Data
twi_status=i2c_transmit(I2C_STOP);
}
char i2c_write(char data)
{
unsigned char twi_status;
char r_val = -1;
// Send the Data to I2C Bus
TWDR = data;
// Transmit I2C Data
twi_status=i2c_transmit(I2C_DATA);
// Check the TWSR status
if (twi_status != TW_MT_DATA_ACK) goto i2c_quit;
r_val=0;
i2c_quit:
return r_val;
}
char i2c_read()/////////////////////////read
{
if(TWSR==0x40)
{
TWCR=0b10000100;
unsigned char twi_status;
char data;
data=TWDR;
i2c_quit:
return data;
}
}
void i2c_init(void)
{
// Initial
TWSR = 0x00;
TWBR = 0x30;
}
int main(void)
{
i2c_init();
i2c_start( 0x21 , 0x01);//start by sending add & r/w bit
char x=i2c_read( );
DDRD=0xff;
PORTD=x;
i2c_stop();
return 0;
}
Code:
#include <avr/io.h>
#include <util/delay.h>
#include <compat/twi.h>
#include <avr/interrupt.h>
char i2c_slave_receiveadd()
{char addr;
TWCR=0b01000100;
addr=TWDR;
return addr;
}
//------------------------------
void i2c_slave_action()
{
char data=0x64;
char addr;
if(addr==0x21)
{
TWDR=data;
}
}
int main()
{
TWAR=0x21;
char x= i2c_slave_receiveadd();
DDRD=0xff;
PORTD=x;
i2c_slave_action();
return 0;
}