请注意,本文内容源自机器翻译,可能存在语法或其它翻译错误,仅供参考。如需获取准确内容,请参阅链接中的英语原文或自行翻译。
器件型号:TMP112 工具与软件:
请提供 TMP112温度传感器的示例 C 代码。
This thread has been locked.
If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.
该 TI I2C 温度传感器示例基于 Linux 内核文档中的示例:
https://docs.kernel.org/i2c/dev-interface.html
https://docs.kernel.org/i2c/smbus-protocol.html
这是访问/dev/i2c 器件的用户空间代码、但它可以根据内核驱动程序代码进行调整。
使用软件包管理器(例如 apt) libi2c-dev
通过-li2c
标志进行安装和编译。
这是使用 TMP112在 aspberryPi 4上进行的测试、但与任何具有 12位 Q4编码的类似75的温度传感器兼容。
请注意、此代码使用 SMBus 读取字、大多数传感器具有错误的字节序。 此代码用于 __builtin_bswap16()
执行字节交换。
#include <fcntl.h> #include <i2c/smbus.h> #include <linux/i2c-dev.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <unistd.h> int main() { int file; int adapter_nr = 1; /* /dev/i2c- number */ char filename[20]; int addr = 0x49; /* Sensor I2C address */ __u8 reg = 0x0; /* Temperature register address */ __s32 res; snprintf(filename, 19, "/dev/i2c-%d", adapter_nr); file = open(filename, O_RDWR); if (file < 0) { printf("Failed to open %s\n", filename); exit(1); } if (ioctl(file, I2C_SLAVE, addr) < 0) { printf("Failed to set address\n"); exit(1); } /* need to fetch 2 bytes (16 bits) */ res = i2c_smbus_read_word_data(file, reg); if (res < 0) { printf("smbus_read failed\n"); } else { /* SMBus word is LSByte first, so we must change endianness */ int16_t word = __builtin_bswap16(res); /* print result in hex */ printf("0x%X\n", word); /* print result in degrees c */ printf("%f\n", (float)(word >> 4) * 0.0625f); } close(file); }