Skip to content

Instantly share code, notes, and snippets.

@DeadlyCore
Created June 15, 2020 12:46
Show Gist options
  • Save DeadlyCore/34fa1ba9d146e272adacef8b8cadf602 to your computer and use it in GitHub Desktop.
Save DeadlyCore/34fa1ba9d146e272adacef8b8cadf602 to your computer and use it in GitHub Desktop.
// only 1 sensor to test
const int led = 8;
const int echo = 3;
const int trig = 2;
const long wait = 1000; //cooldown time for the sensor
unsigned long last = 0;
int spots = 4; // the number im trying to update each time the sensors are triggered
int distance;
long duration;
void setup() {
Serial.begin (9600);
pinMode(trig, OUTPUT); // Sets the trigPin as an Output
pinMode(echo, INPUT); // Sets the echoPin as an Input
pinMode(led, OUTPUT);
}
void loop() {
unsigned long timePassed = millis();
// Write a pulse to the HC-SR04 Trigger Pin
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
// Measure the response from the HC-SR04 Echo Pin
duration = pulseIn(echo, HIGH);
// Determine distance from duration
// Use 343 metres per second as speed of sound
distance = (duration / 2) * 0.0343;
// Send results to Serial Monitor
if (distance <= 20) {
if (timePassed - last >= wait){ // im trying to have a 1 second delay here without using the delay function soo that 2 sensors could be triggered at once
Serial.print(distance);
Serial.println(" cm");
digitalWrite (led, HIGH);
last = timePassed;
spots += 1;
Serial.print(spots);
Serial.println(" Spots Left");
}
}
else {
digitalWrite (led, LOW);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment