hwmon通过smbus block write read读取某设备温度 实例
时间: 2024-01-04 14:03:11 浏览: 257
好的,以下是一个通过smbus block write/read读取设备温度的示例代码:
```c
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int file;
char *bus = "/dev/i2c-0"; // smbus总线设备文件名,可以根据实际情况修改
int addr = 0x4c; // 设备地址,可以根据实际情况修改
char buf[4] = {0};
if ((file = open(bus, O_RDWR)) < 0) {
printf("Failed to open the bus.\n");
return -1;
}
if (ioctl(file, I2C_SLAVE, addr) < 0) {
printf("Failed to acquire bus access and/or talk to slave.\n");
return -1;
}
// 发送block write指令,写入指令码0x01和寄存器地址0x00
buf[0] = 0x01;
buf[1] = 0x00;
if (write(file, buf, 2) != 2) {
printf("Failed to write to the i2c bus.\n");
return -1;
}
// 发送block read指令,读取2字节温度值
if (read(file, buf, 2) != 2) {
printf("Failed to read from the i2c bus.\n");
return -1;
}
// 将读取到的2字节温度值转换为摄氏度,并打印
int temp = (buf[0] << 8) | buf[1];
printf("Temperature: %.2f℃\n", temp * 0.0625);
return 0;
}
```
这里假设设备地址为0x4c,要读取的温度值存储在寄存器地址0x00中,每个温度单位占据2字节,且是以补码形式存储的。通过发送block write指令写入指令码0x01和寄存器地址0x00,再发送block read指令读取2字节温度值,最后将读取到的温度值转换为摄氏度并打印。
阅读全文