testPwm.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const i2cBus = require("i2c-bus")
  2. const { Pca9685Driver } = require("pca9685")
  3. class ContrlService {
  4. constructor() {
  5. // PWM 和 舵机配置
  6. this.pwmOption = {
  7. i2c: i2cBus.openSync(1), // 树莓派1:scl1
  8. address: 0x40, //板子地址
  9. frequency: 50, //频率
  10. debug: false
  11. }
  12. // init PWM
  13. this.PWM = new Pca9685Driver(this.pwmOption, er => {
  14. if (er) {
  15. console.error("Error initializing PCA9685");
  16. }
  17. })
  18. console.log('测试开始');
  19. let a = 90
  20. const t = setInterval(() => {
  21. if(a >= 160) {
  22. clearInterval(t)
  23. // this.PWM.setPulseLength(1, this.Servo2pwm(130));
  24. return
  25. }
  26. a++
  27. this.PWM.setPulseLength(1, this.Servo2pwm(a));
  28. console.log(a);
  29. }, 20);
  30. }
  31. /**
  32. * 舵机换算比例:摇杆范围0-256,PWM范围500~1500~2500
  33. * @param {number} v
  34. * @returns
  35. */
  36. Servo2pwm(v) {
  37. return parseInt(v / (256 / 2000)) + 500
  38. // return parseInt(v / (256 / 1000)) + 1000
  39. }
  40. }
  41. new ContrlService()