So I have been working on a project for a little while now that is controlling a stepper with the use of a pot and a multifunction button. Thanks to the help from everyone here, I got it mostly working. The control functions as such:
pot controls the speed
click of the button changes direction
holding the button for 2 seconds disables the motor
It is mostly working, but it seems to be having some glitches. Here is what happens:
problem 1:
power on and nothing happens until I press the button for 2 seconds (This is the behavior I want)
when I press the button, it powers on and moves for a few seconds then stops (not what I want)
Problem 2:
I click the button and the direction changes but after about 2 seconds it changes back on it's on (not what I want)
Here is the code:
// define pins
#define stepPin 3
#define dirPin 4
#define ms1 8
#define ms2 9
#define ms3 10
#define buttonPin 2
#define motorPin 13
#define debounce 20
#define holdTime 2000
// Potentiometer Variables
int cutomDelay,customDelayMapped;
// Button variables
int buttonVal = 0;
int buttonLast = 0;
long btnDnTime;
long btnUpTime;
boolean ignoreUp = false;
// Motor variables
boolean motorVal = false;
boolean dirVal = false;
void setup() {
// initialize and set outputs
pinMode(buttonPin, INPUT_PULLUP);
digitalWrite(buttonPin, HIGH);
pinMode(motorPin, INPUT_PULLUP);
digitalWrite(motorPin, HIGH);
pinMode(dirPin, OUTPUT);
digitalWrite(dirPin, dirVal);
pinMode(stepPin, OUTPUT);
pinMode(ms1, OUTPUT);
pinMode(ms2, OUTPUT);
pinMode(ms3, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
// Read the state of the button
buttonVal = digitalRead(buttonPin);
// Test for button pressed and store the down time
if (buttonVal == LOW && buttonLast == HIGH && (millis() - btnUpTime) > long(debounce))
{
btnDnTime = millis();
}
// Test for button release and store the up time
if (buttonVal == HIGH && buttonLast == LOW && (millis() - btnDnTime) > long(debounce))
{
if (ignoreUp == false) dirChange();
else ignoreUp = false;
btnUpTime = millis();
}
// Test for button held down for longer than the hold time
if (buttonVal == LOW && (millis() - btnDnTime) > long(holdTime))
{
motorOnOff();
ignoreUp = true;
btnDnTime = millis();
}
buttonLast = buttonVal;
motorRun();
motorSpeed();
}
void motorOnOff() {
motorVal = digitalRead(motorPin);
motorVal = !motorVal;
digitalWrite(motorPin, motorVal);
}
void dirChange() {
dirVal = !dirVal;
digitalWrite(dirPin, dirVal);
}
int motorSpeed() {
int customDelay = analogRead(A0);
int newCustom = map(customDelay, 0, 1023, 200, 4000);
return newCustom;
}
void motorRun() {
customDelayMapped = motorSpeed();
digitalWrite(stepPin, LOW);
delayMicroseconds(customDelayMapped);
digitalWrite(stepPin, HIGH);
delayMicroseconds(customDelayMapped);
digitalWrite(ms1,HIGH);
digitalWrite(ms2,HIGH);
digitalWrite(ms3, HIGH);
}
Any ideas where I've messed up?