Devices & Components
Arduino Uno Rev3
Ultrasonic Sensor - HC-SR04 (Generic)
Jumper wires (generic)
Software & Tools
Arduino IDE
Project description
Code
processing code
processing
run this code on processing to plot the disatance
1import processing.serial.*; 2Serial myPort; 3String data="" ; 4PFont myFont; 5void setup() 6{ 7size(1366,900); // size of processing window 8background(0);// setting background color to black 9myPort = new Serial(this, "COM3", 9600); 10myPort.bufferUntil('\n'); 11} 12void draw() 13{ 14 background(0); 15 textAlign(CENTER); 16 fill(255); 17 text(data,820,400); 18 textSize(100); 19 fill(#4B5DCE); 20 text(" Distance : cm",450,400); 21 noFill(); 22 stroke(#4B5DCE); 23} 24void serialEvent(Serial myPort) 25{ 26 27 data=myPort.readStringUntil('\n'); 28}
Arduino code
arduino
upload the code into the arduino
1#include <Mouse.h> 2const int trigpin= 8; 3const int echopin= 7; 4long duration; 5int distance; 6void setup() 7{ 8 pinMode(trigpin,OUTPUT); 9 pinMode(echopin,INPUT); 10 Serial.begin(9600); 11 12} 13void loop() 14{ 15 digitalWrite(trigpin,HIGH); 16 delayMicroseconds(10); 17 digitalWrite(trigpin,LOW); 18 duration=pulseIn(echopin,HIGH); 19 distance = duration*0.034/2; 20 Serial.println(distance); 21}
processing code
processing
run this code on processing to plot the disatance
1import processing.serial.*; 2Serial myPort; 3String data="" 4 ; 5PFont myFont; 6void setup() 7{ 8size(1366,900); // size of processing 9 window 10background(0);// setting background color to black 11myPort = new Serial(this, 12 "COM3", 9600); 13myPort.bufferUntil('\ 14'); 15} 16void draw() 17{ 18 background(0); 19 20 textAlign(CENTER); 21 fill(255); 22 text(data,820,400); 23 textSize(100); 24 25 fill(#4B5DCE); 26 text(" Distance : cm",450,400); 27 28 noFill(); 29 stroke(#4B5DCE); 30} 31void serialEvent(Serial myPort) 32{ 33 34 35 data=myPort.readStringUntil('\ 36'); 37}
Arduino code
arduino
upload the code into the arduino
1#include <Mouse.h> 2const int trigpin= 8; 3const int echopin= 7; 4long 5 duration; 6int distance; 7void setup() 8{ 9 pinMode(trigpin,OUTPUT); 10 11 pinMode(echopin,INPUT); 12 Serial.begin(9600); 13 14} 15void loop() 16{ 17 18 digitalWrite(trigpin,HIGH); 19 delayMicroseconds(10); 20 digitalWrite(trigpin,LOW); 21 22 duration=pulseIn(echopin,HIGH); 23 distance = duration*0.034/2; 24 Serial.println(distance); 25}
Downloadable files
Circuit diagram
connect the sensor to the arduino board as shown in the picture
Circuit diagram

Comments
Only logged in users can leave comments