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.  







terça-feira, 5 de novembro de 2019

Blink - PIC18F - MPLABX - PICkit3



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)



9) Click on Generate Source Code ..




10) Copy and paste the code into the program.











Step 11) Ready! Now we can start programming!


In this project, I just want to blink (flash) some LEDs that I will connect to port B. I used the code similar to this website:https://www.exploreembedded.com/wiki/PIC_I/O_Register_Configuration

#include <xc.h>

void DELAY_ms(unsigned int ms_Count);

int main()
{
  TRISB = 0; //RB0 as Output PIN
  while(1)
  {
    PORTB = 0xFF;  // LED ON
    DELAY_ms(100); // 100 ms Delay
    PORTB = 0x0;  // LED OFF
    DELAY_ms(100); // 100 ms Delay
  }
  return 0;
}
void DELAY_ms(unsigned int ms_Count)
{
    unsigned int i,j;
    for(i=0;i<ms_Count;i++)
    {
        for(j=0;j<100;j++);
    }
}

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.


Cheers!






quinta-feira, 24 de outubro de 2019

Removendo a poeira do microcontrolador!


Blink - PIC18F - MPLABX - PICkit3

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!

Neste projeto, eu quero apenas piscar alguns leds que eu vou conectar na porta B. Eu usei o codigo similar ao deste website: https://www.exploreembedded.com/wiki/PIC_I/O_Register_Configuration

#include <xc.h>

void DELAY_ms(unsigned int ms_Count);

int main()
{
  TRISB = 0; //RB0 as Output PIN
  while(1)
  {
    PORTB = 0xFF;  // LED ON
    DELAY_ms(100); // 100 ms Delay
    PORTB = 0x0;  // LED OFF
    DELAY_ms(100); // 100 ms Delay
  }
  return 0;
}
void DELAY_ms(unsigned int ms_Count)
{
    unsigned int i,j;
    for(i=0;i<ms_Count;i++)
    {
        for(j=0;j<100;j++);
    }
}


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.

Abraços!






Tirando a ferrugem... Getting rid of the rust!

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!






quarta-feira, 19 de junho de 2013

Arduino, Lógica Fuzzy!!! Sensacional!!

O arduino, é uma plataforma de desenvolvimento muito simples para grandes aplicações de engenharia.

Mas, a verdadeira beleza das coisas está na simplicidade.

E apesar de inicialmente parecer uma coisa bastante complexa, a lógica fuzzy é bastante simples de implementar utilizando o arduino.

A principal referência está endereço: http://www.zerokol.com/2012/09/arduinofuzzy-uma-biblioteca-fuzzy-para.html. É um excelente tutorial sobre uma biblioteca de lógica fuzzy para qualquer microcontrolador. Para os curiosos, no link acima, tem uma breve explicação sobre fuzzy, um tutorial explicando como instalar a biblioteca, e também algumas explicações e dicas.


Acabei de desenvolver um sistema de controle de luminosidade utilizando lógica fuzzy.

É bem simples!!

Figura 1 - Sistema Iluminação Automática com Fuzzy

O sistema da figura 1 é composto por um divisor de tensão formado por um LDR e uma resistencia, alimentados no +5V (Figura 2). E como fonte de luz, um led com um resistor de limitação de corrente.
Figura 2 - Divisor de tensão com o LDR
 Depois que instalei a biblioteca no meu arduino, começei a editar o exemplo e consegui executar o programa.

Gostaria de compartilhar aqui as regras de  entrada.

No Fuzzy, a programação é assim, por exemplo: Se Escuro Então BrilhoLED Elevado.

Primeiro, criei 3 situações para a  Iluminação : Escuro, Normal e Iluminado. Lembrando que Iluminação é a saída do sensor LDR. E é portanto a variável de entrada do sistema.

E depois criei 3 condições de saída, ou seja, para o brilho do led: Baixo, Medio, Elevado.

E por fim, criei as regras:

          "SE iluminacao = escuro ENTAO Brilho do LED = elevado"

           "SE iluminacao = normal ENTAO Brilho do LED = medio"

           "SE iluminacao = Iluminado ENTAO Brilho do LED = baixo"


Bem, Definidas as minhas regras, aí os próximos passos, vou apenas citar, mas prometo que num próximo tutorial explico tudo, mas adianto que no link que citei no anterior do artigo tem algumas explicações. Em fim, os passos são:

