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的原始值
相关推荐
.千余9 小时前
【C++】C++类与对象2:C++构造函数、运算符重载与流输入输出全面解析
c语言·开发语言·前端·c++·经验分享
QiLinkOS10 小时前
【用呼吸重构创造价值关系——QiLink生态】
c语言·数据结构·c++·人工智能·单片机·嵌入式硬件·算法
水无痕simon10 小时前
8 判断,分支,循环语句
c语言
朔北之忘 Clancy11 小时前
2026 年 3 月青少年软编等考 C 语言二级真题解析
c语言·开发语言·c++·学习·青少年编程·题解·考级
万法若空11 小时前
Libevent C语言开发完全教程:从入门到实战
c语言·网络
kkeeper~12 小时前
0基础C语言积跬步之自定义类型结构体
c语言·开发语言
小何code14 小时前
C语言【初阶】第1节,初识C语言
c语言·开发语言
莫陌尛.14 小时前
Fuzzy C-Mean Clustering (FCM)
c语言·开发语言
飞天狗11115 小时前
2025第十六届蓝桥杯c/c++B组国赛题解
c语言·c++·算法·蓝桥杯
mN9B2uk1716 小时前
MySQL命令行导出数据库
c语言·数据库·mysql