ds18b20_sample.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * Copyright (c) 2006-2018, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2019-07-24 WillianChan the first version
  9. * 2020-07-28 WillianChan add the inclusion of the board.h
  10. */
  11. #include <stdlib.h>
  12. #include <rtthread.h>
  13. #include <rtdevice.h>
  14. #include "board.h"
  15. #include "dallas_ds18b20_sensor_v1.h"
  16. /* Modify this pin according to the actual wiring situation */
  17. #define DS18B20_DATA_PIN GET_PIN(G, 9)
  18. static void read_temp_entry(void *parameter)
  19. {
  20. rt_device_t dev = RT_NULL;
  21. struct rt_sensor_data sensor_data;
  22. rt_size_t res;
  23. dev = rt_device_find(parameter);
  24. if (dev == RT_NULL)
  25. {
  26. rt_kprintf("Can't find device:%s\n", parameter);
  27. return;
  28. }
  29. if (rt_device_open(dev, RT_DEVICE_FLAG_RDWR) != RT_EOK)
  30. {
  31. rt_kprintf("open device failed!\n");
  32. return;
  33. }
  34. rt_device_control(dev, RT_SENSOR_CTRL_SET_ODR, (void *)100);
  35. while (1)
  36. {
  37. res = rt_device_read(dev, 0, &sensor_data, 1);
  38. if (res != 1)
  39. {
  40. rt_kprintf("read data failed!size is %d\n", res);
  41. rt_device_close(dev);
  42. return;
  43. }
  44. else
  45. {
  46. if (sensor_data.data.temp >= 0)
  47. {
  48. rt_kprintf("temp:%3d.%dC, timestamp:%5d\n",
  49. sensor_data.data.temp / 10,
  50. sensor_data.data.temp % 10,
  51. sensor_data.timestamp);
  52. }
  53. else
  54. {
  55. rt_kprintf("temp:-%2d.%dC, timestamp:%5d\n",
  56. abs(sensor_data.data.temp / 10),
  57. abs(sensor_data.data.temp % 10),
  58. sensor_data.timestamp);
  59. }
  60. }
  61. rt_thread_mdelay(100);
  62. }
  63. }
  64. static int ds18b20_read_temp_sample(void)
  65. {
  66. rt_thread_t ds18b20_thread;
  67. ds18b20_thread = rt_thread_create("18b20tem",
  68. read_temp_entry,
  69. "temp_ds18b20",
  70. 1024,
  71. RT_THREAD_PRIORITY_MAX / 2,
  72. 20);
  73. if (ds18b20_thread != RT_NULL)
  74. {
  75. rt_thread_startup(ds18b20_thread);
  76. }
  77. return RT_EOK;
  78. }
  79. INIT_APP_EXPORT(ds18b20_read_temp_sample);
  80. static int rt_hw_ds18b20_port(void)
  81. {
  82. struct rt_sensor_config cfg;
  83. cfg.intf.user_data = (void *)DS18B20_DATA_PIN;
  84. rt_hw_ds18b20_init("ds18b20", &cfg);
  85. return RT_EOK;
  86. }
  87. INIT_COMPONENT_EXPORT(rt_hw_ds18b20_port);