Hi,
i'am trayng to make an i2c communication betwen an arduino due and an slave device. My goal is to send some data to slave device first. Until now no luck. I realy aprecite some help if is possible. Below is my code, but does not work.
Is this the right way?? is the clock set corectly?
// I2C test communication with due
// TWI reg
WoReg TWI_CR;
RoReg TWI_RHR;
RwReg TWI_CWGR;
RwReg TWI_MMR;
RwReg TWI_IADR;
WoReg TWI_THR;
#define INTERNAL_I2C_PULLUPS 1
int addr = 0x29;
int reg = 0x00;
int sensorPin = A0;
int sensorValue = 0;
void setup()
{
// Start I2C Bus as Master
i2c_init();
}
void loop()
{
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
int outputValue = map(sensorValue, 0, 1023, 0, 255);
i2c_write(outputValue);
i2c_stop();
}
// ************************
// I2C general functions
// ************************
void i2c_init(void) {
#if defined(INTERNAL_I2C_PULLUPS)
PIOB->PIO_PUER = PIO_PB12;
PIOB->PIO_PUER = PIO_PB13;
#else
PIOB->PIO_PUDR = PIO_PB12;
PIOB->PIO_PUDR = PIO_PB13;
#endif
pmc_enable_periph_clk(WIRE1_INTERFACE_ID);
PIO_Configure(
g_APinDescription[PIN_WIRE_SDA].pPort,
g_APinDescription[PIN_WIRE_SDA].ulPinType,
g_APinDescription[PIN_WIRE_SDA].ulPin,
g_APinDescription[PIN_WIRE_SDA].ulPinConfiguration);
PIO_Configure(
g_APinDescription[PIN_WIRE_SCL].pPort,
g_APinDescription[PIN_WIRE_SCL].ulPinType,
g_APinDescription[PIN_WIRE_SCL].ulPin,
g_APinDescription[PIN_WIRE_SCL].ulPinConfiguration);
NVIC_DisableIRQ(WIRE_ISR_ID);
NVIC_ClearPendingIRQ(WIRE_ISR_ID);
NVIC_SetPriority(WIRE_ISR_ID, 0);
NVIC_EnableIRQ(WIRE_ISR_ID);
/* Configure clock /
unsigned int cldiv,ckdiv=1 ;
while ( ( cldiv = ( (VARIANT_MCK/(2400000))-3 ) / pow(2,ckdiv)) > 255 )
ckdiv++ ;
TWI_CWGR = 0 ;
TWI_CWGR =(ckdiv<<16)|((unsigned int)cldiv << 8)|(unsigned int)cldiv ;
/* SVEN: TWI Slave Mode Enabled /
TWI_CR = (0x1u << 4);
/ Reset the TWI /
TWI_CR = (0x1u << 7);
/ TWI Slave Mode Disabled, TWI Master Mode Disabled. /
TWI_CR = (0x1u << 5);
TWI_CR = (0x1u << 3);
/ Set master mode */
TWI_CR = (0x1u << 2);
// set slave adress DADR
TWI_MMR = (addr << 16);
// internal adres size IADRSZ
TWI_IADR = (0x1u << 8);
// tranfer direction bit
TWI_MMR = (0x1u << 12);
// set the internal adres IADR
TWI_IADR = 0x00;
}
void i2c_stop(void) {
TWI_CR = (0x1u << 1) ;
}
void i2c_write(uint8_t data ) {
TWI_THR = data;
}