Skip to content

Instantly share code, notes, and snippets.

@decebals
Created May 11, 2015 17:05
Show Gist options
  • Save decebals/b1201f3c24021bdae370 to your computer and use it in GitHub Desktop.
Save decebals/b1201f3c24021bdae370 to your computer and use it in GitHub Desktop.
Arduino
#include <AccelStepper.h>
const int stepsPerRevolution = 50; // change this to fit the number of steps per revolution for your motor
const int cm = stepsPerRevolution * 4.935; // number of steps required to move 1cm
const int button1Pin = 10;
const int button2Pin = 11;
const int button3Pin = 12;
int limitSwitch = 1;
int button2State = 1;
int button3State = 1;
// see http://www.airspayce.com/mikem/arduino/AccelStepper/index.html
AccelStepper stepper(AccelStepper::FULL4WIRE,5,6,7,8); // defaults to AccelStepper::FULL4WIRE (4 pins) on 2, 3, 4, 5
void setup() {
// serial settings
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.println("Stepper test!");
// motor settings
stepper.setMaxSpeed(220);
stepper.setAcceleration(1000);
stepper.setCurrentPosition(0);
pinMode(button1Pin, INPUT_PULLUP);
pinMode(button2Pin, INPUT_PULLUP);
pinMode(button3Pin, INPUT_PULLUP);
// attachInterrupt(0, limitStop, CHANGE);
}
void loop() {
limitSwitch = digitalRead(button1Pin);
Serial.println(limitSwitch);
if (limitSwitch == 0) {
return;
}
button2State = digitalRead(button2Pin);
Serial.println(button2State);
if (button2State == 0) {
// move foreward
stepper.moveTo(stepper.currentPosition() + 1);
}
button3State = digitalRead(button3Pin);
Serial.println(button3State);
if (button3State == 0) {
// move backward
stepper.moveTo(stepper.currentPosition() - 1);
}
stepper.run();
}
/*
void limitStop() {
stepper.stop();
stepper.setCurrentPosition (0);
}
*/
@gnokix
Copy link

gnokix commented Aug 14, 2015

Hey, for limit switch may be you can use an attachinterrupt, it's easier than read all the time the sate of a pin, maybe with something like this.

#define LED 13
volatile byte state = LOW;

void setup() {

    Serial.begin(9600); 
    pinMode(LED, OUTPUT);
    attachInterrupt(0, toggle, RISING);  // look in the specification of your board wich pin is attached to interrupt 0, I have mega2560 and i'ts "digital 2". //

}

void loop() {
    // Do whatever you need, delay is not recomended //
}

void toggle() { 

        state = !state; 
    digitalWrite(LED,state);
    Serial.println(state); 
}

I hope it helps!
Kind regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment