ive been working on this code (not written entirely by me) and for some reason cant figure out how to change the distance threshold and have it actually work
const int TRIG_PIN = 6;
const int ECHO_PIN = 7;
const int LED_PIN = 3;
const int LED_PIN2 = 0;
const int DISTANCE_THRESHOLD1 = 50;
const int DISTANCE_THRESHOLD2 = 150;
// variables will change:
float duration_us, distance_cm;
void setup() {
Serial.begin (9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(LED_PIN2, OUTPUT);
}
void loop() {
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration_us = pulseIn(ECHO_PIN, HIGH);
distance_cm = 0.017 * duration_us;
if(distance_cm < DISTANCE_THRESHOLD1)
digitalWrite(LED_PIN, HIGH);
else
digitalWrite(LED_PIN2, LOW);
if(distance_cm < DISTANCE_THRESHOLD2)
digitalWrite(LED_PIN2, HIGH);
else
digitalWrite(LED_PIN, LOW);
Serial.print("distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
delay(500);
}
titans_eye.ino (1.24 KB)
aarg
July 14, 2020, 1:34am
#2
Is this sketch the working or non-working one? What is wrong with the non-working one, exactly? How does it not meet your expectations?
the first trigger distance works but I cant change the distance for some reason and the second one just doesn't work
aarg
July 14, 2020, 1:49am
#4
What do you mean, you "can't change the distance"? Do you mean the reported distance value? What happens when you try? Please be more specific in your answers. Also again "just doesn't work"... you can be more specific too, example "there is no output".
to clairify I am having truble changing the const int DISTANCE_TRESHOLD and whatever I do it only triggers below 50 even if I change the value
aarg
July 14, 2020, 2:31am
#6
Okay. Have you tried the same hardware, with simple example test sketches other than the one above?
aarg
July 14, 2020, 2:38am
#7
Did you intend for LED to represent value < thresh1 and LED2 to represent value < thresh2?
If so, you have typos reversing LED_PIN and LED_PIN2 in your logic, so that wouldn’t happen.
In other words,
if (distance_cm < DISTANCE_THRESHOLD1)
digitalWrite(LED_PIN, HIGH);
else
digitalWrite(LED_PIN2, LOW);
should be
if (distance_cm < DISTANCE_THRESHOLD1)
digitalWrite(LED_PIN, HIGH);
else
digitalWrite(LED_PIN, LOW);