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的原始值
相关推荐
openKylin3 小时前
与全球技术演进同频,openKylin 3.0从C迈向Rust
c语言·开发语言·rust·开源·开放原子·openkylin
迷茫、Peanut4 小时前
C语言sizeof和strlen
c语言
Bug退散师8 小时前
多路IO复用[select版TCP服务器与poll版TCP服务器]与常用网络编程函数详解
linux·服务器·c语言·网络·驱动开发·tcp/ip
天空'之城8 小时前
C 语言工业级通用组件手写 03:双向链表
c语言·嵌入式开发·双向链表
FREEDOM_X9 小时前
嵌入式——定时器工作原理
linux·c语言·单片机·嵌入式硬件·ubuntu
2401_827501289 小时前
51单片机(四)DS18B20 数字温度传感器
c语言·51单片机
不会c+11 小时前
C语言:入门到精通(408考研版)系列七 派生的数据类型
c语言·开发语言
躺不平的理查德11 小时前
SQLite C API 备忘录
c语言·数据库·sqlite
程序猿编码12 小时前
没有AI框架,没有GPU,一个C语言文件跑通大模型
c语言·开发语言·人工智能·深度学习·ai·大模型
CHANG_THE_WORLD12 小时前
Linux C 多线程 TCP 并发服务器:从 `accept()` 到资源管理深度剖析
linux·服务器·c语言