ds18b20/temp.c
2019-06-07 20:06:07 +08:00

52 lines
1.2 KiB
C
Executable File

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/select.h>
float getTempByDev(char *devName);
int main(int argc, char *argv[])
{
float t223 = getTempByDev("/dev/ds18b20-223");
float t224 = getTempByDev("/dev/ds18b20-224");
printf("%.4f#%.4f\n", t223, t224);
return 0;
}
float getTempByDev(char *devName)
{
int fd;
unsigned char result[2] = {0};
unsigned int hightBitValue = 0;
unsigned int lowBitValue = 0;
float p = 0.0625;
float value = 1024.0f;
fd = open(devName, 0);
if (fd >= 0)
{
int i = read(fd, &result, sizeof(&result));
if (i >= 0)
{
// printf("%xH-%xH\n", result[1], result[0]);
hightBitValue = result[1];
lowBitValue = result[0];
hightBitValue <<= 8;
hightBitValue = hightBitValue + lowBitValue;
if ((result[1] & 0xf8))
{
// printf("aaa\n");
hightBitValue = ~hightBitValue + 1;
value = hightBitValue * p * -1;
}
else
{
value = hightBitValue * p;
}
}
close(fd);
}
return value;
}