younder
Joined: 24 Jan 2013 Posts: 53 Location: Brazil
|
AM2320 I2C Relative Humidity & Temperature by Hugo Silva |
Posted: Mon Aug 08, 2016 6:19 pm |
|
|
Hi guys,
I'm Just sharing this driver for anyone that needs it...
Enjoy!
Hugo
AM2320.h
Code: |
////////////////////////////////////////////////////////////////////////////////
/// AM2320.h ///
/// AM2320 I2C Relative Humidity and Temperature Sensor Driver ///
/// ///
// Date: Aug-2015 ///
// Ver.: 1.0 ///
// Author: Hugo Silva ([email protected]) ///
// ///
////////////////////////////////////////////////////////////////////////////////
#define AM2320_address 0xB8
#define I2C_write_cmd 0x00
#define I2C_read_cmd 0x01
#define Read_Fct_Code 0x03
#define Start_address 0x00
#define Nr_of_Registers 0x04
const unsigned char read_cmd[3]={Read_Fct_Code,Start_address,Nr_of_Registers};
unsigned char Sensor_data_buffer[8],s;
void AM2320_init() {
for(s = 0; s< 8; s++) Sensor_data_buffer[s] = 0x00;
}
void Step_1_Wake_Sensor()
{
I2C_Start();
I2C_Write(AM2320_address| I2C_write_cmd);
delay_us(800);
I2C_Stop();
}
void Step_2_Send_Read_Cmd()
{
I2C_Start();
I2C_Write(AM2320_address | I2C_write_cmd);
for (s=0; s<(sizeof(read_cmd)); s++) I2C_Write(read_cmd[s]);
I2C_Stop();
}
void Step_3_Receive_Sensor_Data()
{
I2C_Start();
I2C_Write(AM2320_address | I2C_read_cmd);
delay_us(30);
for (s=0; s<(sizeof(Sensor_data_buffer)-1); s++) Sensor_data_buffer[s] = I2C_read(1); //data = i2c_read(ack); ack - Optional, defaults to 1. ->1 indicates to ack.
Sensor_data_buffer[(sizeof(Sensor_data_buffer)-1)]=I2C_read(0);
I2C_Stop();
}
void Get_Sensor_Data()
{
Step_1_Wake_Sensor();
Step_2_Send_Read_Cmd();
delay_us(1500);
Step_3_Receive_Sensor_Data();
}
unsigned int16 get_RH () {
static unsigned int16 RH;
RH = ((unsigned int16)((Sensor_data_buffer[2] << 8) | Sensor_data_buffer[3]));
return RH;
}
signed int16 get_Temperature () {
static signed int16 Temperature;
Temperature = ((signed int16)((Sensor_data_buffer[4] << 8) | Sensor_data_buffer[5]));
return Temperature;
}
unsigned int16 get_CRC() {
static unsigned int16 CRC_data;
CRC_data = ((unsigned int16)((Sensor_data_buffer[7] << 8) | Sensor_data_buffer[6]));
return CRC_data;
}
unsigned int16 CRC16(unsigned char *ptr, unsigned char length)
{
unsigned int16 crc = 0xFFFF;
unsigned char s = 0x00;
while(length--)
{
crc ^= *ptr++;
for(s = 0; s < 8; s++)
{
if((crc & 0x01) != 0)
{
crc >>= 1;
crc ^= 0xA001;
}
else
{
crc >>= 1;
}
}
}
return crc;
}
|
AM2320.c
Code: |
#include <30F4012.h>
#device ADC=10
#use delay(Internal=117964800)
#use i2c(MASTER, SCL=PIN_E5, SDA=PIN_E4, FAST, FORCE_SW) //Software selectable I2C
#fuses FRC_PLL16,NOPROTECT,NOWRT,MCLR,PUT64,NOCKSFSM,BORV27,NODEBUG,NOWDT
#include <AM2320.h>
Signed int16 Air_Temperature=0;
Unsigned int16 Relative_Humidity=0;
void Main() {
// Initialize Temperature & RH Sensor data
AM2320_init();
while(1) {
Get_Sensor_Data();
Air_Temperature=get_temperature();
Relative_Humidity=get_RH();
}
|
_________________ Hugo Silva |
|