hx711.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Module for HX711 load cell amplifier
  2. // https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide
  3. #include "module.h"
  4. #include "lauxlib.h"
  5. #include "platform.h"
  6. #include "c_stdlib.h"
  7. #include "c_string.h"
  8. #include "user_interface.h"
  9. static uint8_t data_pin;
  10. static uint8_t clk_pin;
  11. /*Lua: hx711.init(clk_pin,data_pin)*/
  12. static int hx711_init(lua_State* L) {
  13. clk_pin = luaL_checkinteger(L,1);
  14. data_pin = luaL_checkinteger(L,2);
  15. MOD_CHECK_ID( gpio, clk_pin );
  16. MOD_CHECK_ID( gpio, data_pin );
  17. platform_gpio_mode(clk_pin, PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_FLOAT);
  18. platform_gpio_mode(data_pin, PLATFORM_GPIO_INPUT, PLATFORM_GPIO_FLOAT);
  19. platform_gpio_write(clk_pin,1);//put chip to sleep.
  20. return 0;
  21. }
  22. #define HX711_MAX_WAIT 1000000
  23. /*will only read chA@128gain*/
  24. /*Lua: result = hx711.read()*/
  25. static int ICACHE_FLASH_ATTR hx711_read(lua_State* L) {
  26. uint32_t i;
  27. int32_t data = 0;
  28. //TODO: double check init has happened first.
  29. //wakeup hx711
  30. platform_gpio_write(clk_pin,0);
  31. //wait for data ready. or time out.
  32. //TODO: set pin inturrupt and come back to it. This may take up to 1/10 sec
  33. // or maybe just make an async version too and have both available.
  34. system_soft_wdt_feed(); //clear WDT... this may take a while.
  35. for (i = 0; i<HX711_MAX_WAIT && platform_gpio_read(data_pin)==1;i++){
  36. asm ("nop");
  37. }
  38. //Handle timeout error
  39. if (i>=HX711_MAX_WAIT) {
  40. return luaL_error( L, "ADC timeout!", ( unsigned )0 );
  41. }
  42. for (i = 0; i<24 ; i++){ //clock in the 24 bits
  43. platform_gpio_write(clk_pin,1);
  44. platform_gpio_write(clk_pin,0);
  45. data = data<<1;
  46. if (platform_gpio_read(data_pin)==1) {
  47. data = i==0 ? -1 : data|1; //signextend the first bit
  48. }
  49. }
  50. //add 25th clock pulse to prevent protocol error (probably not needed
  51. // since we'll go to sleep immediately after and reset on wakeup.)
  52. platform_gpio_write(clk_pin,1);
  53. platform_gpio_write(clk_pin,0);
  54. //sleep
  55. platform_gpio_write(clk_pin,1);
  56. lua_pushinteger( L, data );
  57. return 1;
  58. }
  59. // Module function map
  60. static const LUA_REG_TYPE hx711_map[] = {
  61. { LSTRKEY( "init" ), LFUNCVAL( hx711_init )},
  62. { LSTRKEY( "read" ), LFUNCVAL( hx711_read )},
  63. { LNILKEY, LNILVAL}
  64. };
  65. int luaopen_hx711(lua_State *L) {
  66. // TODO: Make sure that the GPIO system is initialized
  67. return 0;
  68. }
  69. NODEMCU_MODULE(HX711, "hx711", hx711_map, luaopen_hx711);