gettemp.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include <fcntl.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6. #include <sys/select.h>
  7. float getTempByDev(char *devName);
  8. int main(int argc, char *argv[])
  9. {
  10. if (argc == 2)
  11. {
  12. char * ch = argv[1];
  13. // int gpio = atoi(ch);
  14. char * name = "/dev/ds18b20-";
  15. char devName[16];
  16. strcpy(devName, name);
  17. strcat(devName, ch);
  18. float t223 = getTempByDev(devName);
  19. printf("%.4f", t223);
  20. }
  21. else
  22. {
  23. printf("-1");
  24. }
  25. return 0;
  26. }
  27. float getTempByDev(char *devName)
  28. {
  29. int fd;
  30. unsigned char result[2] = {0};
  31. unsigned int hightBitValue = 0;
  32. unsigned int lowBitValue = 0;
  33. float p = 0.0625;
  34. float value = 1024.0f;
  35. fd = open(devName, 0);
  36. if (fd >= 0)
  37. {
  38. int i = read(fd, &result, sizeof(&result));
  39. if (i >= 0)
  40. {
  41. // printf("%xH-%xH\n", result[1], result[0]);
  42. hightBitValue = result[1];
  43. lowBitValue = result[0];
  44. hightBitValue <<= 8;
  45. hightBitValue = hightBitValue + lowBitValue;
  46. if ((result[1] & 0xf8))
  47. {
  48. // printf("aaa\n");
  49. hightBitValue = ~hightBitValue + 1;
  50. value = hightBitValue * p * -1;
  51. }
  52. else
  53. {
  54. value = hightBitValue * p;
  55. }
  56. }
  57. close(fd);
  58. }
  59. return value;
  60. }