Go Down

Topic: NEW TO ARDUINO, NEED HELP WITH SIMPLE PROJECT.PLEASE :( (Read 329 times) previous topic - next topic


Jan 13, 2019, 06:36 am Last Edit: Jan 13, 2019, 09:18 am by Coding Badly
I am currently learning Arduino and I just need help with the sketch I made for a program that uses ultra sonic sensor(HC-SR04) that has 2 LEDs where 1st LED lights if the object is atleast 2 cm away and 2nd LED lights if the object is 2cm beyond

the problem is that the monitor always reads 0 distance and both LEDs light up.

sorry for bad english, not my first language :)

Here's my code.
Code: [Select]

const int trigPin = 9;
const int echoPin = 10;
const int led1 = 11;
const int led2 = 12;

long duration;
int distance;

void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

void loop() {
digitalWrite(trigPin, LOW);
digitalWrite(trigPin, HIGH);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;

if( distance < 2.0 ){

Serial.print("Distance: ");

Moderator edit: [code] [/code] tags added.


I am using HC-SR04 ultrasonic sensor for my project and whenever I run it, the reading on serial monitor has an interval of 0 like on the picture.

Is my sensor broken or is it with the wirings or sketch? help :(



Are you wanting to pay someone to help you with this problem? The reason I ask is because that's what this forum section is for.

Please use code tags (</> button on the toolbar) when you post code or warning/error messages. The reason is the forum software can interpret parts of your code as markup, leading to confusion, wasted time, and a reduced chance for you to get help with your problem. This will also make it easier to read your code and to copy it to the IDE or editor. If your browser doesn't show the posting toolbar, then you can manually add the code tags:
[code]// your code is here[/code]
Using code tags and other important information is explained in the How to use this forum post. Please read it.

Please always do an Auto Format (Tools > Auto Format in the Arduino IDE or Ctrl + B in the Arduino Web Editor) on your code before posting it. This will make it easier for you to spot bugs and make it easier for us to read.


You already have a forum thread for this:
Please don't post multiple times about the same thing.


I do not understand how the code you have shown could have generated the output you have linked appears to show time in HH:MM:SS format with milli seconds added and also, and every alternate Distance is something other than the zero which you claim in your posts.

Go Up