In the previous tutorial we discussed about how to generate a specific delay using internal timers of pic microcontroller. We also derived and discussed the formula for calculating the output signal period. We also discussed the terms related with the time/frequency formula derivation, such as Tick_counter frequency, Timer Count etc. This tutorial is in chain with the previous one the code used below in inherited from the previous tutorial. I recommend to first go through the previous simple tutorial. You can easily understand the code below if you take the tutorial
Now you have taken the above tutorial its time to start with this tutorial. Suppose we want to toggle an led, generate and event or read data after 10 ms with 20 Mhz clock source. I selected the prescaller to be 1:4. For this we have to calculate the “Timer Count” value. Lets start deriving the “Timer Count”. The formula is given below.
Specific delay formula for Pic Microcontroller’s
10 ms = Timer Count * ( 4 / (20M hz/ 4) )
10 ms = Timer Count * ( 4 / 5 Mhz)
10 ms * 5 M hz = Timer Count * 4
50 k = Timer Count * 4
50000 / 4 = Timer Count
Timer Count = 12500 (Hex 0x30D4)
TMR1H = 0x30;
TMR1L = 0xD4;
Project circuit diagram
Note: Led’s anode is connected to pic microcontroller port-b pins and cathode is grounded with 330 ohm resistor placed in series. This configuration of led’s is a bad choice. I recommend you to connect the anode of led’s with external power source and connect the cathode with port-b pins of pic microcontroller. Resistor must be placed in series with the led to limit the current consumption by led.
My circuit configuration also worked but the led lights are too dim and its hard to see the effect of blinking/toggling in bright day light. I switched of room lights to see the clear pic microcontroller blinking led effect.
/************************************************** | |
* Property of: www.microcontroller-project.com * | |
* Author: Usman Ali Butt * | |
* Created on 11 April, 2017, 2:30 PM * | |
**************************************************/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <pic16f887.h> | |
void Timer0Delay(void); //Delay Function | |
int main(int argc, char** argv) { | |
TRISB=0x00; //Port-B as Output | |
while(1){ | |
PORTB= ~PORTB; //Toggle Output | |
Timer0Delay(); //Delay | |
} | |
return (EXIT_SUCCESS); | |
} | |
void Timer0Delay(void){ //10ms delay | |
T1CON=0x01; //Timer-1 16-bit mode Prescaler 1:4 | |
TMR1H=0x30; //Count Hight Byte | |
TMR1L=0xD4; //Count Low Byte | |
T1CONbits.TMR1ON=1; //Run timer | |
while(INTCONbits.TMR0IF==0); //Wait for flag to over flow | |
T1CONbits.TMR1ON=0; //Switch off timer | |
INTCONbits.TMR0IF=0; //Clear Interrupt | |
} |
T1CON=0x01; //Timer-1 16-bit mode Prescaler 1:4
TMR1H=0x30; //Count High Byte
TMR1L=0xD4; //Count Low Byte
The post Toggle/Blink led on specific delay with pic microcontroller using timers: MPLABX and xc8 compiler appeared first on PIC Microcontroller.