SERVO2_PCA9685.ino 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. Description: Use SERVO2 Module to control the rotation of 16-channel servo.
  3. */
  4. #include <M5Stack.h>
  5. #include <Wire.h>
  6. #include "Adafruit_PWMServoDriver.h"
  7. Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x40, Wire);
  8. #define SERVOMIN 102 // This is the 'minimum' pulse length count (out of 4096)
  9. #define SERVOMAX 512 // This is the 'maximum' pulse length count (out of 4096)
  10. #define USMIN 500 // This is the rounded 'minimum' microsecond length based on the minimum pulse of 102
  11. #define USMAX 2500 // This is the rounded 'maximum' microsecond length based on the maximum pulse of 512
  12. #define SERVO_FREQ 50 // Analog servos run at ~50 Hz updates
  13. void setup() {
  14. M5.begin(true, true, true, true);
  15. pwm.begin();
  16. pwm.setPWMFreq(50);
  17. M5.Lcd.setCursor(115, 0, 4);
  18. M5.Lcd.setTextColor(TFT_GREEN, TFT_BLACK);
  19. M5.Lcd.print("Servo2");
  20. }
  21. void setServoPulse(uint8_t n, double pulse) {
  22. double pulselength;
  23. pulselength = 1000000; // 1,000,000 us per second
  24. pulselength /= 50; // 50 Hz
  25. Serial.print(pulselength); Serial.println(" us per period");
  26. pulselength /= 4096; // 12 bits of resolution
  27. Serial.print(pulselength); Serial.println(" us per bit");
  28. pulse *= 1000;
  29. pulse /= pulselength;
  30. Serial.println(pulse);
  31. pwm.setPWM(n, 0, pulse);
  32. }
  33. void servo_angle_write(uint8_t n, int Angle) {
  34. double pulse = Angle;
  35. pulse = pulse/90 + 0.5;
  36. setServoPulse(n, pulse);
  37. }
  38. void loop() {
  39. for(int i=0; i<16; i++) {
  40. setServoPulse(i, 0.5);
  41. }
  42. delay(500);
  43. for(int i=0; i<16; i++) {
  44. setServoPulse(i, 2.5);
  45. }
  46. delay(500);
  47. }