luat_lib_pwm.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. @module pwm
  3. @summary PWM模块
  4. @version 1.0
  5. @date 2020.07.03
  6. @demo pwm
  7. @tag LUAT_USE_PWM
  8. */
  9. #include "luat_base.h"
  10. #include "luat_pwm.h"
  11. /**
  12. 开启指定的PWM通道
  13. @api pwm.open(channel, period, pulse, pnum, precision)
  14. @int PWM通道
  15. @int 频率, 1-1000000hz
  16. @int 占空比 0-分频精度
  17. @int 输出周期 0为持续输出, 1为单次输出, 其他为指定脉冲数输出
  18. @int 分频精度, 100/256/1000, 默认为100, 若设备不支持会有日志提示
  19. @return boolean 处理结果,成功返回true,失败返回false
  20. @usage
  21. -- 打开PWM5, 频率1kHz, 占空比50%
  22. pwm.open(5, 1000, 50)
  23. -- 打开PWM5, 频率10kHz, 分频为 31/256
  24. pwm.open(5, 10000, 31, 0, 256)
  25. */
  26. static int l_pwm_open(lua_State *L) {
  27. luat_pwm_conf_t conf = {
  28. .pnum = 0,
  29. .precision = 100
  30. };
  31. conf.channel = luaL_checkinteger(L, 1);
  32. conf.period = luaL_checkinteger(L, 2);
  33. conf.pulse = luaL_optnumber(L, 3,0);
  34. if (lua_isnumber(L, 4) || lua_isinteger(L, 4)){
  35. conf.pnum = luaL_checkinteger(L, 4);
  36. }
  37. if (lua_isnumber(L, 5) || lua_isinteger(L, 5)){
  38. conf.precision = luaL_checkinteger(L, 5);
  39. }
  40. int ret = luat_pwm_setup(&conf);
  41. lua_pushboolean(L, ret == 0 ? 1 : 0);
  42. return 1;
  43. }
  44. /**
  45. 关闭指定的PWM通道
  46. @api pwm.close(channel)
  47. @int PWM通道
  48. @return nil 无处理结果
  49. @usage
  50. -- 关闭PWM5
  51. pwm.close(5)
  52. */
  53. static int l_pwm_close(lua_State *L) {
  54. luat_pwm_close(luaL_checkinteger(L, 1));
  55. return 0;
  56. }
  57. /**
  58. PWM捕获
  59. @api pwm.capture(channel)
  60. @int PWM通道
  61. @int 捕获频率
  62. @return boolean 处理结果,成功返回true,失败返回false
  63. @usage
  64. -- PWM0捕获
  65. while 1 do
  66. pwm.capture(0,1000)
  67. local ret,channel,pulse,pwmH,pwmL = sys.waitUntil("PWM_CAPTURE", 2000)
  68. if ret then
  69. log.info("PWM_CAPTURE","channel"..channel,"pulse"..pulse,"pwmH"..pwmH,"pwmL"..pwmL)
  70. end
  71. end
  72. */
  73. static int l_pwm_capture(lua_State *L) {
  74. int ret = luat_pwm_capture(luaL_checkinteger(L, 1),luaL_checkinteger(L, 2));
  75. lua_pushboolean(L, ret == 0 ? 1 : 0);
  76. return 1;
  77. }
  78. #include "rotable2.h"
  79. static const rotable_Reg_t reg_pwm[] =
  80. {
  81. { "open" , ROREG_FUNC(l_pwm_open )},
  82. { "close" , ROREG_FUNC(l_pwm_close)},
  83. { "capture" , ROREG_FUNC(l_pwm_capture)},
  84. { NULL, ROREG_INT(0) }
  85. };
  86. LUAMOD_API int luaopen_pwm( lua_State *L ) {
  87. luat_newlib2(L, reg_pwm);
  88. return 1;
  89. }