下面是程序
#include <PS2X_lib.h> //for v1.6
#include <Servo.h>
PS2X ps2x; // create PS2 Controller Class
Servo myservo;//创建伺服器对象
Servo myservo1;
Servo myservo2;
Servo myservo3;
int serover =3; //定义舵机信号线接口
int serover1=4;//小臂
int serover2=5;//大臂
int serover3=6;
int pos;
int pos1;
int pos2;
int pos3;
float x;//定义数学方程变量
float y;
float posa;
float A;
float B;
float C;
float D;
float pi=acos(-1.0);
int error = 0;
byte type = 0;
byte vibrate = 0;
byte a = 0;
void setup(){
Serial.begin(115200);
myservo.attach(serover);
myservo1.attach(serover1);
myservo2.attach(serover2);
myservo3.attach(serover3);
pos=72;
x=150;
y=0;
pos3=90;
servo_write();
error = ps2x.config_gamepad(13,11,12,10, false, false); //setup pins and settings: GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error
if(error == 0){
Serial.println("");
}
else if(error == 1)
Serial.println("");
else if(error == 2)
Serial.println("");
Serial.println("");
//Serial.print(ps2x.Analog(1), HEX);
type = ps2x.readType();
switch(type) {
case 0:
Serial.println("0");
break;
case 1:
Serial.println("1");
break;
case 2:
Serial.println("2");
break;
}
}
void loop(){
if(error == 1) //skip loop if no controller found
return;
if(type == 2){ //Guitar Hero Controller
ps2x.read_gamepad(); //read controller
return;
}
else { //DualShock Controller
ps2x.read_gamepad(false, vibrate);
if(ps2x.Analog(PSS_LY)<127)
{
y=y-2; //L--UP
servo_write();
}
if(ps2x.Analog(PSS_LY)>128)
{
y=y+2; //L--DOWN
servo_write();
}
if(ps2x.Analog(PSS_LX)<127)
{
x=x-2; //L--LEFT
servo_write();
}
if(ps2x.Analog(PSS_LX)>128)
{
x=x+2; //L--RIGHT
servo_write();
}
if((ps2x.Analog(PSS_LY)==127) && (ps2x.Analog(PSS_LX)==128))
{
//b_stop();
}
if(ps2x.Analog(PSS_RY)<127)
{
pos++; //R--UP
servo_write();
}
if(ps2x.Analog(PSS_RY)>128)
{
pos--; //R--DOWN
servo_write();
}
if(ps2x.Analog(PSS_RX)<127)
{
pos3++; //R--LEFT
servo_write();
}
if(ps2x.Analog(PSS_RX)>128)
{
pos3--; //R--RIGHT
servo_write();
}
}
}
void servo_write()//写入舵机角度
{
A=sqrt(x*x+y*y);//数学方程
B=atan(y/x);
C=acos(A/300);
D=acos(1.0-A*A/45000);
D=D/pi*180;
posa=B+C;
pos1=posa/pi*180;
pos2=180-pos1-D;
myservo.write(pos);
myservo1.write(pos1);
myservo2.write(pos2);
myservo3.write(pos3);
Serial.print("pos=");//显示pos的值
Serial.println(pos);
Serial.print("pos1=");//显示pos1的值
Serial.println(pos1);
Serial.print("pos2=");//显示pos2的值
Serial.println(pos2);
Serial.print("pos3=");//显示pos3的值
Serial.println(pos3);
delay(8);
} |