I'm trying to use millis to make a program that will turn a stepper motor some degree one direction and then stop when a button is pushed in a certain time window. And if a button is pushed within another time window, (the time between button pushes actually), is too long then I want the motor to spin the other way and then stop. Please ignore the Servo stuff. Even without the servo involved the code doesn't seem to work. The code:
#include <Servo.h>
Servo myservo;
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);
const int inPin = 2;
const int outPin= 13;
unsigned long elapsedtime=0;
int ledstate =LOW;
int switchstate = LOW;
int previous = LOW;
unsigned long prevtime = 0;
unsigned long debounce = 200;
unsigned long dur_on = 0; //duration between on/off
void setup(){
myservo.attach(9);
pinMode(inPin,INPUT);
pinMode(outPin,OUTPUT);
Serial.begin(9600);
AFMS.begin();
myMotor->setSpeed(10);
}
void loop()
{
ReadSensor();
MotorActionForward();
MotorActionBackward();
delay(200);
}
void ReadSensor()
{
switchstate=digitalRead(inPin);
if ((millis()-prevtime)>debounce){
if(switchstate!=previous && switchstate==HIGH){
if (ledstate==LOW){
digitalWrite(outPin,HIGH);
prevtime=millis();
ledstate=HIGH;
}
else if(ledstate==HIGH){
digitalWrite(outPin,LOW);
ledstate=LOW;
Serial.print("time between drips ");
elapsedtime=((millis()-prevtime));
Serial.println(elapsedtime);
prevtime=millis();
}
}
}
}
void MotorActionForward()
{
if (elapsedtime > 5500){
myMotor->step(10, FORWARD, DOUBLE);
elapsedtime=((millis()-prevtime));
}
}
void MotorActionBackward()
{
if (elapsedtime < 4500 && elapsedtime > 200 && elapsedtime != 0){
myMotor->step(10, BACKWARD, DOUBLE);
elapsedtime=((millis()-prevtime));
}
}
???????????????????????????
I can get the program to work as expected with the void MotorActionForward() alone. But when I add void MotorActionBackward() it doesn't increment the motor and stop. Instead it performs the increment of 10 about 8x and then stops. And during that time it will no longer read a button push. And if I just try to used MotorActionBackward() without MotorActionForward() the motor still does the 8x BACKWARD thing.
I've also tried combining MotorActions together and using two if statements, but the Backwards still acts goofy. Code:
if (elapsedtime > 5500){
myMotor->step(10, FORWARD, DOUBLE);
elapsedtime=((millis()-prevtime));
}
if (elapsedtime < 4500){
myMotor->step(10, BACKWARD, DOUBLE);
elapsedtime=((millis()-prevtime));
}
I'm not a programmer and am new to arduino.
Does anyone know how to proceed? Is this program possible without writing interrupts? Why is Backwards not working in one increment and then stopping as expected? Thanks to anyone that will reply.