Skip to content

Instantly share code, notes, and snippets.

@aeris
Last active Feb 17, 2018
Embed
What would you like to do?
Kitten laser tower
// License: AGPLv3
#include <Servo.h>
#define MIN_DURATION 200
#define MAX_DURATION 500
#define MIN_FREEZE 100
#define MAX_FREEZE 200
#define LASER_PIN 9
class PanTilt {
public:
void attach(const int pin_x, const int pin_y);
void go(const float x, const float y);
void center();
void move(const float x, const float y, const float duration);
void move_random(const float duration);
void square();
private:
float x = 0;
float y = 0;
Servo servo_x;
Servo servo_y;
static constexpr const float MIN_X = 0;
static constexpr const float MAX_X = 180;
static constexpr const float MIN_Y = 0;
static constexpr const float MAX_Y = 85;
static constexpr const float MINIMAL_MOVEMENT = 0;
static constexpr const int STEP_DURATION = 10;
};
void PanTilt::attach(const int pin_x, const int pin_y) {
this->servo_x.attach(pin_x);
this->servo_y.attach(pin_y);
}
void PanTilt::go(const float x, const float y) {
// Serial.print("X: ");
// Serial.println(x);
this->x = x;
this->servo_x.write(x);
// Serial.print("Y: ");
// Serial.println(y);
// Serial.flush();
this->y = y;
this->servo_y.write(y);
}
void PanTilt::center() {
const float x = MIN_X + (MAX_X - MIN_X)/2;
const float y = MIN_Y + (MAX_Y - MIN_Y)/2;
this->go(x, y);
}
void PanTilt::square() {
this->go(MIN_X, MIN_Y);
delay(1000);
this->go(MAX_X, MIN_Y);
delay(1000);
this->go(MAX_X, MAX_Y);
delay(1000);
this->go(MIN_X, MAX_Y);
delay(1000);
}
void PanTilt::move(const float x, const float y, const float duration) {
const int steps = duration / STEP_DURATION;
Serial.print("Steps: ");
Serial.println(steps);
const float x_delta = (x - this->x)/steps;
Serial.print("X delta: ");
Serial.println(x_delta);
const float y_delta = (y - this->y)/steps;
Serial.print("Y delta: ");
Serial.println(y_delta);
float tmp_x = this->x, tmp_y = this->y;
for (int i = 0; i < steps; ++i) {
tmp_x += x_delta;
tmp_y += y_delta;
// Serial.print("X tmp: ");
// Serial.println(tmp_x);
// Serial.print("Y tmp: ");
// Serial.println(tmp_y);
this->go(tmp_x, tmp_y);
delay(STEP_DURATION);
}
this->go(x, y);
}
void PanTilt::move_random(const float duration) {
const float x = random(MIN_X, MAX_X);
const float y = random(MIN_Y, MAX_Y);
this->move(x, y, duration);
}
PanTilt panTilt;
void setup() {
pinMode(LASER_PIN, OUTPUT);
digitalWrite(LASER_PIN, HIGH);
Serial.begin(9600);
panTilt.attach(5, 6);
panTilt.square();
panTilt.center();
}
void loop() {
// for ( int x = 120; x <= 180; ++x ) {
// panTilt.go(x, 0);
// delay(100);
// }
// for ( int y = 0; y <= 180; ++y ) {
// panTilt.go(0, y);
// delay(100);
// }
// exit(-1);
const int duration = random(MIN_DURATION, MAX_DURATION);
panTilt.move_random(duration);
const int freeze = random(MIN_FREEZE, MAX_FREEZE);
delay(freeze);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment