I need help to my code!

// defines pins numbers
const int trigPin = 11;
const int echoPin = 10;
const int relay1 = 5;
const int relay2 = 6;
// defines variables
long duration;
int distance;
long distancemm;

void setup() {
// put your setup code here, to run once:
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(relay1, OUTPUT);// Control Pin
pinMode(relay2, OUTPUT);
Serial.begin(9600); // Starts the serial communication
}

void loop() {
// put your main code here, to run repeatedly:
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
distancemm = distance * 10 + 30;

//Control

if (distancemm > 80 && distancemm < 160)
{
digitalWrite(relay1, HIGH);
digitalWrite(relay2, LOW);
}
else
{
if (distance > 160)
{
digitalWrite(relay1, LOW);
digitalWrite(relay2, HIGH);
} else
{
digitalWrite(relay1, LOW);
digitalWrite(relay2, LOW);

  {

  }

  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
  //Serial.print("Distance: ");
  Serial.print(distancemm);
  Serial.println("mm");
  delay(250);
}

1 Like

Hello,

No double posting please ! (you also posted I need help to my code)

do yourself a favour and please read How to get the best out of this forum and modify your post accordingly (including code tags and necessary documentation for your ask).