I have connected MCP23017 to dsPIC33EP512MU810. I can write on it but I have a problem in reading. the chip can be read in first instant that I connect the circuit to a power supply (about 1s) then after the MCU reads only zeros.
The written program is as below:
Code: Select all
//-----------------------I/O Direction Registers(TRIS)--------------------------
#define IODIRA 0x00
#define IODIRB 0x01
//-----------------------General Purpose I/O------------------------------------
#define GPIOA 0x12 //Reading the GPIOn register reads the value on the port.
#define GPIOB 0x13
//-----------------------Output Latches-----------------------------------------
#define OLATA 0x14 //Writing to the OLATn register Writes to the associated port.
#define OLATB 0x15
//-----------------------W/R Control bytes--------------------------------------
#define WRITE 0x40 // 0b0100 + 0b000(Slave address) + 0b0(Write) => 0x40
#define READ 0x41
char DD, DATT;
void EXPANDER_write(char portAddr, char dat)
{
I2C2_start();
//while(I2C2_Is_Idle()); //Wait for previous operations to cease.
I2C2_write(WRITE);
I2C2_write(portAddr);
I2C2_write(dat);
I2C2_stop();
}
//------------------------------------------------------------------------------
char EXPANDER_read(char portAddr){
char dat;
I2C2_start();
// while(I2C2_Is_Idle());
I2C2_write(WRITE);
I2C2_write(portAddr);
I2C2_Restart();
I2C2_write(READ);
dat = I2C2_Read(1u);
I2C2_stop();
return dat;}
void EXPANDER_init(char portA, char portB)
{
EXPANDER_write(IODIRA,portA);
EXPANDER_write(IODIRB,portB);
}
void main() {
OSCCON=0x33E0;
CLKDIV=0x0006; //PLL's Divider Configuration (divided by CLKDIV<4:0>+2)
PLLFBD=278; //PLL's Feedback Congiguration (multiply by PLLFBD+2)
//OSCTUN=0;
//REFOCON=0;
ACLKCON3=0xE4A0; //Axuliary OSC PLL Configuration 0x00F0 post divider; 0x000F prescale
ACLKDIV3=7;
TRISF=0x0000;
LATF=0x0000;
LATF.b3=1; //RESET bit
I2C2_init(100000); //Give speed in KBps
EXPANDER_init(0x00,0xFF); //PortA all Outputs, PortB all Inputs.
while(1) {
DATT=EXPANDER_read(GPIOB);
// EXPANDER_write(OLATB, 0xFF); //(writing works fine)
DD=DATT+1;
EXPANDER_write(OLATA, DD);
delay_ms(1000);
}}
Regards,