temp.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include <fcntl.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <sys/select.h>
  5. #include <pthread.h>
  6. #define N 2
  7. float getTempByDev(char *devName);
  8. void *run(void *args);
  9. float results[N];
  10. pthread_t tids[N];
  11. char *names[] = {"/dev/ds18b20-223","/dev/ds18b20-224"};
  12. int main(int argc, char *argv[])
  13. {
  14. int i = 0;
  15. for (i = 0; i < N; i++)
  16. {
  17. pthread_create(&tids[i], NULL, run, (void*)i);
  18. }
  19. for (i = 0; i < N; i++)
  20. {
  21. pthread_join(tids[i], NULL);
  22. }
  23. for (i = 0; i < N; i++)
  24. {
  25. if (i > 0)
  26. {
  27. printf("#");
  28. }
  29. printf("%.3f", results[i]);
  30. }
  31. printf("\n");
  32. return 0;
  33. }
  34. void *run(void *args)
  35. {
  36. int ret=(int)args;
  37. float res = getTempByDev(names[ret]);
  38. results[ret] = res;
  39. }
  40. float getTempByDev(char *devName)
  41. {
  42. int fd;
  43. unsigned char result[2] = {0};
  44. unsigned int hightBitValue = 0;
  45. unsigned int lowBitValue = 0;
  46. float p = 0.0625;
  47. float value = 1024;
  48. short count = 0;
  49. fd = open(devName, 0);
  50. if (fd >= 0)
  51. {
  52. do
  53. {
  54. count++;
  55. int i = read(fd, &result, sizeof(&result));
  56. if (i >= 0)
  57. {
  58. hightBitValue = result[1];
  59. lowBitValue = result[0];
  60. hightBitValue <<= 8;
  61. hightBitValue = hightBitValue + lowBitValue;
  62. if ((result[1] & 0xf8))
  63. {
  64. hightBitValue = ~hightBitValue + 1;
  65. value = hightBitValue * p * -1;
  66. }
  67. else
  68. {
  69. value = hightBitValue * p;
  70. }
  71. }
  72. }
  73. while ((value < -55 || value > 125) && count < 5);
  74. close(fd);
  75. }
  76. return value;
  77. }