Hi,
I'm Building a quadcopter using 4 brushless motors (Radio Control Planes, Drones, Cars, FPV, Quadcopters and more - Hobbyking). These can be controlled by the Servo library but due to the library being incompatible with VirtualWire (radiocontrol), I'm using the ServoTimer2 library instead.
Following the normal procedure I'm able to make the motor spin with a simple code:
#include <ServoTimer2.h>
#include <VirtualWire.h>
ServoTimer2 _servo;
void setup() {
Serial.begin(9600);
_servo.attach(12);
_servo.write(2000); // Im using a scale from in the interval 1200 - 2000
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
}
void loop()
{
if(Serial.available() > 0)
{
char incomingChar = Serial.read();
if(incomingChar == '1')
{
_servo.write(2000); // Maximum power
digitalWrite(13, HIGH);
} else if(incomingChar == '0') {
_servo.write(1200); // Minimum power
digitalWrite(13, LOW);
}
}
}
This all works as expected. However when I try to put it into a class, nothing happens. The program compiles without warnings and I can see the onboard LED change state upon my requests:
#include <ServoTimer2.h>
class Motor
{
private:
ServoTimer2* _servo;
public:
Motor(int pin)
{
_servo = new ServoTimer2();
_servo->attach(pin);
setSpeed(0);
}
// Hvor speed er et tal mellem 0 - 100
void setSpeed(int speed)
{
// Accelerer ligeså stille
speed = min(100, max(0, speed));
speed = map(speed, 0, 100, 1200, 2000); // Look at http://forum.arduino.cc/index.php/topic,21975.0.html for specification
_servo->write(speed);
}
};
Motor m1(12);
void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
digitalWrite(13, LOW);
m1.setSpeed(0);
}
void loop() {
if(Serial.available() > 0)
{
char incomingChar = Serial.read();
if(incomingChar == '0')
{
m1.setSpeed(0);
digitalWrite(13, LOW);
} else if(incomingChar == '1'){
m1.setSpeed(100);
digitalWrite(13, HIGH);
}
}
}
I'm not used to coding in C++ so my attempt with the pointer is probably wrong, however removing the pointer and using it exactly like the m1 object does not work either. What am I doing wrong?
Best regards
Morten