Obstacle Avoidance Robot (Pinky) – Part 2

Part 1 | Part 2 | Part 3 | Part 4 | Part 5

For an obstacle avoidance robot using an ultrasonic sensor (one sensor only), we can use a servo motor to do a rotation in angle. To do the rotation, we need a servo library. In Arduino IDE, there is a built-in function for servo, however, for the first time used, the library always reset my Maker Uno (I do not why! 🙂 ). Therefore, I have installed a new library (PWMServo). To do so, go to the Arduino IDE and click Sketch > Include Library > Manage Libraries and then search PWMServo.

//   Board                     SERVO_PIN_A   SERVO_PIN_B   SERVO_PIN_C
//   -----                     -----------   -----------   -----------
//   Arduino Uno, Duemilanove       9            10          (none)
//   Arduino Mega                  11            12            13
//   Sanguino                      13            12          (none)
//   Teensy 1.0                    17            18            15
//   Teensy 2.0                    14            15             4
//   Teensy++ 1.0 or 2.0           25            26            27
//   Teensy LC & 3.x                 (all PWM pins are usable)
#include <PWMServo.h>
#include <HCSR04.h>

PWMServo myservo;  // create servo object to control a servo

void setup() {
  Serial.begin(9600); 
  myservo.attach(SERVO_PIN_A);  // attaches the servo on pin 9 to the servo object
  Serial.println("Test Servo");
  myservo.write(90);            // Initial Position
  delay(500);
}

void loop() {
  myservo.write(90);            //90 
  delay(500);
  myservo.write(45);            //45 
  delay(500);
  myservo.write(0);             //0 
  delay(500);
  myservo.write(45);            //45 
  delay(500);
  myservo.write(90);            //90 
  delay(500);
  myservo.write(135);           //135 
  delay(500);
  myservo.write(180);           //180 
  delay(500);
  myservo.write(135);           //135 
  delay(500);
}