Fuzzyficar, Inferir, Defuzzificar.

No arduino, os comandos utilizados foram:

  float iluminacao_medida = (analogRead(LDR))*0.09765;  //0.09765 = 100/1024
 
  fuzzy->setInput(1,iluminacao_medida  ); // iluminação medida é a variável de entrada
     
  fuzzy->fuzzify();

 int output = fuzzy->defuzzify(1);

   analogWrite(9,output); // onde output é a saída PWM e varia de 0-255

//***********


Resultados Obtidos

Na figura 3a e 3b, o sistema  encontra - se no escuro, logo o Brilho é Elevado.

Figura 3a - Sensor no Escuro - Brilho Elevado 
Na figura 3b, a forma de onda amarela é o sinal de saída do PWM que aciona o LED. E a forma de onda azul é o sinal de tensão divisor de tensão, tal como mostrado na figura 2. 

A forma de onda amarela é o PWM ( 0 à 255) e a curva azul é a tensão do sensor
Figura 3b - Formas de onda - Escuro
 Na figuras 4a e 4b, o sensor está um ambiente iluminado, logo o pwm (curva amarela) é menor, tal como na figura 4b

Figura 4a - Ambiente Iluminado
Figura 4b - Ambiente iluminado -> Brilho Baixo
 A figura 5a mostra uma tentativa de simular uma condição de baixa luminosidade (tampei o sensor com o dedo), mas o sistema não está totalmente escuro.

Figura 5a - Condição de Baixa luminosidade
E por fim, as formas de onda. A tensão no sensor  caiu e o pwm aumentou, aumentando assim o briho do led. 

Figura 5b - Aumento do brilho do LED
***********************************************************************************
Finalizo deixando aqui o código para que você tenha acesso à informação assim como eu tive. Perdoe-me por erros indevidos, e também por algumas coisas que não consegui deixar claro, principalmente em relação ao processo fuzzy. Apesar disso, estou à disposição para tirar dúvidas por email.

Um abraço

**********
#include <FuzzyRule.h>
#include <FuzzyComposition.h>
#include <Fuzzy.h>
#include <FuzzyRuleConsequent.h>
#include <FuzzyOutput.h>
#include <FuzzyInput.h>
#include <FuzzyIO.h>
#include <FuzzySet.h>
#include <FuzzyRuleAntecedent.h>


int iluminacao_saida = 0;

int LDR = 5;// Sensor de iluminacao

int initPin = 13;

unsigned long pulseTime = 0;

// Instanciando um objeto da biblioteca
Fuzzy* fuzzy = new Fuzzy();

