Hi there,
I have been having a few issues with the following code. Could someone please help.
// Description:
// Reads time differences between success pulse inputs
// no debounce applied to inputs for speed
// measures time difference and converts to shaft RPM
//
// If RPM above a preset value, turn stepper motor one direction for a preset distance
// Otherwise, turn motor other direction for a preset distance
//
DETAILS -
100 steps (1.8 degrees per step) is required when Stepper is activated in either direction.
Stepper activation is governed by the rotational speed of a Rotor shaft.
When the Rotor shaft RPM (read by Photo interrupter) is -
Greater then 80 - turn Stepper motor CCW 100 steps @ 20 rpm
Less then 80 - turn Stepper motor CW 100 steps @ 20 rpm.
RPM of Rotor shaft is read every 15 seconds.
*/
// I/O Connections:
// Arduino pin - I/O description
// Pins 8-11: stepper motor
// Pin 2: shaft photointerrupter input
#define SHAFT_PIN 2
// Constants
#define STEPS_PER_REV 200
// RPM limit
#define RPM_LIMIT 80
// 80 RPM is 750 milliseconds per rotation
#define RPM_LIMIT_MS 750
// Stepper distance to move
#define MOTOR_DISTANCE 100
// Speed steps/second
#define MOTOR_SPEED 20
// Interval in which to check RPM
#define TEST_INTERVAL 15000
// Input debounce in ms
#define DEBOUNCE 10
// Globals
Stepper _motor (STEPS_PER_REV, 8, 9, 10, 11);
bool _trigger = false;
unsigned long _sensorTime = 0;
unsigned long _lastUpdate = 0;
void setup()
{
// Inialize serial port
Serial.begin(115200);
Serial.println("Start");
_motor.setSpeed(MOTOR_SPEED);
pinMode(SHAFT_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(SHAFT_PIN), isrTrigger, RISING);
}
void loop()
{
unsigned long timeNow = millis();
bool localTrigger = false;
// Disable interrupts
cli();
localTrigger = _trigger;
_trigger = false;
// Re-enable
sei();
if (localTrigger)
{
Serial.print("Pulse period: "); Serial.println(timeNow - _sensorTime);
Serial.print("Calc RPM: "); Serial.println(60000 / (timeNow - _sensorTime));
if (timeNow - _lastUpdate > TEST_INTERVAL)
{
_lastUpdate = timeNow;
if ((timeNow - _sensorTime) > RPM_LIMIT_MS)
{
Serial.println("Moving CW");
// Slower, turn motor clockwise
_motor.step(MOTOR_DISTANCE);
}
else
{
// Turn motor counterclockwise
Serial.println("Moving CCW");
_motor.step(-MOTOR_DISTANCE);
}
}
// Capture shaft period
_sensorTime = timeNow;
}
}
// ISR for the pulse interrupt
// triggered by shaft sensor
void isrTrigger()
{
_trigger = true;
}