0

This is my Sketch or code:

const int EchoPin = 5;
const int TriggerPin = 6;
const int LedPin = 13; 

void setup() {
 Serial.begin(9600);
 pinMode(LedPin, OUTPUT);
 pinMode(TriggerPin, OUTPUT);
 pinMode(EchoPin, INPUT);
 pinMode(13, OUTPUT);
}

void loop() {
 int cm = ping(TriggerPin, EchoPin);
 Serial.print("Distancia: ");
 Serial.println(cm);
 delay(1000);
}

int ping(int TriggerPin, int EchoPin) {
 long duration, distanceCm;
 digitalWrite(TriggerPin, LOW);
 delayMicroseconds(4);
 digitalWrite(TriggerPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(TriggerPin, LOW);
 duration = pulseIn(EchoPin, HIGH);
 distanceCm = duration * 10 / 292/ 2;
 return distanceCm;
}

if (distanceCm <= 20) {
 digitalWrite(13, HIGH);
}

if (distanceCm >= 20) {
 digitalWrite(13, LOW);
}

The error appears in the second if.

  • 5
    Lean C syntax. Code goes in functions! – Majenko May 7 '18 at 19:56
1

The error is occurring because you have 2 if statements outside of a function. You could move them into the ping() function which would fix the error but there seems to be a logic error with the 2 if statements as well.

If distanceCm is 20, both if statements execute one right after another, so I doubt you'll see the LED turn on. Perhaps an if/else might work.

if(distanceCm < 21){
  digitalWrite(13, HIGH);
}
else{
  digitalWrite(13, LOW);
}
0

Error is because you close your ping method before the "if (distanceCm >= 20)" clausule. This is a correct code:

const int EchoPin = 5;
const int TriggerPin = 6;
const int LedPin = 13; 

void setup() {
 Serial.begin(9600);
 pinMode(LedPin, OUTPUT);
 pinMode(TriggerPin, OUTPUT);
 pinMode(EchoPin, INPUT);
 pinMode(13, OUTPUT);
}

void loop() {
 int cm = ping(TriggerPin, EchoPin);
 Serial.print("Distancia: ");
 Serial.println(cm);
 delay(1000);
}

int ping(int TriggerPin, int EchoPin) {
 long duration, distanceCm;
 digitalWrite(TriggerPin, LOW);
 delayMicroseconds(4);
 digitalWrite(TriggerPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(TriggerPin, LOW);
 duration = pulseIn(EchoPin, HIGH);
 distanceCm = duration * 10 / 292/ 2;
  if (distanceCm <= 20) {
 digitalWrite(13, HIGH);
}

if (distanceCm >= 20) {
 digitalWrite(13, LOW);
}
 return distanceCm;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.