//i2c_ads1115.c #include "i2c_ads1115.h" #include #include "i2c.h" #include "main.h" #include "elog.h" /* * ads1115_get_voltage_val( hi2c1, 0x00, CONFIG_REG_H, CONFIG_REG_L ) */ extern I2C_HandleTypeDef hi2c1; #define ADS1115_hi2c hi2c1 int ads1115_test(I2C_HandleTypeDef ads1115_I2cHandle) { ads1115_config_register(ads1115_I2cHandle, 0x00, CONFIG_REG_H, CONFIG_REG_L); return 0; } /** * @brief * @param [in] ads1115_I2cHandle * @param [in] pointADD -- 0x01 写配置寄存器 * @param [in] configH * @param [in] configL * * @details */ void ads1115_config_register(I2C_HandleTypeDef ads1115_I2cHandle,uint8_t pointADD,uint8_t configH,uint8_t configL) { uint8_t reg_data[3]={pointADD,configH,configL}; while(HAL_I2C_Master_Transmit(&ads1115_I2cHandle, ADS1115_WRITE_ADDRESS, reg_data, 3, 2000) != HAL_OK) { if(HAL_I2C_GetError(&ads1115_I2cHandle) != HAL_I2C_ERROR_AF) { log_i("ads1115 Config Register error!!!\r\n"); } } } int16_t ads1115_read_data(I2C_HandleTypeDef ads1115_I2cHandle) { int16_t data; uint8_t rx_data[2]={0}; while(HAL_I2C_Master_Transmit(&ads1115_I2cHandle, ADS1115_WRITE_ADDRESS, 0x00, 1, 2000) != HAL_OK) { if(HAL_I2C_GetError(&ads1115_I2cHandle) != HAL_I2C_ERROR_AF) { log_i("ads1115 convert Register error!!!\r\n"); } } while(HAL_I2C_Master_Receive(&ads1115_I2cHandle, ADS1115_READ_ADDRESS, rx_data, 2, 2000) != HAL_OK) { if(HAL_I2C_GetError(&ads1115_I2cHandle) != HAL_I2C_ERROR_AF) { log_i("ads1115 read data error!!!\r\n"); } } data = rx_data[0]*256 + rx_data[1]; return data; } double ads1115_get_voltage_val( I2C_HandleTypeDef ads1115_I2cHandle, uint8_t pointADD, uint8_t configH, uint8_t configL) { double val; int16_t ad_val; double coeff_mv = 1000.0; /* 输出 毫伏*/ double coeff_v = 1000000.0; /* 输出 伏*/ ads1115_config_register( ads1115_I2cHandle, pointADD, configH, configL ); // HAL_Delay(10); osDelay(10); ad_val=ads1115_read_data( ads1115_I2cHandle ); if( (ad_val==0x7FFF)|(ad_val==0X8000) )//是否超量程了 { ad_val=0; log_i("over PGA\r\n"); } switch( ( 0x0E&configH )>>1 )//量程对应的分辨率 { case(0x00): val=(double)ad_val*187.5/coeff_mv;// break; case(0x01): val=(double)ad_val*125/coeff_mv; break; case(0x02): val=(double)ad_val*62.5/coeff_mv; break; case(0x03): val=(double)ad_val*31.25/coeff_mv; break; case(0x04): val=(double)ad_val*15.625/coeff_mv; break; case(0x05): val=(double)ad_val*7.8125/coeff_mv; break; } return val; }