This post provides the code to make an LED blink using PIC16F628A microcontroller. This code is written in C language using MPLAB with HI-TECH C compiler. This code is intended to be the first step in learning how to use PIC16F628A microcontroller in your projects. You can download this code from the 'Downloads' section at the bottom of this page.
Following figure shows the minimum circuit required to make an LED blink with PIC16F628A.
In this figure, first thing to note is that there is a crystal of 20MHz used with PIC16F628A. You can use any crystal from 0 to 20MHz with PIC16F628A. MCLR master reset pin is pulled high to keep PIC16F628A out of reset. RB4 pin is being toggled in the code.
C-Code
The code for making LED blink using PIC16F628A is shown below.Figure 2. Code for making LED blink using PIC16F628A |
Whenever you are writing code for PIC microcontrollers, then you have to include "htc.h" file in the code. After including "htc.h" file, configuration bits are being set in the code shown above. To understand the details of how these configuration bits are being programmed, you can read this post.
After the configuration bits, LED pin is being defined as the RB4 pin. You can replace RB4 with any other pin name if you want (e-g RB5 etc). After LED pin definition, CPU frequency is being defined. You have to define _XTAL_FREQ macro, if you want to use built in delay functions like __delay_us() and __delay_ms(). Here CPU frequency is defined to be 20MHz, which is the crystal oscillator frequency attached with PIC16F628A in the circuit.
In the main function, firstly RB4 pin direction is set to be an output pin using TRISB4 = 0; statement. Using TRISx register, we can set the direction of any pin i-e if it is an input or output. Then LED pin is made low using LED = 0; statement.
LED pin is being toggled in the while loop after every half second. In this way you can easily make LED blink using PIC16F628A microcontroller.
Notes and References
[1] Because every PIC microcontroller has an architecture which executes an instruction in 4 CPU cycles, when CPU frequency is defined to be 20MHz, then actual speed of this PIC microcontroller will be 5 MIPS (Million of instructions per second).
[2] For details please refer to PIC16F628A datasheet.
No comments:
Post a Comment