dht.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Module for interfacing with the DHTxx sensors (xx = 11-21-22-33-44).
  2. #include "module.h"
  3. #include "lauxlib.h"
  4. #include "platform.h"
  5. #include "cpu_esp8266.h"
  6. #include "dht/dht.h"
  7. #define NUM_DHT GPIO_PIN_NUM
  8. // ****************************************************************************
  9. // DHT functions
  10. int platform_dht_exists( unsigned id )
  11. {
  12. return ((id < NUM_DHT) && (id > 0));
  13. }
  14. static void aux_read( lua_State *L )
  15. {
  16. double temp = dht_getTemperature();
  17. double humi = dht_getHumidity();
  18. int tempdec = (int)((temp - (int)temp) * 1000);
  19. int humidec = (int)((humi - (int)humi) * 1000);
  20. lua_pushnumber( L, (lua_Float) temp );
  21. lua_pushnumber( L, (lua_Float) humi );
  22. lua_pushinteger( L, tempdec );
  23. lua_pushinteger( L, humidec );
  24. }
  25. // Lua: status, temp, humi, tempdec, humidec = dht.read( id )
  26. static int dht_lapi_read( lua_State *L )
  27. {
  28. unsigned id = luaL_checkinteger( L, 1 );
  29. MOD_CHECK_ID( dht, id );
  30. lua_pushinteger( L, dht_read(id, DHT_NON11) );
  31. aux_read( L );
  32. return 5;
  33. }
  34. // Lua: status, temp, humi, tempdec, humidec = dht.read11( id ))
  35. static int dht_lapi_read11( lua_State *L )
  36. {
  37. unsigned id = luaL_checkinteger( L, 1 );
  38. MOD_CHECK_ID( dht, id );
  39. lua_pushinteger( L, dht_read(id, DHT11) );
  40. aux_read( L );
  41. return 5;
  42. }
  43. // Lua: status, temp, humi, tempdec, humidec = dht.read12( id ))
  44. static int dht_lapi_read12( lua_State *L )
  45. {
  46. unsigned id = luaL_checkinteger( L, 1 );
  47. MOD_CHECK_ID( dht, id );
  48. lua_pushinteger( L, dht_read(id, DHT12) );
  49. aux_read( L );
  50. return 5;
  51. }
  52. // Lua: status, temp, humi, tempdec, humidec = dht.readxx( id ))
  53. static int dht_lapi_readxx( lua_State *L )
  54. {
  55. unsigned id = luaL_checkinteger( L, 1 );
  56. MOD_CHECK_ID( dht, id );
  57. lua_pushinteger( L, dht_read(id, DHT22) );
  58. aux_read( L );
  59. return 5;
  60. }
  61. // Module function map
  62. LROT_BEGIN(dht, NULL, 0)
  63. LROT_FUNCENTRY( read, dht_lapi_read )
  64. LROT_FUNCENTRY( read11, dht_lapi_read11 )
  65. LROT_FUNCENTRY( read12, dht_lapi_read12 )
  66. LROT_FUNCENTRY( readxx, dht_lapi_read )
  67. LROT_NUMENTRY( OK, DHTLIB_OK )
  68. LROT_NUMENTRY( ERROR_CHECKSUM, DHTLIB_ERROR_CHECKSUM )
  69. LROT_NUMENTRY( ERROR_TIMEOUT, DHTLIB_ERROR_TIMEOUT )
  70. LROT_END(dht, NULL, 0)
  71. NODEMCU_MODULE(DHT, "dht", dht, NULL);