I am trying to use the servo library inside a class so that I can make mutiple instances of my class with each one using a different servo pin. I can figure out how to do this without getting scope errors in the code. The three files and are below and they are all in an attached zip file.
MyOBstacle.ino
#include <Wire.h>
#include "obstacle.h"
OBSTACLE c(11);
/*****************************************************************************/
void setup()
{
Wire.begin();
Serial.begin(115200);
while (!Serial);
delay(250);
}
/*****************************************************************************/
void loop()
{
}
obstacle.cpp
#include <arduino.h>
#include "Obstacle.h"
#include <VL53L0X.h>
#include <Servo.h>
VL53L0X tof;
const int CENTER = 88;
const int SPEED = 150;
const int SCANMAX = CENTER + 50;
const int SCANMIN = CENTER - 50;
const int MIN_DISTANCE = 400;
const int LEFT = 0;
const int RIGHT = 1;
const int STRAIGHT = 2;
int OBSTACLE::GetPos()
{
return _pos;
}
void OBSTACLE::SetPos(int p)
{
_pos = p;
}
int OBSTACLE::GetDist()
{
return _dist;
}
int OBSTACLE::GetDir()
{
return _dir;
}
OBSTACLE::OBSTACLE(int servoPin)
{
Servo srv;
srv.attach(servoPin);
// tof.setAddress(0x29);
// tof.setTimeout(100);
// if (!tof.init())
// {
// Serial.println("Failed to detect and initialize sensor!");
// while (1);
// }
// tof.startContinuous();
}
boolean OBSTACLE::Tick()
{
static int p;
int incDec = 4;
int mm = 0; // = tof.readRangeContinuousMillimeters(); // get the distance
//
// if (tof.timeoutOccurred())
// Serial.print(" TIMEOUT");
//
// Serial.print(mm); // print the distance
p += incDec; // inc or dec depencing on value of incDec
if (p > SCANMAX) // if we exceed the max
{
p = SCANMAX; // set it to the max
incDec = -4; // start decrimenting
}
if (p < SCANMIN) // if we are below min
p = SCANMIN; // start incrementing
incDec = 4;
OBSTACLE::SetPos(p); // set the next servo position
srv.write(p); // move the servo
_pos = p; // set pos
_dist = mm; // set Dist
if (_pos < 90) // set dir left or right
_dir = LEFT;
else
_dir = RIGHT;
if (mm < MIN_DISTANCE) // is there an obstacle?
return true;
else
return false;
}
obstacle.h
#ifndef OBSTACLE_H
#define OBSTACLE_H
#include <arduino.h>
class OBSTACLE
{
private:
int _pos;
int _dist;
int _dir;
public:
int GetPos();
void SetPos(int p);
int GetDist();
int GetDir();
OBSTACLE(int servoPin);
boolean Tick();
};
#endif
MyObstacle.zip (1.5 KB)