// a program to drive to servomotors using the the X and Y position of 1 object with an arduino uno
#include <SPI.h>
#include <Pixy.h>
#include <Servo.h>
Pixy pixy; //pixy-object for detection of the object
Servo myServoX; //servo-object for motor X which positions according to the X-position
Servo myServoY; //servo-object for motor Y which positions according to the Y-position
int PositionXmotor; //integervalue from 544 to 2400 to position X-motor
int PositionYmotor; //integervalue from 544 to 2400 to position Y-motor
void setup()
{
myServoX.attach(3, 544, 2400); //motor 1 is controlled by PWM-signal on output 3
myServoY.attach(5, 544, 2400); //motor 2 is controlled by PWM-signal on output 5
}
void loop()
{
uint16_t blocks; //typicle pixycode
blocks = pixy.getBlocks(); //typicle pixycode
if (blocks!=0) //testing if pixy detected any objects
{ //this is executed if an object is detected
PositionXmotor=544+int(float(pixy.blocks[0].x)/3191856); //The x-position ranges from 0 tot 319. 0 will be equivalent to a Xmotorposition of 544 and 319 to 2400.
//To transform the Xpostion of the object you divide the Xposition by 319 and multiply it by 1856=2400-544.
//We have to add 544 because this is the minimal value for the motorposition
PositionYmotor=544+int(float(pixy.blocks[0].y)/1991856); //The y-position ranges from 0 tot 199. 0 will be equivalent to a Ymotorposition of 544 and 319 to 2400.
//To transform the Ypostion of the object you divide the Yposition by 199 and multiply it by 1856=2400-544.
//We have to add 544 because this is the minimal value for the motorposition
myServoX.write(PositionXmotor); //drive the Xmotor to the position
myServoY.write(PositionYmotor); //drive the Ymotor to the position
}
//in the case no object is detected the motors will keep their position
}