[pre lang="arduino" line="1" file="servoes_control"]
#include <Servo.h>
long starttime;
int postInterval = 50;
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
int pos1 = 90;
int pos2 = 90;
int pos3 = 90;
int pos4 = 90;
int maxPos = 150;
int minPos = 30;
int stp = 2;
int x1potPin = 0; //设置模拟口0为X的信号输入端口
int y1potPin = 1; //设置模拟口1为Y的信号输入端口
int x2potPin = 2;
int y2potPin = 3;
int x1val=0; //设置变量
int y1val=0;
int x2val=0;
int y2val=0;
boolean bUpdateServo = true;
void setup()
{
starttime = millis();
Serial.begin(9600);
servo1.attach(2);
servo2.attach(3);
servo3.attach(4);
servo4.attach(5);
}
void loop ()
{
if ((millis()-starttime) > postInterval)
{
checkInput();
starttime = millis();
}
}
void checkInput()
{
x1val = analogRead(x1potPin); //xval变量为从0信号口读取到的数值
y1val = analogRead(y1potPin); //yval变量为从1信号口读取到的数值
x2val = analogRead(x2potPin);
y2val = analogRead(y2potPin);
pos1 = checkState(x1val,pos1);
pos2 = checkState(y1val,pos2);
pos3 = checkState(x2val,pos3);
pos4 = checkState(y2val,pos4);
if(bUpdateServo)
{
updateServo();
bUpdateServo = false;
}
}
int checkState(int val,int pos)
{
if(val > 600)
{
if(pos < maxPos)
{
pos+= stp;
bUpdateServo = true;
}
}
else if(val <400)
{
if(pos > minPos)
{
pos-=stp;
bUpdateServo = true;
}
}
return pos;
}
void updateServo()
{
servo1.write(pos1);
servo2.write(pos2);
servo3.write(pos3);
servo4.write(pos4);
}[/code]
刚好写了个双摇杆控制四舵机的简单程序。
Enjoy it~ |