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的原始值
相关推荐
qq_5896660516 小时前
C语言、C++与C#的区别详解
c语言·c++·c#
昌原的儿子LEO19 小时前
Linux进程知识点总结
linux·服务器·c语言·数据库
多弗朗皮卡丘1 天前
C语言梦开始的地方16:结构体
c语言·开发语言·windows
2401_862880821 天前
Linux应用层开发 --- 多任务
linux·服务器·c语言
心仪久了会沦陷1 天前
数据结构入门系列——顺序表详解:概念、分类与动态实现
c语言·数据结构·经验分享·笔记·开源
witton1 天前
xmake中将proto文件生成C/C++文件然后再编译链接进项目
c语言·c++·mingw·protobuf·xmake·protobuf-c·protoc-gen-c
dear_bi_MyOnly1 天前
C语言控制语句与循环逻辑精讲
c语言·开发语言·学习·分类
M78佐菲1 天前
c语言学习笔记:排序与查找方法整理
linux·c语言·笔记·学习·算法
wWYy.1 天前
C++与C的区别
c语言·c++
LuminousCPP1 天前
数据结构‑二叉树(二):二叉堆从零实现|Heap结构设计 + 建堆优化 + 堆排序深度解析
c语言·数据结构·笔记·二叉树