I have designed and built a small educational robot using and Arduino Nano and a Nano servo Shield (HiLetgo 5pcs Nano I/O Expansion Sensor Shield). I am using 4 MG90 360degree servos for the wheel motors. Power is supplied to the board via a rechargeable 9v battery pack.
In my code, a speed value of 90 is full stop. I program the servos to drive forward or backward by adding or subtracting a value of +/- 90 (closer to 0 or 180, the faster it turns). However, If I ever go above a total of 130 or below 50 the nano resets. Any ideas?
#include <Servo.h>
Servo FrontLeftServo;
Servo FrontRightServo;
Servo BackLeftServo;
Servo BackRightServo;
const int FrontRightServoPin = 5;
const int FrontLeftServoPin = 4;
const int BackRightServoPin = 7;
const int BackLeftServoPin = 8;
const int echoPin = A1;
const int trigPin = A0;
const int MaximumRange = 30; //Value in centimeters
const int MinimumRange = 0;
long Duration, Distance;
const int BuzzerPin = 2;
void setup() {
FrontRightServo.attach (FrontRightServoPin);
FrontRightServo.write(90);
FrontLeftServo.attach (FrontLeftServoPin);
FrontLeftServo.write (90);
BackRightServo.attach (BackRightServoPin);
BackRightServo.write(90);
BackLeftServo.attach (BackLeftServoPin);
BackLeftServo.write (90);
pinMode (BuzzerPin, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Wait();
}
void loop() {
// put your main code here, to run repeatedly:
CheckObstacles();
if (Distance > 15)
{
Forward();
}
if (Distance < 14)
{
Stop();
delay(500);
Backward();
delay(1000);
turnRight();
delay(400);
}
}
void Stop() {
FrontLeftServo.write(90);
FrontRightServo.write(90);
BackLeftServo.write(90);
BackRightServo.write(90);
}
void Forward() {
FrontLeftServo.write(90 + 50);
FrontRightServo.write(90 - 50);
BackLeftServo.write(90 + 50);
BackRightServo.write(90 - 50);
}
void Backward() {
FrontLeftServo.write(90 - 50);
FrontRightServo.write(90 + 50);
BackLeftServo.write(90 - 50);
BackRightServo.write(90 + 50);
}
void turnRight() {
FrontLeftServo.write(90 + 50);
FrontRightServo.write(90 + 50);
BackLeftServo.write(90 + 50);
BackRightServo.write(90 + 50);
}
void turnLeft() {
FrontLeftServo.write(90 - 50);
FrontRightServo.write(90 - 50);
BackLeftServo.write(90 - 50);
BackRightServo.write(90 - 50);
}
void Wait() {
Buzz();
delay(2000);
Buzz();
delay(2000);
Buzz();
delay(2000);
}
void Buzz() {
digitalWrite (BuzzerPin, HIGH);
delay (90);
digitalWrite (BuzzerPin, LOW);
}
//Use Ultrasonic Range Finder to check for obstacles
void CheckObstacles() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
Duration = pulseIn(echoPin, HIGH);
Distance = (Duration / 2) / 29.1; // Get Distance
delay(10);
}
