GetStopBit.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const i2cBus = require("i2c-bus")
  2. const { Pca9685Driver } = require("pca9685")
  3. const RPIO = require("rpio");
  4. const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
  5. class ContrlService {
  6. constructor() {
  7. // PWM 和 舵机配置
  8. this.pwmOption = {
  9. i2c: i2cBus.openSync(1), // 树莓派1:scl1
  10. address: 0x40, //板子地址
  11. frequency: 50, //频率
  12. debug: false
  13. }
  14. // init PWM
  15. this.PWM = new Pca9685Driver(this.pwmOption, er => {
  16. if (er) {
  17. console.error("Error initializing PCA9685");
  18. }
  19. })
  20. // prio init
  21. RPIO.init({ mapping: "gpio" });
  22. // init PWM
  23. this.ins = 0
  24. this.timer = 0
  25. // test Pwm
  26. this.num = 0
  27. this.startInt()
  28. }
  29. // 测试全程找中位
  30. startInt() {
  31. console.log('start');
  32. RPIO.open(6, RPIO.OUTPUT, RPIO.HIGH);
  33. RPIO.open(13, RPIO.OUTPUT, RPIO.HIGH);
  34. RPIO.open(19, RPIO.OUTPUT, RPIO.HIGH);
  35. this.timer = setInterval(() => {
  36. this.num++
  37. // if (this.num >= 255) {
  38. // // 继电器停止
  39. // RPIO.open(6, RPIO.OUTPUT, RPIO.LOW);
  40. // RPIO.open(13, RPIO.OUTPUT, RPIO.LOW);
  41. // RPIO.open(19, RPIO.OUTPUT, RPIO.LOW);
  42. // clearInterval(this.timer);
  43. // this.num = 0
  44. // console.log('end');
  45. // return
  46. // }
  47. // 寻找中位=>120-130
  48. if(this.num >= 120 && this.num <= 130){
  49. this.PWM.setPulseLength(this.ins, this.Servo2pwm(this.num));
  50. clearInterval(this.timer);
  51. console.log('center',this.num);
  52. return
  53. }
  54. this.PWM.setPulseLength(this.ins, this.Servo2pwm(10));
  55. console.log(this.num);
  56. }, 50);
  57. }
  58. /**
  59. * 舵机换算比例:摇杆范围0-256,PWM范围1000~1500~2000
  60. * @param {number} v
  61. * @returns
  62. */
  63. Servo2pwm(v) {
  64. return parseInt(v / (256 / 1000)) + 1000
  65. }
  66. }
  67. new ContrlService()