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 value of our distance sensor. To check if your hand is close, use an if
conditional statement along with a lesser than (<
) relational operator. Thus, if an object is...