[app]温度传感器测试程序

本文介绍了一种通过sys接口而非i2c-dev接口读取LM75温度传感器的方法。当直接使用i2c-dev接口遇到问题时,提供了一种可行的替代方案。文章展示了如何打开设备文件,读取温度数据,并将读取到的原始值转换为摄氏度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刚开始去读/dev/i2c-1, 但是在设置地址的时候,始终错误,返回-1, 所以最后还是用了sys接口

/*******************************************
 * Description: Read temperature sensor from LM75
 * Author:        Aaron.gao
 * Data:        20170524
 * Histroy:
 *                1. NULL
 * ****************************************/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include <stdlib.h>
#include <fcntl.h>
#include <termios.h>


/* main func */
int main(int argc, char **argv)
{
    int ret, fd;
    char buffer[10];
    int value;
    float temp = 0.0;

    while(1)
    {
        /* open device */
        fd = open("/sys/bus/i2c/devices/i2c-1/1-004f/hwmon/hwmon0/temp1_input", O_RDONLY);
        if( fd < 0)
        {
            printf("fd is %d\r\n", fd);
            printf("open i2c device-lm75 failed!\r\n");
            exit(1);
        }

        ret = read(fd, buffer, 10);
        if(ret < 0)
        {
            printf("read error\r\n");
        }
        value = atoi(buffer);
        memset(buffer, 0, strlen(buffer));
        temp = value / 1000.0;
        printf("environment temperature is %.2lfC\r\n", temp);
        sleep(2);
        
        close(fd);
    }
    
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值