O'Reilly logo

Arduino for Kids by Vijay Varada, Rishi Gaurav Bhatnagar, Priya Kuber

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

High five!

Now you have everything you need to create your High-fiving robot!

We will use the ultrasonic proximity sensor we used in the previous chapter, along with conditional statements and relational operators to get everything working the way it should:

#include <NewPing.h> 
#include <Servo.h>  
  
 
NewPing sonar(2, 3); 
Servo myservo; 
  
void setup() { 
myservo.attach(9); 
} 
  
void loop() { 
  int dist = sonar.ping_cm(); 
  if (dist<15) 
  { 
    myservo.write(90); 
    delay(1000); 
  } 
  else  
  { 
    myservo.write(0); 
    delay(1000); 
  } 
} 

We begin by including the necessary libraries, our ultrasonic library, and the Servo library and initialize objects: sonar and myservo respectively. We attach our ultrasonic sensor to pins 2 and 3 of our Arduino and the servo to pin 9.

We then read the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required