I would like to create an array of a generic type so I can use multiple sensors and make my code as extensible as possible.
/*
Planning for good design. Agent library
should be able to use more than one sensor.
The agent's constructor will accept a vector
of sensors.
*/
class Sensor
{
public:
Sensor(){};
};
My implementation class
#include "Arduino.h"
class UltraSonicSensor: public Sensor {
public:
/*
Constructors
*/
UltraSonicSensor(){};
UltraSonicSensor(int pin){
pin_ = pin;
};
int Sense(){ return 20;};
/*
Measure Distance
*/
float DistanceMeasure(void);
private:
/*
Class only suppports Metric
*/
float microseconds_to_centimeters(void);
int pin_;
long duration_;
};
#endif // SROBOT_SENSORS_ULTRASONIC_H_
I have tried many, many variations of this code but always the same error
Sensor *sensors[2];
UltraSonicSensor uSensor;
sensors[0] = &uSensor;
void setup(){
Serial.begin(9600);
}
void loop(){
Serial.println("starting...");
delay(1000);
Serial.println("ok");
// delay(2000);
// for (int i = 0; i < sensors.size(); i++) {
//// sensors[i].Sense();
// }
}
The error is always a variation of
main:10: error: 'sensors' does not name a type
sensors[0] = &uSensor;
^
exit status 1
'sensors' does not name a type
I also used the code for a small replacement vector
class but also the same error
2 Answers 2
You have to do it inside of function:
Sensor *sensors[2];
UltraSonicSensor uSensor;
void setup(){
Serial.begin(9600);
sensors[0] = &uSensor;
}
Or directly:
UltraSonicSensor uSensor;
Sensor *sensors[] = {&uSensor};
Don't forget to make method Sense()
virtual in the base class and in the inherited classes. Otherwise you'll have to also find out the type of the object and typecast it to correct class pointer before it's use.
class Sensor
{
public:
virtual int Sense() = 0; // pure virtual base class
};
// and inherited class:
class UltraSonicSensor: public Sensor {
public:
// ...
// Prototype must be exactly the same, by using override
// is ensured it actually overrides something from the parent class.
virtual int Sense() override {
// ...
}
// ...
}
Also the last versions of Arduino IDE
supports C++11
standard so you can use range based for
loop:
for (Sensor * sensor : sensors) {
int val = sensor->Sense();
// ...
}
-
excellent! Thank you very much the clarification. Tried it just now and it worksSam Hammamy– Sam Hammamy2016年09月23日 20:07:13 +00:00Commented Sep 23, 2016 at 20:07
Based on the answer from @KIIV and the Vector class, the below code compiles successfully
#include "Vector.h"
#include "Sensor.h"
#include "UltraSonicSensor.h"
#include "LaserSensor.h"
Vector<Sensor*> sensors;
UltraSonicSensor uSensor;
LaserSensor lSensor;
void setup(){
sensors.push_back(&uSensor);
sensors.push_back(&lSensor);
}
void loop(){
Serial.println("starting...");
delay(1000);
for (int i = 0; i < sensors.size(); i++) {
int val = sensors[i]->Sense();
// ...
}
}