Program 25: Stepper Motor – One Revolution CW then CCW
PIC18F4550 · Embedded C

#include <xc.h>

   #define _XTAL_FREQ 20000000UL

   #define STEPS_PER_REV 200                // 360 / 1.8 deg = 200 steps (change for your motor)

   void Clockwise_1Rev(void)
   {
       unsigned int i;
       for(i = 0; i < STEPS_PER_REV / 4; i++)           // 4 steps per loop -> 50 loops




        {
             LATC = 0x03;      __delay_ms(5);
             LATC = 0x06;      __delay_ms(5);
             LATC = 0x24;      __delay_ms(5);
             LATC = 0x21;      __delay_ms(5);
        }
   }

   void Anticlockwise_1Rev(void)
   {
       unsigned int i;
       for(i = 0; i < STEPS_PER_REV / 4; i++)
       {
           LATC = 0x21; __delay_ms(5);
           LATC = 0x24; __delay_ms(5);
           LATC = 0x06; __delay_ms(5);
           LATC = 0x03; __delay_ms(5);
       }
   }

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

        while(1)
        {
            Clockwise_1Rev();               // one revolution clockwise
            LATC = 0x00;                    // coils OFF
            __delay_ms(2000);               // pause 2 s

             Anticlockwise_1Rev();          // one revolution anticlockwise
             LATC = 0x00;                   // coils OFF
             __delay_ms(2000);              // pause 2 s
        }
   }
