#include <AFMotor.h>
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
#define MIN_PULSE_WIDTH 650
#define MAX_PULSE_WIDTH 2350
#define DEFAULT_PULSE_WIDTH 1500
#define FREQUENCY 50
void setup() {
pwm.begin();
pwm.setPWMFreq(FREQUENCY);
Serial.begin(9600);
}
void loop() {
//Read from bluetooth and write to usb serial
if(Serial.available()>= 2 )
{
unsigned int servopos = Serial.read();
unsigned int servopos1 = Serial.read();
unsigned int realservo = (servopos1 *256) + servopos;
Serial.println(realservo);
if (realservo >= 1000 && realservo <1180){
int servo1 = realservo;
servo1 = map(servo1, 1000,1180,0,180);
pwm.setPWM(3, 0, pulseWidth(servo1));
Serial.println("servo 1 ON");
delay(10);
}
if (realservo >=2000 && realservo <2180){
int servo2 = realservo;
servo2 = map(servo2,2000,2180,0,180);
pwm.setPWM(5, 0, pulseWidth(servo2));
Serial.println("servo 2 On");
delay(10);
}
if (realservo >=3000 && realservo < 3180){
int servo3 = realservo;
servo3 = map(servo3, 3000, 3180,0,180);
pwm.setPWM(8, 0, pulseWidth(servo3));
Serial.println("servo 3 On");
delay(10);
}
if (realservo >=4000 && realservo < 4180){
int servo4 = realservo;
servo4 = map(servo4, 4000, 4180,0,180);
pwm.setPWM(13, 0, pulseWidth(servo4));
Serial.println("servo 4 On");
delay(10);
}
if (realservo >=5000 && realservo < 5180){
int servo5 = realservo;
servo5 = map(servo5, 5000, 5180,0,180);
pwm.setPWM(11, 0, pulseWidth(servo5));
Serial.println("servo 5 On");
delay(10);
}
if (realservo >=6000 && realservo < 6180){
int servo6 = realservo;
servo6 = map(servo6, 6000, 6180,0,90);
pwm.setPWM(15, 0, pulseWidth(servo6));
Serial.println("servo 6 On");
delay(10);
}
}
}
int pulseWidth(int angle)
{
int pulse_wide, analog_value;
pulse_wide = map(angle, 0, 180, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);
analog_value = int(float(pulse_wide) / 1000000 * FREQUENCY * 4096);
return analog_value;
}
Comments