View previous topic :: View next topic |
Author |
Message |
hemnath
Joined: 03 Oct 2012 Posts: 242 Location: chennai
|
mcp3422 |
Posted: Thu May 23, 2019 2:49 am |
|
|
18F2520, Internal oscillator 4Mhz, CCS 4.114
Below code is not working for MCP3422
Code: |
int16 get_adc()
{
INT16 upper, lower, config;
i2c_start ();
i2c_write (0xD0);
i2c_write (0x88);
i2c_stop();
i2c_start ();
i2c_write (0xD1);
upper = i2c_read (1); // read slave data
lower = i2c_read (1); // read slave data
config = i2c_read (0); // read slave data
i2c_stop ();
sensor1 =( upper * 256) + lower;
i2c_start ();
i2c_write (0xD0);
i2c_write (0xA8);
i2c_stop();
i2c_start ();
i2c_write (0xD1);
upper = i2c_read (1); // read slave data
lower = i2c_read (1); // read slave data
config = i2c_read (1); // read slave data
i2c_stop ();
sensor2 =( upper * 256) + lower;
} |
|
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
Re: mcp3422 |
Posted: Thu May 23, 2019 3:06 am |
|
|
hemnath wrote: |
int16 get_adc()
{
INT16 upper, lower, config;
i2c_start ();
i2c_write (0xD1);
upper = i2c_read (1); // read slave data
lower = i2c_read (1); // read slave data
config = i2c_read (1); // read slave data
i2c_stop ();
sensor2 =( upper * 256) + lower;
} |
Bug. The last i2c_read() should have a 0 parameter. |
|
|
hemnath
Joined: 03 Oct 2012 Posts: 242 Location: chennai
|
|
Posted: Thu May 23, 2019 3:31 am |
|
|
Thanks. I changed it 0. Sensor1 and sensor2 values are same.
Then, i have added a line delay_ms(100) in between sensor1 =( upper * 256) + lower; and i2c_start(); It is working now. Why is it so? |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19520
|
|
Posted: Thu May 23, 2019 4:04 am |
|
|
You are sending command 0x88 to the device, and then immediately reading.
The chip takes _time_ to do a conversion. You need to either poll
the RDY flag to see that it has finished, or wait long enough for the
conversion to have completed before starting your data read.
You are selecting the 15SPS mode, so a conversion will take 67mSec to
complete. So add a delay_ms(67), after the I2C_STOP for the command,
and the I2C_READ for the data. |
|
|
|