Led remains turned on... Help

Hello there!

I have wrote a program for my robot that uses distance sensors and i want it so that when the something is detected the led turns on and when not its low… However with my current program the led remains lit no matter what i do.

Snippet of code including led:

 if(distance < 7 && distance > 0 ){
     digitalWrite(led, HIGH);
     motor.write(90);
     
  }else{    
    digitalWrite(led, LOW); 
      if (Sped == 100){
        motor.write(30);
      }else{
        motor.write(90);
      }
  }

entire code:

#include <Servo.h>
#define trig 12
#define echo 13
#define led 10

Servo myServo, motor; 
String pos;
String sped;
String readString;


void setup(){
  
 Serial.begin(19200);
 myServo.attach(10);
 motor.attach(9);
 pinMode(trig, OUTPUT);
 pinMode(echo, INPUT);
 pinMode(led, OUTPUT);
 digitalWrite(led, LOW);
 
}

void loop(){
  
  int duration, distance;
  
  
 digitalWrite(trig, LOW);
  delayMicroseconds(5);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);

  duration = pulseIn(echo, HIGH);
  distance = duration/58.2;
  
  if (Serial.available())  {
    char c = Serial.read();  //gets one byte from serial buffer
    if (c == '*') {
      //do stuff



      int ind1 = readString.indexOf(',');  //finds location of first ,
      pos = readString.substring(0, ind1); 
      int ind2 = readString.indexOf(',', ind1+1);
      sped = readString.substring(ind1+1, ind2);
      
      int Pos = pos.toInt();
      int Sped = sped.toInt();
      
      
      
      if (Pos == 125){
      Pos = 90;
      }else if( Pos > 125){
      Pos = map(Pos, 126, 225, 90, 160);
      }else if ( Pos < 125){
      Pos = map(Pos, 124, 30, 90, 20);
      }else;
      Pos = Pos;
      
      myServo.write(Pos);
      
  if(distance < 7 && distance > 0 ){
     digitalWrite(led, HIGH);
     motor.write(90);
     
  }else{    
    digitalWrite(led, LOW); 
      if (Sped == 100){
        motor.write(30);
      }else{
        motor.write(90);
      }
  }
      
      
      readString = "";
      pos = "";
      sped = "";
      
    }else{
      readString += c;
      
    }
  }
  
}

If someone could idicate to me why it might be staying on that would be much apreciated!

Also the wiring is correct because i did some simple programs to test it and its fine.

Hello,

  • deleted my stupid comment, sorry I'm tired :D -

Hahaha i didn't even see it so don't worry!

lele_gricc: Hahaha i didn't even see it so don't worry!

That's not fair. Whenever I make a stupid comment, EVERYONE sees it before I realise.

And I'm quite frequently "tiered" ;)

Hahaha sucks....

But anyways i solved the problem

I attached myServo and the led to the same pin in the software.... ::)

lele_gricc: I attached myServo and the led to the same pin in the software.... ::)

Sounds like you're "tired" too :)