Hi,
I'm trying to use the sonar example in the Arduino tutorial, new Ping >> New Ping Example, when using the sonar part HC-SR04. I'm trying to use C++ here. (I can make it run fine in C.)
My problem is that I cannot seem to get the code to run correctly with my class. When I try to run the code below, I get this error,
'sonar' was not declared in this scope
I was surprised, because I thought I was declaring it, as a type 'int'.
/*
- Gets the distance an object is from the sonar, and sets it to variable 'distance'
- This variable can then be used in computations and for instructions for the robot to do something
- or to send it to a seperate device
*/
#include <NewPing.h> // sonar library
class Sonar
{
public:
void Sonar_Setup()
{
#define TRIGGER_PIN 20 // Arduino trigger pin on sonar
#define ECHO_PIN 21 // Arduino echo pin on sonar
#define MAX_DISTANCE 200 /* Maximum distance we want to ping for (in centimeters).
Maximum sensor distance is rated at 400-500cm. */
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
}
void Sonar_Reading(double distance)
{
delay(50); // Wait 50ms between pings (~ 20 pings/sec). 29ms should be min delay between pings
Serial.print("Distance: ");
Serial.print(distance); // units are in inches
Serial.println("in");
}
private:
int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS) // units are converted from cm to inches
double distance = ((uS / US_ROUNDTRIP_CM) / 2.54); // Convert ping time to distance, 0 = outside set distance range
// units are converted from cm to inches
};
// CLASS SETUP, FORM: ( Class [space] Object )
Sonar sonar_function;
void setup()
{
Serial1.begin(9600); // Open Serial1 monitor at 9600 baud to see ping results.
sonar_function.Sonar_Setup();
}
void loop()
{
sonar_function.Sonar_Reading(distance);
}
I image that's not my only issue, but I have to start somewhere. Any ideas?