Author Options:

Need Help with a simple arduino code plz? Answered

HELLO instructables , i need help with writing an extra simple code over my arduino code that simply works with the arduino code i wrote , the description of what i want is very simple , 

I've got an ultra sensor i want if it reads a distance of less than or 10 cm it makes a red LED goes on.

I've this arduino code written so can u plz tell me what should code shall i write to work with it  ? 

#include <Servo.h>

#define trigPin 7

#define echoPin 6

Servo servo;

int sound = 250;

void setup() {

Serial.begin (9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);



void loop() {

long duration, distance;

digitalWrite(trigPin, LOW);


digitalWrite(trigPin, HIGH);


digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance = (duration/2) / 29.1;

if (distance < 10) {

Serial.println("the distance is less than 10");



else {



if (distance > 10 || distance <= 0){

Serial.println("The distance is more than 10");


else {


Serial.println(" cm");







2 years ago

Suggested tips:

1) Read code examples and try to understand how they work.

Start by looking at code examples that:

- blink a LED (for example: https://www.arduino.cc/en/Tutorial/Blink)

- code for your "ultra sensor". Reading your code, I suspect you are talking about an ultrasonic distance sensor here?

For example: https://create.arduino.cc/projecthub/silicon-ripley-10/distance-measurement-using-ultrasonic-sensor-and-arduino-9bacd4

2) read the code you posted, and try to determine at which line of code the LED needs to be turned on. And if the LED also needs to be turned off (e.g. if the distance is > 10 cm), then try to determine where this needs to be added. Hint: is something else already happening at the same time (then add the blinking LED code there)?

3) I am not sure why you have added servo code to your project? If your project does not include a servo, removing code regarding the servo will make it less complex.

If you do need a servo, you might want to try and write code without the servo first (or even code for the LED only, and for the sensor only). Likewise, you might want to blink the LED only first, and read the value for the sensor first. Once you understand these separatly, it will be easier to combine the programs.


Answer 2 years ago