|
最近想玩 APM雷达追踪, 但 Maestro 6ch servo controller 太贵了 就自己做一个。
原型做好了,就是在APM中调试界面中也能操作,就是抖舵太严重了,现在我把源代码公开,大家一起来讨论
材料: Arduino ProMini/Nano
转向舵机连接 pin 2 , 俯仰舵机连接pin 3
源代码
======== apm_attenal_tracker.ino=====
//#define DEBUG true
#include <Servo.h>
#ifdef DEBUG
#error
#include <SoftwareSerial.h>
#endif
const int SERVO_CONTROLLER_RX_PIN = 11; // The SERVO CONTROLLER'S RX PIN.
const int SERVO_CONTROLLER_TX_PIN = 12;
boolean cmdComplete = false; // whether the string is complete
static int dataBufferIndex = 0;
static int remainingByte = 0;
#define BUF_LEN 12
byte serialBuffer[BUF_LEN] = "";
#ifdef DEBUG
SoftwareSerial softSerial = SoftwareSerial(SERVO_CONTROLLER_RX_PIN, SERVO_CONTROLLER_TX_PIN);
#endif
Servo servo[2];
int prev_pwm[2];
void setup(void) {
Serial.begin(57600);
#ifdef DEBUG
softSerial.begin(9600);
#endif
servo[0].attach(2); //head
servo[1].attach(3); //pitch
servo[0].write(90);
servo[1].write(90);
prev_pwm[0] = 0;
prev_pwm[1] = 0;
delay(50);
}
void loop(void) {
serial_receive();
} // end loop()
void serialEvent() {
while (Serial.available() > 0 ) {
byte incomingByte = Serial.read();
if (incomingByte == 0x84) {
serialBuffer[dataBufferIndex++] = incomingByte;
remainingByte = 3;
} else if ( remainingByte > 0) {
serialBuffer[dataBufferIndex++] = incomingByte;
remainingByte--;
if ( remainingByte == 0) {
cmdComplete = true;
}
}
} // end while()
} // end serialEvent()
void serial_receive(void){
if (cmdComplete) {
if ( serialBuffer[0] == 0x84) {
int servo_no = serialBuffer[1];
int servo_val = serialBuffer[3];
servo_val = (servo_val<<7) + serialBuffer[2];
servo_val >>=2;
servo_val = servo_val/50*50;
#ifdef DEBUG
softSerial.print(servo_no);softSerial.print(" ");softSerial.println(servo_val);
#endif
setServo(servo_no, servo_val);
}
cmdComplete = false;
dataBufferIndex = 0;
} // endif
} // end serial_receive()
void setServo(int no, int val)
{
if ( no >=0 && no <= 1 && val >= 500 && val <= 2500) {
if ( abs(val-prev_pwm[no]) > 30) {
servo[no].writeMicroseconds(val);
prev_pwm[no] = val;
}
}
}
|
欢迎继续阅读楼主其他信息
|