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! ...
Get Arduino for Kids now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.