adc.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Module for interfacing with adc
  2. #include "module.h"
  3. #include "lauxlib.h"
  4. #include "platform.h"
  5. #include <stdint.h>
  6. #include "user_interface.h"
  7. // Lua: read(id) , return system adc
  8. static int adc_sample( lua_State* L )
  9. {
  10. unsigned id = luaL_checkinteger( L, 1 );
  11. MOD_CHECK_ID( adc, id );
  12. unsigned val = 0xFFFF & system_adc_read();
  13. lua_pushinteger( L, val );
  14. return 1;
  15. }
  16. // Lua: readvdd33()
  17. static int adc_readvdd33( lua_State* L )
  18. {
  19. lua_pushinteger(L, system_get_vdd33 ());
  20. return 1;
  21. }
  22. // Lua: adc.force_init_mode(x)
  23. static int adc_init107( lua_State *L )
  24. {
  25. uint8_t byte107 = luaL_checkinteger (L, 1);
  26. uint32_t init_data[SPI_FLASH_SEC_SIZE/sizeof(uint32_t)];
  27. partition_item_t pd_pt = {0,0,0};
  28. uint32_t init_sector;
  29. luaL_argcheck(L, cast(uint8_t, byte107+1) < 2, 1, "Invalid mode");
  30. system_partition_get_item(SYSTEM_PARTITION_PHY_DATA, &pd_pt);
  31. init_sector = platform_flash_get_sector_of_address(pd_pt.addr);
  32. if (pd_pt.size == 0 ||
  33. platform_s_flash_read(init_data, pd_pt.addr, sizeof(init_data))==0)
  34. return luaL_error(L, "flash read error");
  35. // If it's already the correct value, we don't need to force it
  36. if (cast(uint8_t *, init_data)[107] == byte107) {
  37. lua_pushboolean (L, false);
  38. return 1;
  39. }
  40. cast(uint8_t *, init_data)[107] = byte107;
  41. /* Only do erase if toggling 0x00 to 0xFF */
  42. if(byte107 && platform_flash_erase_sector(init_sector) != PLATFORM_OK)
  43. return luaL_error(L, "flash erase error");
  44. if(platform_flash_write(init_data, pd_pt.addr, sizeof(init_data))==0)
  45. return luaL_error(L, "flash write error");
  46. lua_pushboolean (L, true);
  47. return 1;
  48. }
  49. // Module function map
  50. LROT_BEGIN(adc, NULL, 0)
  51. LROT_FUNCENTRY( read, adc_sample )
  52. LROT_FUNCENTRY( readvdd33, adc_readvdd33 )
  53. LROT_FUNCENTRY( force_init_mode, adc_init107 )
  54. LROT_NUMENTRY( INIT_ADC, 0x00 )
  55. LROT_NUMENTRY( INIT_VDD33, 0xff )
  56. LROT_END(adc, NULL, 0)
  57. NODEMCU_MODULE(ADC, "adc", adc, NULL);