1. 程式人生 > >Arduino控制16路PWM舵機驅動板(PCA9685)

Arduino控制16路PWM舵機驅動板(PCA9685)

gin 很多 unsigned ets pan bits ble signed setup

最近買了塊16路PWM舵機驅動板,測試後做個總結。

舵機原理網上資料很多就不詳細介紹了,一般以9g舵機為例,一個20ms的周期內通過0.5ms到2.5ms的脈沖寬度控制舵機角度。

板子為16通道12bit PWM舵機驅動,用2個引腳通過I2C就可以驅動16個舵機。

修改例子為可以通過串口設置舵機角度

 1 #include <Wire.h>
 2 #include <Adafruit_PWMServoDriver.h>
 3 
 4 //默認地址 0x40
 5 Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
 6
7 //9g舵機 高電平寬度在20ms內通過控制脈沖寬度範圍0.5ms~2.5ms 8 #define SERVOMIN 102 // this is the ‘minimum‘ pulse length count (out of 4096) 0度 9 #define SERVOMAX 512 // this is the ‘maximum‘ pulse length count (out of 4096) 180度 10 11 void setup() { 12 Serial.begin(9600); 13 Serial.println("16 channel Servo test!"); 14 pwm.begin();
15 pwm.setPWMFreq(50); //頻率 50Hz,最高60Hz 16 } 17 18 void setServoPulse(uint8_t n, double pulse) { 19 double pulselength; 20 pulselength = 1000000; // 1,000,000 us per second 21 pulselength /= 50; // 50 Hz 22 Serial.print(pulselength); Serial.println(" us per period"); 23 pulselength /= 4096; // 12 bits of resolution
24 Serial.print(pulselength); Serial.println(" us per bit"); 25 pulse *= 1000; 26 pulse /= pulselength; 27 Serial.println(pulse); 28 pwm.setPWM(n, 0, pulse); 29 } 30 //設置9g舵機角度 31 void servo_9g_write(uint8_t n,int Angle) 32 { 33 double pulse = Angle; 34 pulse = pulse/90 + 0.5; 35 setServoPulse(n,pulse);//0到180度映射為0.5到2.5ms 36 } 37 void loop() 38 { 39 unsigned char serialRead; 40 if (Serial.available() > 0) 41 { 42 serialRead = Serial.read(); 43 servo_9g_write(0,serialRead);//控制第一路度數 44 } 45 }

Arduino控制16路PWM舵機驅動板(PCA9685)