void delay_ms( uns16 millisec) //Delays multiples of 1 milliseconds at 4 MHz //Accepts a 16 bit parameter for required delay { char next = 0; //Defines the 8 bit character 'next' and sets it to 0 OPTION = 0b.0010; //0 Assigns the prescaler to TMR0 //010 Sets the prescaler to 8 //This lengthens the clock pulse by 8 for every PIC instruction cycle TMR0 = 2; //The timer increments TMR0 with every clock pulse except the first 2 //Starting the counter from 2 overcomes this error //Do the following at least once and until last 'while' statement is no longer true do { next += 125; //Each loop increments 'next' by 125 //This creates a larger value to compare against the TMR0 timer while (TMR0 != next); //Wait until the TMR0 counter equals 'next' //This condition is true every 1000uS (1ms) because: //Most instructions take 4 clock cycles //4MHz / 4 = 1 million instructions per second (1uS each) //1uS * 8 prescaler * 125 = 1000uS (1ms) per loop } while ( -- millisec != 0); //Final part of the 'do' statement //Reduce the 'millisec' parameter by 1 for each loop //ie: count down by 1ms per loop until 0 }