I have the following sketch, I am powering the servo with 4 AA batteries at present. It worked for a bit via the 9v battery but no longer works when powered by the battery. The board is controlling 6 ultrasonic sensors and the servo. As stated the servo is not powered by the board. If I plug in the USB port to my computer the servo will work fine but not when connected to the 9v barrel connection
#include <Servo.h>
#define servoPin 15
#define maxAngle 80
#define minAngle 5
#define downDistance 30
#define sensorCount 6
struct Sensor
{
int id;
int trigPin;
int echoPin;
boolean isDown;
};
Sensor sensors[sensorCount] = {
{ 1, 12, 13, false},
{ 2, 10, 11, false},
{ 3, 8, 9, false},
{ 4, 6, 7, false},
{ 5, 4, 5, false},
{ 6, 2, 3, false}
};
long duration;
int distance;
int angle;
int downCount;
Servo servo;
/**
Checks the distance from the sensor to be less than 7cm
@param the sensor being checked
@param trigPin the trigger pin of the sensor being checked
@returns void
*/
void isDown(Sensor& sensor)
{
// Clears the trigPin condition
digitalWrite(sensor.trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(sensor.trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(sensor.trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(sensor.echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
Serial.print("ID: ");
Serial.print(sensor.id);
Serial.print(" Distance: ");
Serial.print(distance);
Serial.println(" cm");
if (distance < downDistance && distance != 0)
{
sensor.isDown = true;
downCount++;
}
else
{
sensor.isDown = false;
}
}
void setup() {
for (int i = 0; i < sensorCount; i++)
{
pinMode(sensors[i].trigPin, OUTPUT);
pinMode(sensors[i].echoPin, INPUT);
}
Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
angle = minAngle;
servo.attach(servoPin);
servo.write(angle);
downCount = 0;
}
void loop()
{
for (int i = 0; i < sensorCount; i++)
{
// Is Plate down?
if (!sensors[i].isDown)
{
isDown(sensors[i]);
delay(100);
}
}
if (downCount == sensorCount)
{
// wait 1 second to allow targets to settle
delay(1000);
// do one final check of all sensors to ensure no false sets
downCount = 0;
Serial.println("Final Check");
for (int i = 0; i < sensorCount; i++)
{
isDown(sensors[i]);
}
if (downCount == sensorCount)
{
Serial.println("MOTOR TIME");
// Yes, trigger servo
for (angle = minAngle; angle <= maxAngle; angle += 1)
{
servo.write(angle);
delay(15);
}
// wait 1 second to allow targets to settle
delay(1000);
// reset servo
for (angle = maxAngle; angle >= minAngle; angle -= 1)
{
servo.write(angle);
delay(15);
}
// reset values
downCount = 0;
for (int i = 0; i < sensorCount; i++)
{
sensors[i].isDown = false;
}
}
}
}