View previous topic :: View next topic |
Author |
Message |
-Terppa-
Joined: 08 Jan 2018 Posts: 59 Location: Finland
|
MCP9800 setup [SOLVED] |
Posted: Fri Jan 31, 2020 3:34 am |
|
|
Hello for everyone!
I have small question about MCP9800 temperature sensor which is very similar to LM75.
I try to set that sensor higher resolution but i always get only 0.5c resolution.
MCP9800 init:
Code: |
i2c_start(I2CTEMPSENSOR);
i2c_write(I2CTEMPSENSOR,mcp9800_i2c_write);
i2c_write(I2CTEMPSENSOR,MCP9800_CONFIG_REG_ADDR); //0x01
i2c_write(I2CTEMPSENSOR,0b01100000);
i2c_stop();
|
MCP9800 read temperature (test code)
Code: |
signed long datah, datal;
signed long data;
i2c_start();
i2c_write(mcp9800_i2c_write);
i2c_write(MCP9800_TEMP_REG_ADDR); //0x00
i2c_start();
i2c_write(mcp9800_i2c_write+1);
datah=i2c_read();
datal=i2c_read(0);
i2c_stop();
data=(signed long)datah*10;
if(bit_test(datal,7))
{
if(data<0)data-=5;
else data+=5;
}
//fahrenheit:
data=(data)*90;
data=(data/50)+320;
//celcius:
data*=10;
data=(data-3200)/18;
|
What silly mistake i have here? Thank you very much for your help!
Last edited by -Terppa- on Tue Feb 11, 2020 6:39 am; edited 1 time in total |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19540
|
|
Posted: Fri Jan 31, 2020 4:50 am |
|
|
Problem is your conversion code is only using the top bit of the datal
return, so any extra resolution is lost....
Code: |
union {
signed int16 data;
unsigned int8 bytes[2];
} value;
i2c_start();
i2c_write(mcp9800_i2c_write);
i2c_write(MCP9800_TEMP_REG_ADDR); //0x00
i2c_start();
i2c_write(mcp9800_i2c_write+1);
value.bytes[1]=i2c_read();
value.bytes[0]=i2c_read(0);
i2c_stop();
value.data/=16;
|
value.data, is now the signed integer data, in 1/16th degree steps. |
|
|
-Terppa-
Joined: 08 Jan 2018 Posts: 59 Location: Finland
|
|
Posted: Fri Jan 31, 2020 8:47 am |
|
|
Thank you very much Mr.Ttelmah! I just not noticed it at all. |
|
|
-Terppa-
Joined: 08 Jan 2018 Posts: 59 Location: Finland
|
|
Posted: Thu Feb 04, 2021 4:23 am |
|
|
This seems works okay but if temperature gets negative i can get say: 6543.8?
and if temperature gets positive everything is okay..
How i tune this function?
Thank you for your help!
Code: |
signed long MCP9800_read_temp(void)
{
union
{
signed int16 data;
unsigned int8 bytes[2];
} value;
i2c_start();
i2c_write(mcp9800_i2c_write);
i2c_write(MCP9800_TEMP_REG_ADDR);
i2c_start();
i2c_write(mcp9800_i2c_write+1);
value.bytes[1]=i2c_read();
value.bytes[0]=i2c_read(0);
i2c_stop();
value.data/=16;
value.data*=10;
return value.data=(value.data-320)/18;
|
|
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19540
|
|
Posted: Thu Feb 04, 2021 4:37 am |
|
|
Use the union as I show. Casting does not carry the sign bit. |
|
|
-Terppa-
Joined: 08 Jan 2018 Posts: 59 Location: Finland
|
|
Posted: Thu Feb 04, 2021 5:27 am |
|
|
Thank you! It works. Too much haste here
I just put sensor outside and now it shows -17.3 Hmm.. very cold in here. |
|
|
|