Using C++ with a Sensor

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?

I was surprised, because I thought I was declaring it, as a type 'int'.

Where?

The only "sonar" is declared inside a function, where it is out of scope in all other functions.

AWOL:
Where?

The only "sonar" is declared inside a function, where it is out of scope in all other functions.

Ok, I think I see what you mean. But I'm uncertain how to fix this, as I've tried a few different ideas with no luck. I learned how to create my own defined functions in classes, but not yet altering those previous made.

Got a suggestion how I can fix this?

Got a suggestion how I can fix this?

Create the instance of sonar in the proper scope - typically global.

Ok, I was able to get my code running with some small modifications. Basically, I had to move these 3 lines all into the public part of the class:

       NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.                         
       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  */

However, I would have thought that these lines should be in the private domain, but the program started telling me errors for each one of them. They seem like they should be in private because they are variables related only to the sonar.

Is this thinking correct? How would I modify my code if so?

Here is the working code:

/*
   -  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()  // run at setup once
    {
         #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. */
    }
    
  void Sonar_Reading() 
    {
       NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.                         
       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  */
      
        Serial.print("Distance: ");
        Serial.print(distance);      // units are in inches
        Serial.println("in");
        
        delay(50);    // Wait 50ms between pings (~ 20 pings/sec). 29ms should be min delay between pings
    }

  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();  // define sonar pin setup
}

void loop() 
{
  sonar_function.Sonar_Reading();   
}
  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
  */

You can’t initialize member of a class that way.

  void Sonar_Reading() 
    {
       NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

Creating a new instance of the class every time you need a reading is wasteful. Like getting a new dog every time it’s feeding time.

  void Sonar_Setup()  // run at setup once
    {
         #define TRIGGER_PIN  20  // Arduino trigger pin on sonar
         #define ECHO_PIN     21  // Arduino echo pin on sonar
         #define MAX_DISTANCE 200

#define statements do not belong in functions. The scope is NOT limited to the function.