Go Down

Topic: New Class including a servo object ERROR ->Newbie problem (Read 513 times) previous topic - next topic

rgreenfi

Hi,

I am developing a sentry gun project. New to Arduino.

I am having a problem creating the Sentry class with two servo objects.

This simple code is suposed to bring both servos to value 90, but the servo's flicker uncontrollably. Using small SG90 servos, which work fine with other sketches where the objects are called directly inside the sketch.

Plz, help!

Main
Code: [Select]


#include "Sentry.h"

Sentry sentry(9,10,11);

void setup() {

}

void loop() {
     
  sentry.advance(90, 90);
  delay(1000);
  sentry.advance(0,0);
  delay(1000);                 
}



Sentry.h

Code: [Select]


    #ifndef SENTRY_H
    #define SENTRY_H
     
    #include <Arduino.h>
    #include <Servo.h>
    class Sentry {
    private:
            Servo servo_x;
            Servo servo_y;
            bool weapon_on;

    public:
            Sentry(int x_servo_pin, int y_servo_pin, int laser_pin);
            ~Sentry();
            void advance(int x,int y);
            void go_hot();
            void go_cold();
            void weapon_toggle();
    };
     
    #endif


Sentry.cpp
Code: [Select]
#include "Sentry.h"
    #include <Servo.h>
           
    Servo servo_x;
    Servo servo_y;
    int weapon_pin;
    bool weapon_on=false;
     
    //<<constructor>>
    Sentry::Sentry(int x_servo_pin, int y_servo_pin, int laser_pin){
          servo_x.attach(x_servo_pin);
          servo_y.attach(y_servo_pin);
          weapon_pin=laser_pin;
          weapon_on=false;
          pinMode(laser_pin, OUTPUT);
    }
     
    //<<destructor>>
    Sentry::~Sentry(){
        servo_x.detach();
        servo_x.detach();
      }
   
     void Sentry::advance(int x,int y){
        servo_x.write(x);
        servo_x.write(y);
           }
     
     void Sentry::go_hot(){
      weapon_on=true;
      digitalWrite(weapon_pin, HIGH); 
     }
     
     void Sentry::go_cold(){
       weapon_on=false;
      digitalWrite(weapon_pin, LOW);
     }
     
     void Sentry::weapon_toggle(){
      weapon_on=(!weapon_on);
      if (weapon_on==true) digitalWrite(weapon_pin, HIGH);
      else digitalWrite(weapon_pin, LOW);
     
     }

matty0997

In your main section of the code you haven't attached the servos to the pins that they are connect to on the arduino board this is done in the void setup section

PaulS

Add a #include statement to the sketch, to include the Servo.h file. You can NOT hide the fact that your library uses Servo.h from the sketch.
The art of getting good answers lies in asking good questions.

Go Up