// Example_2.C
//
// Right and left arrow.
//
// copyright, Peter H. Anderson, Baltimore, MD, April 9, '08
//

#case

#device PIC16F887 *=16 ICD=TRUE

#include <defs_887.h>

void arrow_right(long d_time);
void arrow_left(long d_time);

void delay_10us(byte t);
void delay_ms(long t);


void main(void)
{

   byte ms;
   OSCCON = 0x61;
   not_rbpu = 0;  // insert pullups on PORTB
   ANSELH = 0x00;  // disable high six A/D

   TRISD = 0xf0;   // lower four bits are outputs

   while(1)
   {
       if (portb1 == 0)
       {
           ms = 250;
       }
       else
       {
           ms = 5;
       }

       if (portb0 == 0)
       {
           arrow_right(ms);
       }
       else
       {
           arrow_left(ms);
       }

   }
}

void arrow_right(long d_time)
{
    const byte patts[5] = {0x00, 0x08, 0x04, 0x02, 0x01};
    static byte index = 0;

    if (index > 4)
    {
        index = 0;
    }
    PORTD = patts[index];
    delay_ms(d_time);
    ++index;
}

void arrow_left(long d_time)
{
    const byte patts[5] = {0x00, 0x01, 0x02, 0x04, 0x08};
    static byte index = 0;

    if (index > 4)
    {
        index = 0;
    }
    PORTD = patts[index];
    delay_ms(d_time);
    ++index;
}

void delay_10us(byte t)
// provides delay of t * 10 usecs (4.0 MHz clock)
{
#asm
      BCF STATUS, RP0
DELAY_10US_1:
      CLRWDT
      NOP
      NOP
      NOP
      NOP
      NOP
      NOP
      DECFSZ t, F
      GOTO DELAY_10US_1
#endasm
}


void delay_ms(long t)   // delays t millisecs (4.0 MHz clock)
{
   do
   {
     delay_10us(100);
   } while(--t);
}