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.
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.
The blink led is a great start (or re-start in my case) with microcontrollers. In this project, I will describe how to set up the MPLBX and run a simple blink (hello word) C program.
The great advantage of starting (or re-starting) programming microcontrollers with a simple code, such as Blink, is that you can focus on installing and configuring the compiler and potentially many other bugs while installing or setting up your microcontroller environment.
I love programming and for me, life is kind of boring if I am not "thinkering" or working with embedded systems. I believe that 8-bit platforms, but if you can start with 32-bits that works too. The most important is to learn how to configure your microcontroller, how to read a datasheet, what are the limitations, and most importantly what is your main goal.
Today, and in the next series of posts, I will be using the PIC 18F45k22 and the development board PIC-EK. The PIC-EK is manufactured by LogiFind and I bought it on Ebay.
The PIC-EK is a versatile development board and supports an infinity of microcontrollers including families with 8, 10, 14, 18, 20, 28, and 40 pins. Moreover, the PIC-EK has multiple peripherals including LEDs, switches, 7 segment display, joystick, memory, buzzer, and others.
Development board - PIC - EK
I am using the PIC18F45k22 with a 4MHz crystal.
PIC18F45k22 with a 4MHz crystal.
To program the PIC, I am using the PICKit3.
Once the code is written and compiled, you connect the PICKit3 in the PIC-EK and download the binary file.
To program and write code for my embedded systems application, I could use the Mikro C pro or the MPLABx. The major advantage of MikroC is the number of libraries available. On the other side, the pro (full version) costs 250 dollars. A free version, the MPLABx requires more work, but it is free and it gives you full access to the writing memory. I will be using the MPLABx and I will teach you (or at least document) how to install and configure your enviroment for your first program.
Download MPLAB® X IDE v5.25 (Link to windows) and install the drivers.
If you have had experience with creating a new project then you can go to the bit setting part. If not, I suggest you follow these steps:
1) Start a new project:
2) Choose the microcontroller family and your pic
3) Select the compiler. If this is your first time using MPLABx, you have to click the Download XC8 option. (I had already done this and just selected the XC8)
4) Choose the name and location of your project (I forgot to take a print screen, but this part is very straight forward)
Okay, your project has been created.
5) Now you have to click on the helper above the Sources folder and select New >> main.c
6) Okay, now we have a project and a main. Before you start programming, we have to tweak the configuration bits (Warning: if you have no programming experience, this part may seem quite confusing, but it is nothing like a seven-headed array. The microcontroller is a very flexible device, and you have to "adjust" your preferences so that everything works just fine (unfortunately or fortunately) you will need to read the microcontroller datasheet.
7) setting bit: Click on the tab.
8) In this project, I modified only 3 bits: oscillator (HSMP), watchdog (OFF) and, PORTB AD (OFF)
Then just compile (on the hammer), connect PICKit3 to PIC-EK and click on the icon with the green arrow pointing down (Make and program)
A window will pop up for you to select your programmer (PICKit3)
Some microcontrollers work with 3.3V and others with5V. The PIC18F45k22 is at 5V. This option, I just clicked OK. (I am not responsible if you burn your PIC because of the wrong voltage. Read everything carefully and always be cautious!)
Here is the result:
I hope you have been able to follow the step by step and get rid of the PIC microcontroller bits ai. Please post comments with questions, program suggestions, and improvements.
Next steps:
Put the code in github (public)
Create an .h file for configuration functions.
Explore pushbutton LED routines and timer and hardware interrupt routines.
Acho que este título descreve bem o projeto: Blink -> PIC18F -> MPLABX -> PICkit3.
O tempo passa e, acaba que o blink (pisca-pisca) é sempre um bom lugar para recomeçar. Resultado:
A vantagem de começar (ou recomeçar) com um projeto simples é que você pode focar nos ajustes do compilador e outros (muitos) problemas que acontencer durante a instalação do compilador.
Eu gosto muito de programar. Acho que a vida fica meio chata quando eu não estou mexendo com alguma placa de desenvolvimento ou fazendo algum sistema embarcado novo. Muita gente tem preconceito com PIC e Arduino por estas plataformas (especialmetne as de 8bits) não serem tão poderosas quanto à novas arquiteturas de 32-bits (PIC32, ARM Cortex, etc). Eu acho que cada plataforma tem o seu papel e a sua aplicabilidade. É importante usar a ferramenta que você tem nas mãos e conhecer as suas limitações e possíveis aplicações.
Hoje, e nas próximas séries de posts, eu vou usar o PIC 18F45k22 com a placa de desenvolvimento PIC-EK.
A PIC-EK é feita pelo fabricante LogiFind. Uma das vantagems desta placa é a versatilidade, pois ela suporta uma infinidade de famílias de microcontroladores com pinos diferentes (8, 10, 14, 18, 20, 28, 40 pinos). Além disso, a PIC-EK também tem uma série de periféricos montados na placa, incluindos, leds, chaves, visor de 7 segmentos, joystick, memória, buzzer, e vários outros periféricos. Eu comprei a minha pelo ebay, mas eu sei que ela tem para vender no aliexpress. Comenta ai se você sabe se alguem re-vende esta placa no mercado livre ou outro website.
Placa de programação - PIC - EK
O PIC que eu estou estando é o PIC18F45k22 com um cristal de 4MHz. Eu estou usando este PIC pois ele é o único que eu tinha disponível aqui de um projeto antigo.
PIC18F45k22 com o cristal de 4MHz.
Para programar o PIC, vou usar o PICKit3. Novamente, é uma opção mais em conta e funciona bem.
Uma vez que o programa foi escrito e compilado (vou chegar nesta parte em um instante), é só conectar o PICKit3 na PIC-EK e fazer o download do programa.
Para programar, eu tinha a opção de usar o Mikro C pro ou o MPLABx. A vantagem do MikroC é que tem uma infinidade de biblioteca pronta no compilador, mas para ter acesso a versão completa (mais de 32k de programa) tem que pagar uma licença de 250 dolares (1000 reais mais ou menos). O MPLAB é de graça, dá mais trabalho, mas é de graça. Eu vou usar o MPLAB.
Faça o download do MPLAB® X IDE v5.25 (Link para windows), instale os drivers e vamos tirar a ferrugem.
Se voce já teve experiencia com criar um novo projeto, então pode ir pra parte de configuração dos bits. Se não, sugiro que você siga os seguintes passos:
1) Começe um novo projeto:
2) Escolha a familia de microcontrolador e o seu PIC
3) Selecione o compilador. Se esta á a primeira vez usando o MPLABx, você tem que clicar na opção Download XC8. (Eu já tinha feito isso e apenas selecionei o XC8)
4) Escolha um nome e o local do seu projeto (Esqueci de tirar printscreen, mas é bem tranquilo essa parte)
Pronto, seu projeto foi criado.
5) Agora, voce tem que clicar com o auxiliar em cima da pasta Sources e selecionar New>>main.c
6) Pronto, agora a gente tem um projeto e um main. Antes de começar a programar, a gente que mexer nos bits de configuração (Alerta: se vc não tem experiencia com programação, esta parte pode parecer bastante confusa, mas não é nada de bixo de sete cabeças. O microcontrolador é um dispositivo muito flexivel, e você tem que "ajustar" as suas preferencias para que tudo funcione direitinho. Para isso, (infelizmente, ou felizmente) você vai precisar ler o datasheet do microcontrolador.
7) bit de configuração: Clique na aba.
8) Neste projeto, eu modifique apenas 3 bits: oscilador (HSMP), watchdog (OFF) e, PORTB AD (OFF)
9) Clique em gerar código (Generate Source Code.. )
10) Copie e cole o codigo no programa
Passo 11) Pronto! Ufa, até que em fim. Agora a gente pode começar a programar!
Daí é só compilar (no martelinho), conectar o PICKit3 na PIC-EK e clicar no icone com a setinha verde apontando pra baixo (Make and program)
Uma janela vai aparecer para você selecionar o seu programador (PICKit3)
Alguns microcontroladores são em 3.3V e outros em 5V. O PIC18F45k22 é em 5V. Esta oção, eu apenas cliquei OK. (Não sou responsável se vc queimar seu PIC por causa de voltagem errada. Leia tudo com atenção e seja sempre cauteloso!)
Aqui está o resultado:
Espero que vocês tenham conseguido seguir o passo à passo e tirar a ferrurem dos bits ai do microcontrolador PIC. Por favor, postem comentários com dúvidas, sugestões de programas e melhorias.
Proximos passos:
Colocar o códico no github (publico)
Criar um arquivo .h para as funções de configuração.
Explorar rotinas de LED com pushbutton e rotinas de interrupção de timer e hardware.
Olá pessoal, Já tem um tempo que eu não posto nada aqui no blog. Muita coisa aconteceu desde o último post. Eu vou fazer uma série de posts depois sobre as minhas aventuras e projetos que ocorreram nestes meio tempo. Eu tenho quatro objetivos nesta fase nova do Blog do Borba: 1) Postar uma série de projetos usando diferentes microcontroladores (PIC, Arduino, Texas Instruments, ST). 2) Explorar novos projetos de Internet das Coisas (sempre montando o passo a passo). 3) Explorar machine learning e inteligencia articicial, especialmente focado em vídeo. 4) Explorar e testar ultra-baixo consumo de potencia em sistemas embarcados. Os posts sempre serão em português e em inglês. Eu vou fazer o meu melhor para ter pelo menos um post novo por semana. Abraços, ~Borba! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Hi everyone, It has been a while that I have not posted anything here in my DIY blog. I started this years ago and now I am back. I have three main goals for this blog: 1) Post a series of projects with microcontrollers (PIC, Arduino, Texas Instruments, ST) 2) Explore the Internet of Things (IoT) projects and always leave good tutorials on how you can do it yourself. 3) Explore machine learning and artificial intelligence applications focused on video and image processing. 4) Explore and test ultra-low power solutions for embedded systems. I will be always posting in Portuguese and English. I will do my best to write a new post every week. I hope you enjoy! Cheers, ~Borba!