imx6u 使用 ADS1115 读取电压值的代码示例

本文将介绍如何在 imx6u 上使用 ADS1115 传感器读取电压值。

1. 加载 i2c-dev 驱动程序

首先,需要加载 i2c-dev 驱动程序以使用 i2c 总线通信。可以使用以下命令加载驱动程序:

sudo modprobe i2c-dev

2. 访问 i2c 总线

在程序中使用 i2c-dev 驱动程序访问 i2c 总线,以读取 ADS1115 芯片的电压值。需要使用以下代码打开 i2c 总线设备节点:

int fd;
char *filename = "/dev/i2c-1";    // i2c 总线设备节点
int addr = 0x48;                  // ads1115 芯片 i2c 地址
fd = open(filename, O_RDWR);
if (fd < 0) {
    perror("Failed to open i2c device");
    return -1;
}
if (ioctl(fd, I2C_SLAVE, addr) < 0) {
    perror("Failed to set i2c slave address");
    close(fd);
    return -1;
}

3. 设置 ADS1115 配置寄存器

接下来,需要设置 ADS1115 芯片的配置寄存器,以选择输入通道和增益,以及启用单次转换模式。可以使用以下代码设置配置寄存器:

uint16_t config = 0x8583;   // AIN0/AIN1,增益为 2,单次转换模式
uint8_t buf[3];
buf[0] = 0x01;              // 配置寄存器地址
buf[1] = config >> 8;       // 配置寄存器高字节
buf[2] = config & 0xFF;     // 配置寄存器低字节
if (write(fd, buf, 3) != 3) {
    perror("Failed to write config register");
    close(fd);
    return -1;
}

4. 读取 ADS1115 数据寄存器

最后,需要读取 ADS1115 芯片的数据寄存器,以获取电压值。可以使用以下代码读取数据寄存器:

buf[0] = 0x00;  // 数据寄存器地址
if (write(fd, buf, 1) != 1) {
    perror("Failed to set data register address");
    close(fd);
    return -1;
}
if (read(fd, buf, 2) != 2) {
    perror("Failed to read data register");
    close(fd);
    return -1;
}
int16_t value = (buf[0] << 8) | buf[1];    // 将两个字节的数据合并为一个有符号整数
float voltage = value * 0.0001875;          // 根据增益计算电压值
printf("Voltage: %f V\n", voltage);

完整代码

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#include <stdint.h>

int main()
{
    int fd;
    char *filename = "/dev/i2c-1";
    int addr = 0x48;
    fd = open(filename, O_RDWR);
    if (fd < 0) {
        perror("Failed to open i2c device");
        return -1;
    }
    if (ioctl(fd, I2C_SLAVE, addr) < 0) {
        perror("Failed to set i2c slave address");
        close(fd);
        return -1;
    }

    uint16_t config = 0x8583;   // AIN0/AIN1,增益为 2,单次转换模式
    uint8_t buf[3];
    buf[0] = 0x01;
    buf[1] = config >> 8;
    buf[2] = config & 0xFF;
    if (write(fd, buf, 3) != 3) {
        perror("Failed to write config register");
        close(fd);
        return -1;
    }

    buf[0] = 0x00;
    if (write(fd, buf, 1) != 1) {
        perror("Failed to set data register address");
        close(fd);
        return -1;
    }
    if (read(fd, buf, 2) != 2) {
        perror("Failed to read data register");
        close(fd);
        return -1;
    }
    int16_t value = (buf[0] << 8) | buf[1];
    float voltage = value * 0.0001875;
    printf("Voltage: %f V\n", voltage);

    close(fd);
    return 0;
}
imx6u 使用 ADS1115 读取电压值的代码示例

原文地址: https://www.cveoy.top/t/topic/nnpg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录