user_adc_read.c

程序

复制代码
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#define SYSFS_IIO_PATH "/sys/bus/iio/devices/iio:device0"

int read_adc_raw(int channel)
{
    char path[256];
    char buf[32];
    int fd, ret;
    int value;

    // 构造路径,例如 /sys/bus/iio/devices/iio:device0/in_voltage0_raw
    snprintf(path, sizeof(path), "%s/in_voltage%d_raw", SYSFS_IIO_PATH, channel);

    fd = open(path, O_RDONLY);
    if (fd < 0) {
        fprintf(stderr, "Failed to open %s: %s\n", path, strerror(errno));
        return -1;
    }

    ret = read(fd, buf, sizeof(buf) - 1);
    if (ret < 0) {
        fprintf(stderr, "Failed to read %s: %s\n", path, strerror(errno));
        close(fd);
        return -1;
    }
    buf[ret] = '\0';
    close(fd);

    value = atoi(buf);
    return value;
}

int main(int argc, char *argv[])
{
    int channel = 0;  // 默认通道0
    int raw_value;

    if (argc > 1)
        channel = atoi(argv[1]);

    raw_value = read_adc_raw(channel);
    if (raw_value < 0) {
        fprintf(stderr, "Read ADC channel %d failed\n", channel);
        return 1;
    }

    printf("ADC channel %d raw value: %d\n", channel, raw_value);
    return 0;
}

编译与运行

复制代码
gcc -o user_adc_read user_adc_read.c
./user_adc_read 0      # 读取通道0的原始值
相关推荐
戊本菌12 小时前
进程(三)进程优先级:谁先上 CPU
linux·c语言·硬件架构
嵌入式 Linux手记15 小时前
一块内存,三种解释:union 的真实用法
linux·c语言·驱动开发·嵌入式
H.莓飛1 天前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
Zwawa2 天前
卡尔曼到底在算什么:从一维到它的变式以及工程版卡尔曼滤波算法C语言实现
c语言·算法·嵌入式
Hhy_11072 天前
《C++深度解构07》手撕 vector —— 从底层三指针架构到迭代器失效彻底吃透
c语言·开发语言·c++·学习·visual studio
风落青芜2 天前
链式二叉树的实现与基本操作
c语言·开发语言·数据结构·算法
风落青芜3 天前
数据结构:堆的概念与实现
c语言·开发语言·数据结构·算法
老花眼猫4 天前
C语言绘图方法:(10)椭圆缩放旋转
c语言·经验分享·青少年编程·课程设计
Zwawa5 天前
陀螺仪数据为什么看起来总在动:零偏、噪声和零漂
c语言·单片机·嵌入式
soso19685 天前
低功耗设计与BMS开发指南
c语言·开发语言·汇编