I'm working a project where I need a stepper motor to move a certain range, only when someone presses on a pressure sensor. I'm prototyping it with a button at the moment. I have this code below working, currently, adapted from example code. Currently, when you press the button, the motor spins in one direction. The LED blinks at the rate of the spin. What I need it to do is:
- when the button is not being pressed, do nothing
- when the button is pressed, move forward a specified amount
- move backward the same amount
- do nothing until button is pressed again
Unfortunately, I don't really understand why the stepper code works well enough to make it do this. I dont really get the channels and how they work.
any help?
thanks
/*
For more information see: https://www.instructables.com/id/Arduino-Motor-Shield-Tutorial/
*/
int delaylength = 20;
const int ledPin = 13;
const int buttonPin = 2;
int buttonState = 0;
void setup() { // initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
//establish motor direction toggle pins
pinMode(12, OUTPUT); //CH A -- HIGH = forwards and LOW = backwards???
pinMode(13, OUTPUT); //CH B -- HIGH = forwards and LOW = backwards???
//establish motor brake pins
pinMode(9, OUTPUT); //brake (disable) CH A
pinMode(8, OUTPUT); //brake (disable) CH B
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGHad) { digitalWrite(ledPin, HIGH);
digitalWrite(9, LOW); //ENABLE CH A
digitalWrite(8, HIGH); //DISABLE CH B
digitalWrite(12, HIGH); //Sets direction of CH A
analogWrite(3, 255); //Moves CH A
delay(delaylength);
//digitalWrite(ledPin, HIGH);
digitalWrite(9, HIGH); //DISABLE CH A
digitalWrite(8, LOW); //ENABLE CH B
digitalWrite(13, LOW); //Sets direction of CH B
analogWrite(11, 255); //Moves CH B
delay(delaylength);
digitalWrite(ledPin, LOW);
digitalWrite(9, LOW); //ENABLE CH A
digitalWrite(8, HIGH); //DISABLE CH B
digitalWrite(12, LOW); //Sets direction of CH A
analogWrite(3, 255); //Moves CH A
delay(delaylength);
//digitalWrite(ledPin, LOW);
digitalWrite(9, HIGH); //DISABLE CH A
digitalWrite(8, LOW); //ENABLE CH B
digitalWrite(13, HIGH); //Sets direction of CH B
analogWrite(11, 255); //Moves CH B
delay(delaylength);
} else {
// turn LED off:
digitalWrite(ledPin, LOW); }
}