用stm32 配置ads1115 双通道采集电压
时间: 2023-08-24 08:09:49 浏览: 387
以下是使用STM32配置ADS1115双通道采集电压的步骤:
1. 确保ADS1115已正确连接到STM32的I2C总线上,并且STM32的I2C总线已正确配置。
2. 配置ADS1115的寄存器,使其工作在所需的采样率和增益下,以及配置通道选择。例如,要选择通道0和1进行单次连续采样,您可以将以下代码添加到初始化函数中:
```
// 设置采样率为860SPS,增益为2.048V,选择通道0和1
uint16_t config = ADS1115_REG_CONFIG_CQUE_NONE |
ADS1115_REG_CONFIG_CLAT_NONLAT |
ADS1115_REG_CONFIG_CPOL_ACTVLOW |
ADS1115_REG_CONFIG_CMODE_SINGLE |
ADS1115_REG_CONFIG_DR_860SPS |
ADS1115_REG_CONFIG_MODE_SINGLE |
ADS1115_REG_CONFIG_PGA_2_048V |
ADS1115_REG_CONFIG_MUX_DIFF_0_1;
// 将配置写入ADS1115的配置寄存器
HAL_I2C_Mem_Write(&hi2c1, ADS1115_ADDRESS, ADS1115_REG_POINTER_CONFIG, I2C_MEMADD_SIZE_8BIT, (uint8_t*)&config, 2, 100);
```
3. 启动一次单次连续采样,等待采样完成,并从ADS1115的数据寄存器读取采样结果。例如,您可以将以下代码添加到主循环中:
```
// 启动一次单次连续采样
uint16_t config = ADS1115_REG_CONFIG_CQUE_NONE |
ADS1115_REG_CONFIG_CLAT_NONLAT |
ADS1115_REG_CONFIG_CPOL_ACTVLOW |
ADS1115_REG_CONFIG_CMODE_SINGLE |
ADS1115_REG_CONFIG_DR_860SPS |
ADS1115_REG_CONFIG_MODE_SINGLE |
ADS1115_REG_CONFIG_PGA_2_048V |
ADS1115_REG_CONFIG_MUX_DIFF_0_1;
HAL_I2C_Mem_Write(&hi2c1, ADS1115_ADDRESS, ADS1115_REG_POINTER_CONFIG, I2C_MEMADD_SIZE_8BIT, (uint8_t*)&config, 2, 100);
// 等待采样完成
while(!(HAL_I2C_IsDeviceReady(&hi2c1, ADS1115_ADDRESS, 1, 100)));
// 从ADS1115的数据寄存器读取采样结果
uint8_t data[2];
HAL_I2C_Mem_Read(&hi2c1, ADS1115_ADDRESS, ADS1115_REG_POINTER_CONVERT, I2C_MEMADD_SIZE_8BIT, data, 2, 100);
// 将数据转换为电压值
int16_t result = (int16_t)((data[0] << 8) | data[1]);
float voltage = (float)result * 2.048 / 32767.0;
```
4. 如有需要,您可以重复步骤3以获取另一个通道的采样结果。例如,要选择通道2和3进行单次连续采样,您可以将以下代码添加到主循环中:
```
// 启动一次单次连续采样
uint16_t config = ADS1115_REG_CONFIG_CQUE_NONE |
ADS1115_REG_CONFIG_CLAT_NONLAT |
ADS1115_REG_CONFIG_CPOL_ACTVLOW |
ADS1115_REG_CONFIG_CMODE_SINGLE |
ADS1115_REG_CONFIG_DR_860SPS |
ADS1115_REG_CONFIG_MODE_SINGLE |
ADS1115_REG_CONFIG_PGA_2_048V |
ADS1115_REG_CONFIG_MUX_DIFF_2_3;
HAL_I2C_Mem_Write(&hi2c1, ADS1115_ADDRESS, ADS1115_REG_POINTER_CONFIG, I2C_MEMADD_SIZE_8BIT, (uint8_t*)&config, 2, 100);
// 等待采样完成
while(!(HAL_I2C_IsDeviceReady(&hi2c1, ADS1115_ADDRESS, 1, 100)));
// 从ADS1115的数据寄存器读取采样结果
uint8_t data[2];
HAL_I2C_Mem_Read(&hi2c1, ADS1115_ADDRESS, ADS1115_REG_POINTER_CONVERT, I2C_MEMADD_SIZE_8BIT, data, 2, 100);
// 将数据转换为电压值
int16_t result = (int16_t)((data[0] << 8) | data[1]);
float voltage = (float)result * 2.048 / 32767.0;
```
阅读全文