Stepper motor code and M542T Driver


hi every one, i'm green arduino , coding, been bit frustrated trying code want, gone through lot of examples slight idea on how write , want code turn motor cw stop ccw 1 single button, i've tried accelstepper library , stepper.h , went normal arduino code because found easier understand, here attached code

code: [select]
const int buttonpin = 2;

int buttonstate = 0;
int onoroffstate = 0;

int speed = 500; // how fast motor "step"
int distance = 0;  // how far traveled
int numsteps = 5000; // steps

void setup() {
  pinmode(2, input);               
  pinmode(8, output);     
  pinmode(9, output);
  digitalwrite(8, low);
  digitalwrite(9, low);
}

void loop(){
 buttonstate = digitalread(2);
 if (buttonstate == high){
  onoroffstate = 1;}
                                                                                                             
  while (onoroffstate == 1){
    digitalwrite(9, high);
    delaymicroseconds(speed);
    digitalwrite(9, low);
    delaymicroseconds(speed);
    distance = distance +1;
    if (distance == numsteps)
    onoroffstate = 0;
  }
  if (digitalread(8) == low){
    digitalwrite(8, high);
}
else
{
  digitalwrite(8,low);
}
distance = 0;
delay(5);




its wired ok button getting pulled ground 10k , i'm not sure if i've used {} in right way i've said i'm new , don't understand lot, code works @ end when runs though , press button times runs cw cw again maybe ccw cant predict going times want other times not. thanks

your main problem switching directions every time through loop() when button has not been pressed.  change sketch reverse direction when reach end of movement.

here how write it.  compare original sketch style hints , shortcuts.
code: [select]
const int buttonpin = 2;
const int directionpin = 8;
const int steppin = 9;

const int numsteps = 5000; // steps
const int speed = 500; // how fast motor "step"

boolean running = false;
int distance = 0;  // how far traveled


void setup() {
  pinmode(buttonpin, input);
  pinmode(directionpin, output);
  pinmode(steppin, output);
  digitalwrite(directionpin, low);
  digitalwrite(steppin, low);
}

void loop() {
  if (digitalread(buttonpin)) {
    running = true;
  }

  // move in 1 direction
  while (running) {
    digitalwrite(steppin, high);
    delaymicroseconds(speed);
    digitalwrite(steppin, low);
    delaymicroseconds(speed);
    distance++;
    if (distance == numsteps) {
      running = false;
      // reverse direction
      digitalwrite(directionpin, !digitalread(directionpin));
      // start on @ 0
      distance = 0;
    }
  }
  delay(5);
}


Arduino Forum > Using Arduino > Programming Questions > Stepper motor code and M542T Driver


arduino

Comments