adc.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Module for interfacing with adc
  2. #include "module.h"
  3. #include "lauxlib.h"
  4. #include "platform.h"
  5. #include "c_types.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 init_sector = flash_rom_get_sec_num () - 4;
  27. // Note 32bit alignment so we can safely cast to uint32 for the flash api
  28. char init_data[SPI_FLASH_SEC_SIZE] __attribute__((aligned(4)));
  29. if (SPI_FLASH_RESULT_OK != flash_read (
  30. init_sector * SPI_FLASH_SEC_SIZE,
  31. (uint32 *)init_data, sizeof(init_data)))
  32. return luaL_error(L, "flash read error");
  33. // If it's already the correct value, we don't need to force it
  34. if (init_data[107] == byte107)
  35. {
  36. lua_pushboolean (L, false);
  37. return 1;
  38. }
  39. // Nope, it differs, we need to rewrite it
  40. init_data[107] = byte107;
  41. if (SPI_FLASH_RESULT_OK != flash_erase (init_sector))
  42. return luaL_error(L, "flash erase error");
  43. if (SPI_FLASH_RESULT_OK != flash_write (
  44. init_sector * SPI_FLASH_SEC_SIZE,
  45. (uint32 *)init_data, sizeof(init_data)))
  46. return luaL_error(L, "flash write error");
  47. lua_pushboolean (L, true);
  48. return 1;
  49. }
  50. // Module function map
  51. static const LUA_REG_TYPE adc_map[] = {
  52. { LSTRKEY( "read" ), LFUNCVAL( adc_sample ) },
  53. { LSTRKEY( "readvdd33" ), LFUNCVAL( adc_readvdd33 ) },
  54. { LSTRKEY( "force_init_mode" ), LFUNCVAL( adc_init107 ) },
  55. { LSTRKEY( "INIT_ADC" ), LNUMVAL( 0x00 ) },
  56. { LSTRKEY( "INIT_VDD33" ),LNUMVAL( 0xff ) },
  57. { LNILKEY, LNILVAL }
  58. };
  59. NODEMCU_MODULE(ADC, "adc", adc_map, NULL);