I'm currently trying to add servo(SG90) to my robot. The robot is controlled by PS4 controller via bluetooth.
A library called is already included and this is the movement of servo that I want (constantly moving at the range of 30 degree to 150 degree and the servo's speed is at 40)
const int Max= 150; //Max 150 degree
const int Min= 30; //Min 30 degree
for(int i= Min; i<=Max; i+=30){
myservo.write(i,speed,true);
}
for(int j= Max; j>=Min; j-=30){
myservo.write(j,speed,true);
}
And this is the loop operation. I'm using PS4 stick to control the robot.
void loop() {
Usb.Task();
if (PS4.connected()) {
int Lx;
Lx= PS4.getAnalogHat(LeftHatX)-127;
int Ly;
Ly= 127-PS4.getAnalogHat(LeftHatY);
double degree;
degree= atan2(Ly,Lx)*180.0/PI+180;
double radius;
radius = sqrt(pow(Lx,2)+pow(Ly,2));
if(radius>=45)
{
//*** go straight ***//
if ((degree>225)&&(degree<315))
{
Serial.print(F("\r\ndegree: "));
Serial.print(degree);
Serial.println("go straight!");
digitalWrite(5,HIGH);
digitalWrite(4,LOW);
digitalWrite(3,HIGH);
digitalWrite(2,LOW);
}
//*** move backward ***//
if ((degree>45)&&(degree<135))
{
Serial.print(F("\r\ndegree: "));
Serial.print(degree);
Serial.println("move backward");
digitalWrite(5,LOW);
digitalWrite(4,HIGH);
digitalWrite(3,LOW);
digitalWrite(2,HIGH);
}
//*** turn LEFT ***//
if (((degree>0)&&(degree<45))||((degree>315)&&(degree<360)))
{
Serial.print(F("\r\ndegree: "));
Serial.print(degree);
Serial.println("turn LEFT!!!");
digitalWrite(5,LOW);
digitalWrite(4,HIGH);
digitalWrite(3,HIGH);
digitalWrite(2,LOW);
}
//*** turn RIGHT ***//
if ((degree>135)&&(degree<225))
{
Serial.print(F("\r\ndegree: "));
Serial.print(degree);
Serial.println("turn RIGHT!!!");
digitalWrite(5,HIGH);
digitalWrite(4,LOW);
digitalWrite(3,LOW);
digitalWrite(2,HIGH);
}
//*** STOP ***//
else
{
Serial.println("STOP!");
digitalWrite(5,LOW);
digitalWrite(4,LOW);
digitalWrite(3,LOW);
digitalWrite(2,LOW);
}
}
}
}
My ideal is to let the servo rotates constantly while the robot is controlled by PS4 stick. But here are the problems. When I put servo operation before if() operation in the loop, the robot was not reacting and only the servo was moving.
Then, I put servo operation into if() operation. For example,
digitalWrite(5,HIGH);
digitalWrite(4,LOW);
digitalWrite(3,HIGH);
digitalWrite(2,LOW);
for(int i= Min; i<=Max; i+=30){
myservo.write(i,speed,true);
}
for(int j= Max; j>=Min; j-=30){
myservo.write(j,speed,true);
}
However, I faced the connection problem. (PS4 is not connected to the arduino at all)
Can somebody help me solve this? Thank you.