void setup(){
  Serial.begin(9600);
 
  // set init pin as output
  pinMode(initPin, OUTPUT);
  // set sensor lm35 como entrada


  // create array loop to iterate over every item in the array
  for (int thisReading = 0; thisReading < numOfReadings; thisReading++) {
    readings[thisReading] = 0;
  }
 
  // Criando o FuzzyInput iluminacao
 
  FuzzyInput* iluminacao = new FuzzyInput(1);

  // Criando os FuzzySet que compoem o FuzzyInput iluminacao
 
  FuzzySet* escuro = new FuzzySet(0, 40, 40, 65); // iluminacao escuro 15° 35°
  iluminacao->addFuzzySet(escuro); // Adicionando o FuzzySet escuro em iluminacao

  FuzzySet* normal = new FuzzySet(30, 50, 50, 70); // iluminacao normal
  iluminacao->addFuzzySet(normal); // Adicionando o FuzzySet normal em iluminacao

  FuzzySet* Iluminado = new FuzzySet(60, 80, 80, 100); // iluminacao muito normal
  iluminacao->addFuzzySet(Iluminado); // Adicionando o FuzzySet Iluminado em iluminacao
 
  fuzzy->addFuzzyInput(iluminacao); // Adicionando o FuzzyInput no objeto Fuzzy
 
 
  // Criando o FuzzyOutput Brilho da LED
 
  FuzzyOutput* brilho = new FuzzyOutput(1);
   
    // Criando os FuzzySet que compoem o FuzzyOutput Brilho do LED
   
    FuzzySet* baixo = new FuzzySet(0, 80, 80, 130); // Brilho do LED baixo
    brilho->addFuzzySet(baixo); // Adicionando o FuzzySet baixo em brilho
   
    FuzzySet* medio = new FuzzySet(70, 150, 150, 200); // Brilho do LED normal
    brilho->addFuzzySet(medio); // Adicionando o FuzzySet medio em brilho
   
    FuzzySet* elevado = new FuzzySet(150, 190, 255, 255); // Brilho do LED elevado
    brilho->addFuzzySet(elevado); // Adicionando o FuzzySet elevado em brilho
 
    fuzzy->addFuzzyOutput(brilho); // Adicionando o FuzzyOutput no objeto Fuzzy
 
  //-------------------- Montando as regras Fuzzy
 
  // FuzzyRule "SE iluminacao = escuro ENTAO Brilho do LED = Elevado"
 
  FuzzyRuleAntecedent* ifiluminacaoescuro = new FuzzyRuleAntecedent(); // Instanciando um Antecedente para a expresso
  ifiluminacaoescuro->joinSingle(escuro); // Adicionando o FuzzySet correspondente ao objeto Antecedente
 

    FuzzyRuleConsequent* thenbrilhoelevado = new FuzzyRuleConsequent(); // Instancinado um Consenormal para a expressao
  thenbrilhoelevado->addOutput(elevado);// Adicionando o FuzzySet correspondente ao objeto Consenormal
 
 
  // Instanciando um objeto FuzzyRule
  FuzzyRule* fuzzyRule01 = new FuzzyRule(1, ifiluminacaoescuro, thenbrilhoelevado); // Passando o Antecedente e o Consenormal da expressao
  fuzzy->addFuzzyRule(fuzzyRule01); // Adicionando o FuzzyRule ao objeto Fuzzy
 
  // FuzzyRule "SE iluminacao = normal ENTAO Brilho do LED = medio"
  FuzzyRuleAntecedent* ifiluminacaonormal = new FuzzyRuleAntecedent(); // Instanciando um Antecedente para a expresso
  ifiluminacaonormal->joinSingle(normal); // Adicionando o FuzzySet correspondente ao objeto Antecedente
 
  FuzzyRuleConsequent* thenbrilhomedio = new FuzzyRuleConsequent(); // Instancinado um Consenormal para a expressao
  thenbrilhomedio->addOutput(medio);// Adicionando o FuzzySet correspondente ao objeto Consenormal
 
  // Instanciando um objeto FuzzyRule
  FuzzyRule* fuzzyRule02 = new FuzzyRule(2, ifiluminacaonormal, thenbrilhomedio); // Passando o Antecedente e o Consenormal da expressao
  fuzzy->addFuzzyRule(fuzzyRule02); // Adicionando o FuzzyRule ao objeto Fuzzy
 
  // FuzzyRule "SE iluminacao = Iluminado ENTAO Brilho do LED = baixo"
 
  FuzzyRuleAntecedent* ifiluminacaoIluminado = new FuzzyRuleAntecedent(); // Instanciando um Antecedente para a expresso
  ifiluminacaoIluminado->joinSingle(Iluminado); // Adicionando o FuzzySet correspondente ao objeto Antecedente


   FuzzyRuleConsequent* thenbrilhobaixo = new FuzzyRuleConsequent(); // Instancinado um Consenormal para a expressao
  thenbrilhobaixo->addOutput(baixo);// Adicionando o FuzzySet correspondente ao objeto Consenormal
 
  // Instanciando um objeto FuzzyRule
 
  FuzzyRule* fuzzyRule03 = new FuzzyRule(3, ifiluminacaoIluminado, thenbrilhobaixo); // Passando o Antecedente e o Consenormal da expressao
  fuzzy->addFuzzyRule(fuzzyRule03); // Adicionando o FuzzyRule ao objeto Fuzzy
}

void loop(){
  // send 10 microsecond pulse
  digitalWrite(initPin, HIGH);
  // wait 10 microseconds before turning off
  delayMicroseconds(10);
  // stop sending the pulse
  digitalWrite(initPin, LOW);
 

  float iluminacao_medida = (analogRead(LDR))*0.09765;
 
  fuzzy->setInput(1,iluminacao_medida  );
     
  fuzzy->fuzzify();

 int output = fuzzy->defuzzify(1);
   analogWrite(9,output);

  Serial.print(" iluminacao: ");
  Serial.print(iluminacao_medida);
  Serial.print(" Brilho do LED: ");
  Serial.println(output*0.39215);
  Serial.print(" % ");
  // wait 100 milli seconds before looping again
  delay(100);
}