luat_lib_pwm.c 2.3 KB

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