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

Say hello to my little friend!

Now we have everything we need to know to start building our project. Let's start by writing the code:

#include <NewPing.h> 
  
int ledPin=10; 
int trigPin=8; 
int echoPin=9; 
 
NewPing sonar(trigPin, echoPin); 
  
 
void setup() { 
 
pinMode(ledPin,OUTPUT); 
 
} 
 
void loop() { 
  delay(50); 
  int dist = sonar.ping_cm(); 
  if (dist < 15) 
digitalWrite(ledPin,HIGH); 
    else 
         digitalWrite(ledPin,LOW); 
          
} 

Like before, we start by storing the pin numbers in variables, so that it doesn't become confusing, and then initialize our LED pins for output. The code consists of a simple if statement that checks if an object is closer than 15cm, and if it is, lights up our LED's. If not, it turns our LED's off.

Now that our code is ready, let's build our project! ...

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