📄 lm75.c
字号:
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/types.h>#include <fcntl.h>#include <sys/stat.h>#include <termios.h>#include <unistd.h>#include <sys/ioctl.h>#include <linux/ioctl.h>#include <linux/i2c-dev.h>#include <asm/errno.h>#include "lm75.h"#define I2C_SLAVE 0x0703#define ID_PHY 0x96/* The LM75 registers */#define LM75_REG_TEMP 0x00#define LM75_REG_CONF 0x01#define LM75_REG_TEMP_HYST 0x02#define LM75_REG_TEMP_OS 0x03/* Each client has this additional data */struct lm75_data { unsigned short temp_input; /* Register values */ unsigned short temp_max; unsigned short temp_hyst;};static int lm75_init(int file);static int lm75_get_temp(int file, struct lm75_data * value);main(int argc, char **argv){ int file; int adapter_nr = 0; char filename[20]; struct lm75_data value; int ret; sprintf(filename, "/dev/i2c-%d", adapter_nr); if ((file = open(filename, O_RDWR)) < 0) { perror("No such i2c device!\n"); exit(1); } int addr = (ID_PHY) >> 1; /* The I2C address */ if ((ret = ioctl(file, I2C_SLAVE, addr)) < 0) { if(ret == -EBUSY) printf("Device busy\n"); if(ret == -EINVAL) printf("invalid addr\n"); printf("No such slave device. %d\n ", ret); close(file); exit(1); } lm75_init(file); lm75_get_temp(file, &value); printf("temp_input: %d , temp_max: %d , temp_hyst: %d \n", LM75_TEMP_FROM_REG(value.temp_input), LM75_TEMP_FROM_REG(value.temp_max), LM75_TEMP_FROM_REG(value.temp_hyst) ); close(file);}static int lm75_init(int file){ unsigned char buf[2]; memset(buf, 0, sizeof(buf)); buf[0] = LM75_REG_CONF; write(file, buf , 1); buf[0] = 0; write(file, buf , 1); }static int lm75_get_temp(int file, struct lm75_data * value){ int ret = -EIO; unsigned char buf[5]; int i; memset(buf, 0, sizeof(buf)); buf[0] = LM75_REG_TEMP;while(1){ write(file, buf , 1);sleep(1);} ret = read(file, buf, 2); if (ret<0){ perror("read error!\n"); exit(1); } value->temp_input = (unsigned short)buf[0]<<8 | buf[1]; buf[0] = LM75_REG_TEMP_OS; write(file, buf , 1); ret = read(file, buf, 2); if (ret<0){ perror("read error!\n"); exit(1); } value->temp_max = (unsigned short)buf[0]<<8 | buf[1]; buf[0] = LM75_REG_TEMP_HYST; write(file, buf , 1); ret = read(file, buf, 2); if (ret<0){ perror("read error!\n"); exit(1); } value->temp_hyst = (unsigned short)buf[1]<<8 | buf[0]; return 0;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -