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的原始值
相关推荐
听风说ml8 小时前
socket编程 【C语言】
c语言·udp·tcp·socket编程
学逆向的9 小时前
C 局部静态变量
c语言·开发语言·网络安全
Zwawa16 小时前
从 printf 到曲线:把数据送上 VOFA+
c语言·单片机·嵌入式
二十七日秋20 小时前
算法刷题笔记「Day 1|四道 OJ 入门题里的深坑」
c语言·汇编·数据结构·c++·笔记·python·算法
abc light20 小时前
ARM 裸机开发(1)——ARM 体系结构
c语言·arm开发
Navigator_Z21 小时前
LeetCode //C - 1309. Decrypt String from Alphabet to Integer Mapping
c语言·算法·leetcode
爱聊灵光的维C21 小时前
C语言初阶:关于函数设计的详细讲解和注意事项
c语言·开发语言·青少年编程·蓝桥杯·学习方法
wuminyu1 天前
JVM规范学习总结:class执行性能差异
java·linux·c语言·jvm·c++
C++ 老炮儿的技术栈1 天前
Linux 动态库踩坑:明明重新编译了 .so,调用函数返回值却一直不变(libfjrobot.so 版本号异常排查实录)
linux·c语言·网络·c++·visual studio
小向是个Der1 天前
嵌入式进阶——MCU上电后的动作
c语言·单片机·mcu·学习·链接脚本