Program 24: Stepper Motor – Direction by Push Buttons
PIC18F4550 · Embedded C

#include <xc.h>

   #define _XTAL_FREQ 20000000UL

   unsigned char direction = 0;             // 0 = stop, 1 = clockwise, 2 = anticlockwise

   void main(void)
   {
       ADCON1 = 0x0F;                       // make pins digital

        TRISC = 0x00;                       // PORTC = output (motor)
        LATC = 0x00;

        TRISAbits.TRISA2 = 1;               // SW18 = input
        TRISAbits.TRISA3 = 1;               // SW19 = input

        while(1)
        {
            if(PORTAbits.RA2 == 0)          // SW18 pressed
                direction = 1;              // clockwise

             if(PORTAbits.RA3 == 0)         // SW19 pressed
                 direction = 2;             // anticlockwise

             if(direction == 1)      // CLOCKWISE: 03 -> 06 -> 24 -> 21
             {
                 LATC = 0x03; __delay_ms(5);
                 LATC = 0x06; __delay_ms(5);
                 LATC = 0x24; __delay_ms(5);
                 LATC = 0x21; __delay_ms(5);
             }
             else if(direction == 2) // ANTICLOCKWISE: 21 -> 24 -> 06 -> 03
             {
                 LATC = 0x21; __delay_ms(5);
                 LATC = 0x24; __delay_ms(5);
                 LATC = 0x06; __delay_ms(5);
                 LATC = 0x03; __delay_ms(5);
             }
        }
   }
