Servo turn opposite direction

hi forum. i was able to track the object coordinate in the screen/lcd based on color and plan to direct the middle camera attached to pantilt arm every time the object moves. but the result is the horizontal servo always run to opposite direction of the x coordinate of the object. thank for any help


void setup() {
  size(640, 480);
  servos = new PCA9685("i2c-1", 0x40);
  servos.attach(0);// horizontal servo
  servos.write(90); // midle position of the servo
  
  video = new Capture(this, width, height);
  video.start();
  trackColor = color(250, 0, 0);
}

void captureEvent(Capture video) {
  // Read image from the camera
  video.read();
}

void draw() {
  video.loadPixels();
  image(video, 0, 0); 

  // Before we begin searching, the "world record" for closest color is set to a high number that is easy for the first pixel to beat.
  float worldRecord = 500; 

  // XY coordinate of closest color
  int closestX = 0;
  int closestY = 0;

  // Begin loop to walk through every pixel
  for (int x = 0; x < video.width; x ++ ) {
    for (int y = 0; y < video.height; y ++ ) {
      int loc = x + y*video.width;
      // What is current color
      color currentColor = video.pixels[loc];
      float r1 = red(currentColor);
      float g1 = green(currentColor);
      float b1 = blue(currentColor);
      float r2 = red(trackColor);
      float g2 = green(trackColor);
      float b2 = blue(trackColor);

      // Using euclidean distance to compare colors
      float d = dist(r1, g1, b1, r2, g2, b2); // We are using the dist( ) function to compare the current color with the color we are tracking.

      // If current color is more similar to tracked color than
      // closest color, save current location and current difference
      if (d < worldRecord) {
        worldRecord = d;
        closestX = x;
        closestY = y;
      }
    }
  }

  if (worldRecord < 10) { 
    // Draw a circle at the tracked pixel
    fill(trackColor);
    strokeWeight(4.0);
    stroke(0);
    ellipse(closestX, closestY, 16, 16);
    float mX = map(closestX, 0,640, 1,179);
    int MX = round(mX);
  
   servos.write(0,MX);
  }
}

servos.write(0,-MX); ???

still not work. i am using IO library incorporate PCA9685 library and the error said the servo only work ranging 0-180

so, in your sketch you have 0…180 but the servo behaves as if 180…0 are the values?

You can use a variable and say

float valueForServo = map (initialValue, 0,180,180,0);

here you reverse the two ranges

1 Like

Hello,

References:
About Standard Servo Motors | Make it Move with Crickit | Adafruit Learning System

You may need to start at 180 and go to 0.

:)

You can also subtract it from 180:

:)

2 Likes