Arduino Ultrasonic Sensor pulseIn is only 3 or 4

468 Views Asked by At

What I am trying to do is to read the value pulseIn(ECHO, HIGH), so that I eventually can convert it to centimeters, so I know how far the ultrasonic sensor is from an object. However when I read the value printed in the Serial Monitor it is only 3 or 4 and it is with no regard to how far the ultrasonic sensor is from anything. I can't even see why it would be exactly these two values or why it changes between them. I cannot figure how to solve this problem or what can cause it. I don't know whether the problem is with the code or components. However, this sensor was recently tested by someone else and it worked then, so maybe it is just me who is doing something wrong. Help?

#define SPEAKER 11
#define TRIGGER 2
#define ECHO 3
#define SPLIT 40

unsigned long duration;

int alarm1()
{
  Serial.print("alarmtest");
  analogWrite(SPEAKER, 100);
  delay(100);
  analogWrite(SPEAKER, 0);
  delay(100);
  analogWrite(SPEAKER, 100);
  delay(100);
  analogWrite(SPEAKER, 0);
  delay(500);
}

void setup() 
{
  Serial.begin(9600);
  pinMode(SPEAKER, OUTPUT);
  pinMode(TRIGGER, OUTPUT);
  pinMode(ECHO, INPUT);
}

void loop() 
{       
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(50);
  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(50);
  digitalWrite(TRIGGER, LOW);
  duration = pulseIn(ECHO, HIGH);
  delay(200);

  Serial.print(duration);
  if (duration < SPLIT)
  {
   // alarm1();
  }
}
1

There are 1 best solutions below

0
On

It gave printed this as I by mistake had used the wrong ports. Problem solved. Be sure to check your connections after an extra time!