// https://forum.arduino.cc/t/an-arduino-to-control-and-count-to-200-rev-for-a-coil-winder/1323683
/*
- The wire is attached to one side of the bobbin.
- The bobbin is attached to the stepper motor spindle.
- A pulley is suspended on a rod above the bobbin.
- The motor rotates, turning the bobbin, taking up the wire.
- The servo arm pulls and pushes the pulley along the rod.
- The stepper motor has 200 steps per revolution
- Stepping every 0.5 ms makes about 1000 steps (5 revolutions) per second
*/
#include <Stepper.h>
#include <Servo.h>
const byte stepsPerRevolution = 200;
const byte dirPin = 2, stepPin = 3;
bool stepState = 0;
Servo servo;
const byte servoPin = 4;
const int servoHome = 90, servoSweep = 10;
const int servoLeft = servoHome - servoSweep, servoRight = servoHome + servoSweep;
int servoDir = 1; // - (left) or + (right)
int servoAngle = servoLeft;
int steps;
unsigned long timer, timeout = 500; // microseconds
void setup() {
Serial.begin(11520);
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
digitalWrite(dirPin, HIGH);
servo.attach(servoPin);
servo.write(servoLeft);
}
void loop() {
if (micros() - timer > timeout) { // wait for next step
timer = micros(); // reset timer
step(); // move motor
if (steps++ > stepsPerRevolution) { // count to one revolution
steps = 0;
sweep(); // move servo every revolution
}
}
}
void sweep() {
if (servoAngle < servoLeft || servoAngle > servoRight) // check servo boundaries
servoDir = -servoDir; // change servo direction
servoAngle += servoDir; // change angle
servo.write(servoAngle); // move servo
}
void step() {
digitalWrite(stepPin, stepState);
delay(1); // 1000 us
digitalWrite(stepPin, !stepState);
}