2

I recently started a project with HC-SR04 sensors and RTC DS1302 clock. The idea is when a sensor detects an object, call and keep a timestamp (hh:mm:ss) all over the loop until Else If{} appears, but I don't know how to.

#include <DS1302.h>
#include <Time.h>
#include <TimeLib.h>
#define echoPin 12 // Echo Pin
#define trigPin 13 // Trigger Pin

time_t t = now();
DS1302 rtc(6,20,21);
String inTime;

void setup()
{
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop(){
    long duration, distance;
    digitalWrite(trigPin, LOW);  
    delayMicroseconds(2); 
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10); 
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;

   if (distance <= 4) { 
    inTime= rtc.getTimeStr();
    Serial.println(inTime);

    } 

    else if (distance >= 5 || distance <= 0){
    Serial.println("Out of range");

    }

  delay(500);
}

Appreciate any help, thanks.

1 Answer 1

1

Check '{' and '}' pairs in your code.

void loop(){
    long duration, distance;
    digitalWrite(trigPin, LOW);  
    delayMicroseconds(2); 
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10); 
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;
    if (distance <= 4) { 
        inTime= rtc.getTimeStr();
        Serial.println(inTime);

   } 
} //<--- what is this little fella doing here?
    else if (distance >= 5 || distance <= 0){
    Serial.println("Out of range");
    }

delay(500);
}
2
  • thanks, that's because my original code is too long and is normal miss or add some {} Commented Oct 18, 2017 at 0:37
  • 1
    Well, the machine will not accept your excuses. You must be precise here. Maybe you can try to split code into few files? Also, look at your 'distance' variable. Its type is 'long'. After line 'distance = (duration/2) / 29.1; ' you are loosing what is after comma. Commented Oct 18, 2017 at 7:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.