Hey folks, I found a program recently that I followed to have a Stepper Motor follow a Servo motor to make it look like a skull is looking at you as you pass by. It kinda works but I need some tips, I didn't have luck on the discord but maybe I can get help here!
#include <Stepper.h> //Stepper
#include <Servo.h> // Servo
int stepperAngle = 90;
int pos = 90 ;
int posf;
int multiplier = 10;
const int trig = 5;
const int echo = 4;
const int esp = 12; //Eye Servo Pin
Stepper stepper(posf,8,9,10,11);
Servo eyeServo;
long dur;
int dist;
long lastSeen;
void setup() {
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
pinMode(6, OUTPUT);
pinMode(7,OUTPUT);
eyeServo.attach(esp);
eyeServo.write(90);
Serial.begin(9600); // Starts serial Communication. (Serial Communication is something that
// lets your device & board talk)
}
void loop() {
int posf = pos * multiplier;
int lastAngle = pos;
// Ultrasonic Tracking
getDistance();
if (dist > 10 && dist < 30){ //30 for testing
if (pos < 60){
pos = 60;
}else{
pos-=6;
}
}else{
if (pos > 120){
pos = 120;
}else{
pos++;
}
}
if (pos > 50 && pos < 108){
lastSeen = millis();
}
if (lastSeen != pos){
eyeServo.write(pos);
}
Serial.println(pos);
delay(1);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
//STEPPER ------------------------------------------
stepToDeg(pos);
delay(1);
}
void stepToDeg(int stepAngle){
if (pos < 121){
int difference = stepperAngle - pos;
int absDifference = abs(difference);
int negDif = -difference*7;
stepper.step(negDif);
stepperAngle = pos;
}
}
void getDistance(){ //TAKES AN ULTRASONIC MEASUREMENT AND RETURNS THE COMPUTED DISTANCE IN CM
// Clears the trigPin
digitalWrite(trig, LOW);
delayMicroseconds(2);
//Sends pulse
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
dur = pulseIn(echo, HIGH);
dist = dur*0.034/2;
}