Greetings,
I am experimenting with a sonic proximity sensor and I am using some demo code from the internet. The original demo project had a servo, that is why you will see a deg variable. Here is the code:
#define TRIG_PIN A0
#define ECHO_PIN A1
#include <NewPing.h>
#define MAX_DISTANCE 300
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);
char dist[3];
String output = "";
void setup() {
pinMode (TRIG_PIN, OUTPUT);
pinMode (ECHO_PIN, INPUT);
Serial.begin(9600);
Serial.println("===== Ultrasonic sonar =====");
}
void loop() {
// scan right to left
for (int deg = 10; deg < 170; deg+=5) {
//myServo.write(deg);
delay(300);
displaySonar();
}
// scan left to right
for (int deg = 170; deg > 10; deg-=5) {
//myServo.write(deg);
delay(300);
displaySonar();
}
}
void displaySonar() {
int distance = sonar.ping_cm();
delay(30);
if (distance < 0) distance = 0;
sprintf(dist,"%3d",distance);
Serial.print("Range:");
Serial.print(dist);
Serial.print("cms/");
for (int dloop = 0; dloop < distance/4; dloop++) {
Serial.print("-");
}
Serial.println("=");
}
This code works and is printing:
===== Ultrasonic sonar =====
Range: 43cms/----------=
Range: 0cms/=
Range: 0cms/=
Range: 0cms/=
Range: 42cms/----------=
Range: 42cms/----------=
........
The problem I encounter is when I want to remove the loops (I have no servo and I want to use the sensor part of the demo only)
#define TRIG_PIN A0
#define ECHO_PIN A1
#include <NewPing.h>
#define MAX_DISTANCE 300
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);
char dist[3];
String output = "";
void setup() {
pinMode (TRIG_PIN, OUTPUT);
pinMode (ECHO_PIN, INPUT);
Serial.begin(9600);
Serial.println("===== Ultrasonic sonar =====");
}
void loop() {
delay(300);
displaySonar();
}
void displaySonar() {
int distance = sonar.ping_cm();
delay(30);
if (distance < 0) distance = 0;
sprintf(dist,"%3d",distance);
Serial.print("Range:");
Serial.print(dist);
Serial.print("cms/");
for (int dloop = 0; dloop < distance/4; dloop++) {
Serial.print("-");
}
Serial.println("=");
}
After this, I only get this output:
===== Ultrasonic sonar =====
===== Ultrasonic sonar =====
===== Ultrasonic sonar =====
===== Ultrasonic sonar =====
===== Ultrasonic sonar =====
===== Ultrasonic sonar =====
===== Ultrasonic sonar =====
===== Ultrasonic sonar =====
.........
Why is this looping the setup()? Why does removing the loops break the program? How do I fix this.
Frankly, I have no idea.
Some help, please?