Part 1 | Part 2 | Part 3 | Part 4 | Part 5
Ultrasonic sensor (HC-SR04) is the most important part in an obstacle avoidance robot. Before we can used the HC-SR04, we need to include the library. To do so, go to the Arduino IDE and click Sketch > Include Library > Manage Libraries and then search SR04 from gamegine.
#include <PWMServo.h> #include <HCSR04.h> HCSR04 hc(4,7); // initialisation class HCSR04 (trig pin , echo pin) PWMServo myservo; // create servo object to control a servo float distance; void setup() { Serial.begin(9600); myservo.attach(SERVO_PIN_A); // attaches the servo on pin 9 to the servo object Serial.println("Test Ultrasonic + Servo Fix 90 Degree"); myservo.write(90); delay(500); } void loop() { distance = hc.dist(); Serial.print(distance); Serial.println("CM"); delay(1000); }