/*
 * stepper2.c
 *
 * Drive a stepper motor connected to port B
 *
 * RB1: Coil 1
 * RB2: Coil 2
 * RB3: Coil 3
 * RB4: Coil 4
 *
 * Continually sweeps back and forth, rotating 180 deg each pass
 *
 * Mark Crosbie  9/27/98
 *
 */

#define DELAY 50

#define SWEEP 12

#define NUMSTEPS 4

char step[] = {5, 9, 10, 6};
char stepPos = 0;

/* pulse the motor with the current coil setting
 * and then wait for delay mS
 */
void pulseMotor(char delay) {
  output_port_b(step[stepPos]);
  delay_ms(delay);
}

/* Advance the coil settings forward by one step
 * stepPos is left pointing to the *next* code to output to move forward
 */
void stepMotorForw(void) {
    stepPos++;
    if(stepPos == NUMSTEPS)
      stepPos = 0;
}
 
/* Advance the motor backward by one step
 * stepPos is left pointing to the *next* code to output to move backward
 */
void stepMotorBack(void) {
  /* advance stepPos to before where we were */
  /* do wrap around */
  if(stepPos == 0) {
    stepPos = NUMSTEPS-1;
  } else {
    stepPos--;
  }
} 

void main(void) {

  char i;

  set_bit(STATUS, RP0);    /* select the register bank 1 */
  set_tris_b(0);           /* PORT B is all output */
  clear_bit(STATUS, RP0);

  while(1) {

    for(i=0; i < SWEEP; i++) {
      pulseMotor(DELAY);
      stepMotorForw();
    }
    delay_s(3);

    for(i=0; i < SWEEP; i++) {
      stepMotorBack();
      pulseMotor(DELAY);
    }

    delay_s(3);

  }
}

