quinta-feira, 7 de novembro de 2019

How to design a better blink led?

Simple! Check the code I wrote for the Blink post "Blink - PIC18F - MPLABX - PICkit3"
link:  https://projetosdoborba.blogspot.com/2019/11/blink-pic18f-mplabx-pickit3.html

What can go wrong with a simple blink LED routine and who does care?

Writing complex algorithms to solve hard problems all starts with good writing practices. 


Let's start with a block diagram of the blink algorithm. The flowchart will help you to clarify your thoughts and write better codes. 



From the flowchart, we can write the code skeleton with more informative and constructive comments.

//initialize the microcontroller (uC)

//initialize pins

//while forever 

//turn led on

//delay

//turn led off 

//delay


It is also necessary to understand what each register (TRISB, PORTB) means. Then, you will need to check the datasheet. When we are learning how to program, reading the datasheet seems to be overwhelming and hard, it is actually quite simple, you just have to learn where to find the information you need. 

Please, refer to the datasheet available on https://ww1.microchip.com/downloads/en/DeviceDoc/40001412G.pdf

I posted some screenshots from the datasheet at the end of this post. Please, take a look there.

Here is the code with more comments 


//initialize the microcontroller (uC)

#include <xc.h>

//delay function
void DELAY_ms(unsigned int ms_Count);

int main()
{

//initialize pins
//configure port B as a digital output. Page 132 datasheet. 
TRISB = 0; //  PortB as Output 


//while forever 
while(1)
  {

    //turn led on
    PORTB = 0xFF;  

    //delay
    DELAY_ms(100); // 100 ms Delay

    //turn led off 
    PORTB = 0x0;   

    //delay
    DELAY_ms(100); // 100 ms Delay
  }
}


void DELAY_ms(unsigned int ms_Count)

{

    unsigned int i,j;

    for(i=0;i<ms_Count;i++)

    {

        for(j=0;j<100;j++);

    }

}



A final thought before closing this post: There is a timing issue in the void DELAY_ms function because the for(j=0;j<100;j++) is not calibrated. I am mean, nothing can guarantee that for(j=0;j<100;j++)  is exactly 1 milliseconds. I will go over about delay function calibration later on and why we should not use delay functions like in this program. 



Please, see the screenshot I took from the datasheet. I highlighted the most important thing there. 








Again in the datasheet, we can check why when we write PORTB = 0xFF;  // LED ON the led turns on. The register PORTB is used to read or write values in and from the pin. Please, check page 127 of the datasheet.  







Um comentário: