I'm building a "turret" (a webcam mounted on a servo), that communicates with Processing to find an AR marker taped to a stand, and rigged to a DC motor that kicks the stand over when the user "fires" the turret at the marker. (There's a pic here). The user uses a Leap Motion to rotate the turret, with Processing writing the angle the servo needs to be at over USB.
This works fine, but I want to expand the set-up with a second DC motor that runs continuously, instead of the short burst of the first DC motor. The problem is that while the second motor is running, the servo is twitching heavily. At first I thought it was a problem with the power supply, so I hooked up a second 9V battery for the servo only; this did not fix the problem. I searched around the internet and these forums, but I haven't found a solution yet. Here's hoping some of you know what I'm doing wrong!
The Arduino code:
//Software servo library to prevent serial communication mishaps
#include <SoftwareServo.h>
const int SERVO_PIN = 9;
const int MARKER_MOTOR_PIN = 5;
const int GUNS_MOTOR_PIN = 3;
String _serialBuffer;
SoftwareServo _servo;
//For kicking over the marker
boolean _isKicking;
int _timeOfKick;
const int KICK_TIME = 100;
void setup()
{
Serial.begin(9600);
pinMode(SERVO_PIN, OUTPUT);
pinMode(MARKER_MOTOR_PIN, OUTPUT);
pinMode(GUNS_MOTOR_PIN, OUTPUT);
_servo.attach(SERVO_PIN);
}
void loop()
{
_servo.refresh();
while(Serial.available() > 0)
{
int character = Serial.read();
if(character == '\n') //string complete
{
setTurretPosition(_serialBuffer.toInt());
_serialBuffer = "";
}
else if(character == 'A' && !_isKicking)
{
_isKicking = true;
_timeOfKick = millis();
analogWrite(MARKER_MOTOR_PIN, 150);
}
else if(character == 'B') //Start guns
analogWrite(GUNS_MOTOR_PIN, 100);
else if(character == 'C') //Stop guns
analogWrite(GUNS_MOTOR_PIN, 0);
else
_serialBuffer += char(character); //Add angle digit to buffer
}
//Disable DC motor after time
if(_isKicking && _timeOfKick + KICK_TIME < millis())
{
_isKicking = false;
analogWrite(MARKER_MOTOR_PIN, 0);
}
}
void setTurretPosition(int angle)
{
_servo.write(angle);
}