Pesquisar neste blog

16/12/2023

Sensor DTH22 com ESP32




CÓDIGO

#include <WiFi.h>
#include <Wire.h>
#include "DHTesp.h"
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#define DHT_PIN 4  // Pin onde o sensor DHT22 está conectado

float temperatura, umidade;

DHTesp dht;
Adafruit_BME280 bme;

const char* ssid = "TELETURBO-TQ936";
const char* password = "KV138076";

void setup() {
  Serial.begin(115200);
  delay(1000);
  
  // Inicializa o sensor DHT22
  dht.setup(DHT_PIN, DHTesp::DHT22);

   //Inicializa o sensor BME280
  
  //Código acima esta como comentario para fins de simulação

   //Conecta-se à rede Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Conectando à rede WiFi...");
  }
  Serial.println("Conectado à rede WiFi");
}

void loop() {
  // Leitura do sensor DHT22
  temperatura = dht.getTemperature();
  umidade = dht.getHumidity();
  
  Serial.print("Temperatura: ");
  Serial.print(temperatura);
  Serial.println(" °C");
  Serial.print("Umidade: ");
  Serial.print(umidade);
  Serial.println(" %");

  delay(5000);
}

02/12/2023

Inserindo dados na tablela com PHP + ESP32 #10

Saída gerada no phpMyAdmin4















<?php
    $hostname = "localhost";
    $username = "root";
    $password = "";
    $database = "sensor_db";

    $conn = mysqli_connect($hostname, $username, $password, $database);

    if (!$conn) {
        die("Connection failed: ".mysqli_connect_error());
    }

    echo "Database connection is OK";
    echo ('<br>');

    $sql = "INSERT INTO dht11 (temperature, humidity) VALUES (24, 45)";

    if (mysqli_query($conn, $sql)) {
        # code...
        echo "\n";
        echo "\nNovo registro criado com sucesso !";
    }else {
        echo "\nErro: ". $sql . "<br>" .mysqli_error($conn);
    }
?>



Código em linguagem C para o ESP32:

//https://www.youtube.com/watch?v=VEN5kgjEuh8&ab_channel=AhmadLogs

#include <WiFi.h>
#include <HTTPClient.h>

String URL = "http://192.168.1.12/5 Esp32-Temperatura/test_data.php";

const char* ssid = "XXXX";
const char* password = "XXX";

int temperature = 50;
int humidity = 70;

void setup(){
  Serial.begin(115200);
  connectWiFi();
  
}

void connectWiFi(){
  WiFi.mode(WIFI_OFF);
  delay(1000);

  WiFi.mode(WIFI_STA);

  WiFi.begin(ssid, password);
  Serial.println("Conectando no WiFi");

  while(WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
  }

  Serial.print("Conectado em: "); Serial.println(ssid);
  Serial.print("IP address: "); Serial.println(WiFi.localIP());
  delay(1000);
  
}

void loop(){
  if(WiFi.status() != WL_CONNECTED){
    connectWiFi();
 }

  String postData = "Temperatura = "+String(temperature)+"&humidity="+ String(humidity);

  HTTPClient http;
  http.begin(URL);

  int httpCode = http.POST(postData);
  String payload = http.getString();
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  
  Serial.print("URL: ");Serial.print(URL);
  Serial.print("Data: ");Serial.print(postData);
  Serial.print("httpCode: ");Serial.print(httpCode);
  Serial.print("payload: ");Serial.print(payload);
  Serial.println("-------------------");
  delay(4000);
}

26/11/2023

Fonte linear retificadora

Objetivo: Desenvolver 1 fonte retificadora de 5 V .




Dados: 

Trafo = 24 V
Itrafo = 1 A
30% de Vcp


VCP:

Vp = Vs x 2 = 24 x √2
Vp = 33,94 V

Vcp = Vp - 2 x 0,7 = 33,94 - 2 x 0,2
Vcp = 32,54 V


CAPACITÂNCIA:

C = I / ( 2 x f x Vpp )
C = 1 / ( 2 x 60 (32,54 x 30% )
C = 853 uF = 900 uF

TENSÃO DE ISOLAÇÃO DO CAPACITOR:

Vcap = ( 32,54 x 50% ) + 32,43
Vcap = 48,81 V = 50 V


FUSÍVEL:

Psec = Vsec x Ic = 24 x 1
Psec = 24 W

Ipri = Vpri / Vpri = 24 / 127
Ipri = 378 mA


Saída gerada















09/07/2023

LCD CGRAM com método avançado

Objetivo: Fazer uma animação no LCD cgram utilizando matriz para reduzir linhas de código.

LCD cgram com matriz





















Código feito em CCS C Compiler

#include <16F877A.h>
#use delay(clock = 20MHz)
#include <lcd.c>
#define LIN 12 // limite que a RAM consegue processar
#define COL 8

int matriz[LIN][COL] = {
{0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000},
{0b00000, 0b01000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000},
{0b00000, 0b01110, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000},
{0b00000, 0b01110, 0b00001, 0b00000, 0b00000, 0b00000, 0b00000},
{0b00000, 0b01110, 0b00001, 0b00001, 0b00001, 0b00000, 0b00000},
{0b00000, 0b01110, 0b00001, 0b00001, 0b00001, 0b00001, 0b00000},
{0b00000, 0b01110, 0b00001, 0b00001, 0b00001, 0b00001, 0b00010},
{0b00000, 0b01110, 0b00001, 0b00001, 0b00001, 0b00001, 0b01110},
{0b00000, 0b01110, 0b00001, 0b00001, 0b00001, 0b10001, 0b01110},
{0b00000, 0b01110, 0b00001, 0b00001, 0b10001, 0b10001, 0b01110},
{0b00000, 0b01110, 0b00001, 0b10001, 0b10001, 0b10001, 0b01110},
{0b00000, 0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110}  
};

void main(){
   lcd_init();
         
   while(TRUE){
   /*
      //matriz[0][i];
      lcd_set_cgram_char(0, matriz[i]);
      printf(lcd_putc, "\f%c \t\ni = %d", 0, i);
      delay_ms(1000);
      
      i++;
      if(i >= LIN){ i = 0;}*/
      for(int i = 0; i < COL; i++){        
         for(int j = 0; j < LIN; j++){
            
            lcd_set_cgram_char(0, matriz[j]);
            lcd_gotoxy(1, 1);
            printf(lcd_putc, "\f%c \t[%d][%d]", 0, i, j);
            
            delay_ms(500);
            
         }
      }
   }
}

29/06/2023

CRUD com PHP

Objetivo: Fazer um CRUD em PHP

Saída do designer em PHP














Arquivo 1: cadastrar_pessoa.php

<?php
// 6 funções
Class Pessoa{


    private $pdo;
    // CONEXÃO COM O BANCO DE DADOS
    public function __construct($dbname, $host, $user, $senha) // tudo ok
    {
        try
        {
            $this->pdo = new PDO("mysql:dbname=".$dbname.";host=".$host,$user);
        }
        catch (PDOException $e) {//erro para o PDO
            echo "Erro com o Banco de Dados: ".$e->getMessage();
            exit();
        }
        catch(Exception $e){ // Erros genéricos
            echo "Erro genérico: ".$e->getMessage();
            exit();
        }
    }
    //------- BUSCAR DADOS E EXIBIR NO LADO DIREITO DA TELA ----------
    public function buscarDados() // tudo ok
    {
        $res = array();
        $cmd = $this->pdo->query("SELECT * FROM pessoa ORDER BY id");
        $res = $cmd->fetchAll(PDO::FETCH_ASSOC);// economiza memória
        return $res;
    }
    // FUNÇÃO DE CADASTRAR PESSOAS NO BANCO DE DADOS
    public function cadastrarPessoa($nome, $telefone, $email)
    {
        // Antes de cadastrar verificar se já tem o EMAIL cadastrado
        $cmd = $this->pdo->prepare("SELECT id FROM pessoa WHERE email = :e");
        $cmd->bindValue(":e", $email);
        $cmd->execute();
        if ($cmd->rowCount() > 0)  //se > 0 email já existe no BD
        {
            return false;
        }else  // não foi encontrado no BD
        {
            $cmd = $this->pdo->prepare("INSERT INTO pessoa(nome, telefone, email)
            VALUES (:n, :t, :e)");
            $cmd->bindValue(":n", $nome);
            $cmd->bindValue(":t", $telefone);
            $cmd->bindValue(":e", $email);
            $cmd->execute();
            return true;
        }
    }
    // MÉTODO PARA EXCLUIR PESSOA
    public function excluirPessoa($id) // tudo ok
    {
        $cmd = $this->pdo->prepare("DELETE FROM pessoa WHERE id = :id");
        $cmd->bindValue(":id", $id);
        $cmd->execute();
    }

    // BUSCAR DADOS DE UMA PESSOA
    public function buscarDadosPessoa($id) // tudo ok
    {
        $res = array();
        $cmd = $this->pdo->prepare("SELECT * FROM pessoa WHERE id = :id");
        $cmd->bindValue(":id", $id);
        $cmd->execute();
        $res = $cmd->fetch(PDO::FETCH_ASSOC);//economiza memória
        return $res;
    }

    // ATUALIZAR DADOS NO BANCO DE DADOS
   
    public function atualizarDados($id, $nome, $telefone, $email){ // tudo ok
       
        $cmd = $this->pdo->prepare("UPDATE pessoa SET nome = :n, telefone = :t,
        email = :e WHERE id = :id");
        $cmd->bindValue(":n", $nome);
        $cmd->bindValue(":t", $telefone);
        $cmd->bindValue(":e", $email);
        $cmd->bindValue(":id", $id);
        $cmd->execute();
    }
}
?>


Arquivo 2: index.php

<?php
require_once 'classe_pessoa.php';
$p = new Pessoa("crudpdo", "localhost", "root", "");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cadastro de Pessoa</title>
    <link rel="stylesheet" href="estilo.css">
</head>
<body>
    <?php
    if (isset($_POST['nome']))
    //CLICOU NO BOTÃO CADASTRAR OU EDITAR
    {
        if (isset($_GET['id_up']) && !empty($_GET['id_up']))
        {
            $id_upd = addslashes($_GET['id_up']);
            $nome = addslashes($_POST['nome']);
            $telefone = addslashes($_POST['telefone']);
            $email = addslashes($_POST['email']);
            if (!empty($nome) && !empty($telefone) && !empty($email))
            {
                $p->atualizarDados($id_upd, $nome, $telefone, $email);
               
                header("location: index.php");
            }
            else
            {
                ?>
                    <div class="aviso">
                        <img src="aviso.png" alt="">
                        <h4>Preencha todos os campos !</h4>
                    </div>
                <?php
            }
        }
        // ---------------------------- CADASTRAR ----------------------------
        else
        {
            $nome = addslashes($_POST['nome']);
            $telefone = addslashes($_POST['telefone']);
            $email = addslashes($_POST['email']);
            if(!empty($nome) && !empty($telefone) && !empty($email))
            {
                //cadastrar
                if (!$p->cadastrarPessoa($nome, $telefone, $email))
                {
                    ?>
                        <div>
                            <img src="aviso.png" alt="">
                            <h4>Email já está cadastrado !</h4>
                        </div>
                    <?php
                }
            }
            else
            {
                ?>
                    <div class="aviso">
                        <img src="aviso.png" alt="">
                        <h4>Preencha todos os campos !</h4>
                    </div>
                <?php
            }
        }
    }
    ?>
    <?php
        if (isset($_GET['id_up'])) //SE A PESSOA CLICOU EM EDITAR
        {
            $id_update = addslashes($_GET['id_up']);
            $res = $p->buscarDadosPessoa($id_update);
        }

    ?>
    <section id = "esquerda">
        <form action="" method = "POST">
            <h2>CADASTRAR PESSOA</h2>
            <label for="nome">Nome</label>
            <input type="text" name = "nome" id = "nome"
            value="<?php if(isset($res)){echo $res['nome'];} ?>">
           
            <label for="telefone">Telefone</label>
            <input type="text" name="telefone" id="telefone"
            value="<?php if(isset($res)){echo $res['telefone'];} ?>">

            <label for="email">Email</label>
            <input type="email" name="email" id="email"
            value= "<?php if(isset($res)) {echo $res['email']; } ?>">

            <input type="submit"
            value= "<?php if (isset($res)) { echo "Atualizar"; }else { echo
    "Cadastrar"; } ?>">
        </form>
    </section>
    <section id="direita">
        <table>
            <tr id="titulo">
                <td>NOME</td>
                <td>TELEFONE</td>
                <td colspan="2">EMAIL</td>
            </tr>
            <?php
                $dados = $p->buscarDados();
                if(count($dados) > 0)//TEM PESSOAS NO BANCO DE DADOS
                {
                    for($i=0; $i < count($dados); $i++)
                    {
                        echo "<tr>";
                        foreach ($dados[$i] as $k => $v)
                        {
                            if($k != "id")
                            {
                                echo "<td>".$v."</td>";
                            }
                        }
                        ?>
                            <td>
                                <?php echo $dados[$i]['id'] ?>                              
                                <a href="index.php?id_up=<?php echo $dados[$i]['id']; ?>">Editar</a>
                                <a href="index.php?id=<?php echo $dados[$i]['id']; ?>">Excluir</a>
                            </td>
                        <?php
                        echo "</tr>";
                    }                    
                }
                else // O BANCO DE DADOS ESTÁ VAZIO
                {
                    ?>
                    </table>

                        <div class="aviso">
                            <h4>Ainda não há pessoas cadastradas !</h4>
                        </div>
                    <?php
                }
            ?>
        </table>
    </section>
</body>
</html>

<?php
    if (isset($_GET['id'])) {
        $id_pessoa = addslashes($_GET['id']);
        $p->excluirPessoa($id_pessoa);
        header("location: index.php");//atualiza a página após o clique
    }
?>


Arquivo 3: estilo.css

*{
    padding: 0px;
    margin: 0px;
    font-family: arial;
}

label, input{
    display: block;
    line-height: 30px;
    height: 30px;
    outline: none;
    font-size: 13pt;
    width: 100%;
}

form{
    width: 330px;
    background-color: rgba(0, 0, 0, 0.2);
    padding: 20px;
    margin: 30px auto; /*automático dos lados*/
}

input[type="submit"]{
    margin-top: 10px;
    cursor: pointer;
}

#esquerda{
    width: 35% ;
    height: 500px;
    float: left;
}

h2{
    text-align: center;
}

#direita{
    margin-top: 30px;
    width: 65%;
    height: 500px;
    float: left;

}

table {
    background-color: rgba(0, 0, 0, 0.2);
    width: 90%;
    margin: auto;
}

tr{
    line-height: 30px;
}

tr#titulo{
    font-weight: bold;
    background-color: rgba(0,0,0, .6);
    color: white;
}

td{
    padding: 0px 5px;
}

a{
    background-color: white;
    color: black;
    padding: 5px;
    margin: 0px 5px;
    float: left;
}

.aviso {
   
    width: 90%;
    height: 50px;
    margin: 30px auto 0px auto; /* margin no auto */
}
img {
    width: 50px;
    display: block;
    float: left; /*flutuar à esquerda*/
}
h4{
    float: left;
    line-height: 50px;
}


Créditos para: Mirian TechCod


18/06/2023

Frequência em motor de passo com PIC 16F877A

Objetivo: Fazer um motor de passo com os seguintes requisitos :
1. O motor de passo deve girar no sentido horário ou anti-horário
2. Sua velocidade de rotação deve ser controlada por um potenciômetro
3. Deve ser acionada por 2 botões
4. Deve ser informada os dados no display LCD:
  • Posição do ângulo
  • Dados da frequência angular em que está girando
  • Dados da frequência em Hz em que está girando
5. Se o motor estiver off, deverá ser acionado 1 Led e desligar os demais
6. Se o motor estiver ON no sentido horário deverá ser acionado o Led 2 e desligar os demais
7, Se o motor estiver ON no sentido anti-horário, deverá ser acionado o Led 3 e desligar os demais
8. Se o motor estiver off, deverá informar no Display LCD a quantidade de tempo e dias parado.

Resolução feita em CCS C Compiler e software Protheus
Circuito para identificar 1 ciclo de trabalho
















Circuito
























Simulação feita no Protheus 7.9


CÓDIGO FEITO EM CCS C Compiler

#include <16F877A.h>
#device adc = 8
#use delay(clock = 20MHz)
#FUSES NOWDT, HS, NOPUT, NOPROTECT, NODEBUG, BROWNOUT, NOLVP, NOCPD, NOWRT, NOWRT
#include <lcd.c>
#define size 8

#define PIN_1 PIN_C4
#define PIN_2 PIN_C5
#define PIN_3 PIN_C6
#define PIN_4 PIN_C7

unsigned int A, B, i = 0, POSITION;
unsigned int16 VALUE;
unsigned int8 MOTOR[size] = {64, 96, 32, 48, 16, -112, -128, -64};
unsigned int16 posicao1[size] = {45, 90, 135, 180, 225, 270, 315, 360};
unsigned int16 posicao2[size] = {360, 315, 270, 225, 180, 135, 90, 45};
unsigned int DIAS, HORAS, MINUTOS, SEGUNDOS = 0;

char setaH[size] = {
    0b00000,
    0b00100,
    0b00110,
    0b11111,
    0b00110,
    0b00100,
    0b00000,
    0b00000
};

char setaA[size] = {
    0b00000,
    0b00100,
    0b01100,
    0b11111,
    0b01100,
    0b00100,
    0b00000,
    0b00000
};

char graus[size] = {
   0b00110,
   0b01001,
   0b00110,
   0b00000,
   0b00000,
   0b00000,
   0b00000,
   0b00000
};

int1 nuevopulso = 0, cambio = 0;
int16 TFB = 0, TFS = 0, TF = 0;
float TEMPO = 0.0, frequencia;

#int_ccp1
void ccp1_int(){
   if(cambio == 0){
      TFS = CCP_1;
      setup_ccp1(CCP_CAPTURE_RE);
      cambio = 1;
   }else{
      TFB = CCP_1;
      setup_ccp1(CCP_CAPTURE_RE);
      cambio = 0;
      
      if(nuevopulso == 0){
         nuevopulso = 1;
      }
   }
}

#INT_TIMER0
void  TIMER0_isr(void) {
   
   if (nuevopulso >= 1){
      TF = (TFB - TFS);
      TEMPO = TF * 1.0 / 1000.0;
      frequencia = 1.0 / (TEMPO / 1000.0);
      nuevopulso = 0;
   }
   
}

#INT_TIMER1
void  TIMER1_isr(void) {
   A = input(PIN_B0);
   B = input(PIN_B1);
   
}

void main(){
   
   setup_adc_ports(AN0);
   setup_adc(ADC_CLOCK_DIV_2);
   setup_timer_0(T1_DIV_BY_1); 
   setup_timer_1(T1_INTERNAL|T1_DIV_BY_1);      //13,1 ms overflow
   
   setup_ccp1(CCP_CAPTURE_RE);
   enable_interrupts(int_ccp1);
   
   enable_interrupts(INT_TIMER1);
   enable_interrupts(INT_TIMER0);
   enable_interrupts(GLOBAL);
      
   lcd_init();
   lcd_set_cgram_char(4, graus);
   
   while(TRUE) {
      output_high(PIN_B5);
      output_low(PIN_B6);
      output_low(PIN_B7);
      
      SEGUNDOS++;
      if ( SEGUNDOS > 59 ){SEGUNDOS = 0 ; MINUTOS++ ;}
      if ( MINUTOS > 59 ){MINUTOS = 0 ; HORAS++ ; }
      if ( HORAS > 23 ) {HORAS = 0 ; DIAS++ ; }
           
      lcd_gotoxy(1, 1);
      printf(lcd_putc,"\f\t\t\tMOTOR OFF !");
      
      lcd_gotoxy(1, 2);
      printf(lcd_putc, "%02u:%02u:%02u",HORAS, MINUTOS, SEGUNDOS);
      
      lcd_gotoxy(21, 1);
      printf(lcd_putc, "DIAS PARADO: %u",DIAS);
      
      delay_ms(1000);
      
      while(A == 1 && B == 0){
         output_high(PIN_B6);
         output_low(PIN_B7);
         output_low(PIN_B5);
         
         VALUE = read_adc();
         
         lcd_set_cgram_char(2, setaH);
         lcd_gotoxy(1, 1);
         printf(lcd_putc, "\f\t\tMOTOR ON ! \t%c", 2);
         
         lcd_gotoxy(1, 2);
         printf(lcd_putc,"ANGULO = [%lu%c]" posicao1[i], 4);
         
         lcd_gotoxy(21, 1);
         printf(lcd_putc,"W = %.2f rad/s", frequencia * 2 * 3.1415);
         
         lcd_gotoxy(21, 2);
         printf(lcd_putc, "F = %.2f Hz", frequencia);
         
         POSITION = MOTOR[i];
         output_bit(PIN_1, POSITION & 16);
         output_bit(PIN_2, POSITION & 32);
         output_bit(PIN_3, POSITION & 64);
         output_bit(PIN_4, POSITION & 128);
         i = (i + 1) % (sizeof(MOTOR) / sizeof(int));
         
         delay_ms(VALUE);
      }
      
      while(A == 0 && B == 1){
         output_high(PIN_B7);
         output_low(PIN_B6);
         output_low(PIN_B5);
         
         VALUE = read_adc();
         
         lcd_set_cgram_char(3, setaA);
         lcd_gotoxy(1, 1);
         printf(lcd_putc, "\f%c\tMOTOR ON !", 3);
         
         lcd_gotoxy(1, 2);
         printf(lcd_putc,"ANGULO = [-%lu%c]" posicao2[i], 4);
         
         lcd_gotoxy(21, 1);
         printf(lcd_putc,"W = %.2f rad/s", frequencia * 2 * 3.1415);
         
         lcd_gotoxy(21, 2);
         printf(lcd_putc, "F = %.2f Hz", frequencia);
         
         POSITION = MOTOR[i];
         output_bit(PIN_4, POSITION & 128);
         output_bit(PIN_3, POSITION & 64);
         output_bit(PIN_2, POSITION & 32);
         output_bit(PIN_1, POSITION & 16);
         i = (i - 1) % (sizeof(MOTOR) / sizeof(int));
         
         delay_ms(VALUE);
      }
      
   }
}

11/06/2023

Inserir linhas no Google Sheets com JavaScript

Objetivo : Inserir uma quantidade X de linhas por comando da Planilha_1 para a Planilha_2 de outra URL da web com JavaScript.

Código feito no Google Sheets

function myFunction() {
  var url2 = "Insira sua url aqui !";
  var QtdlinhasDesejada = 2;

  var spreadsheet = SpreadsheetApp.openByUrl(url2);
  //spreadsheet.getRange('1:1').activate();
  spreadsheet.getActiveSheet().insertRowsBefore(spreadsheet.getActiveRange().getRow(),
QtdlinhasDesejada );
  //spreadsheet.getActiveRange().offset(0, 0, 1,
spreadsheet.getActiveRange().getNumColumns()).activate();//0 ,0, 1
  //spreadsheet.getRange('C9').activate();
 
};

Execução e saída gerada






09/06/2023

Mini teste 1 2022/2

1. Projete o circuito e o programa (compilador CCS) de um sistema baseado no microcontrolador PIC16F877A que faça a leitura da entrada analógica PIN_A0, via conversor AD configurado em 8 bits. O  sistema deve apresentar 7 níveis de alerta através de um dispositivo de 3 segmentos (figura 1).


























RESOLUÇÃO FEITA EM CCS C Compiler:



















#include <16F877A.h>
#device adc = 8
#use delay(clock = 20M)
#fuses XT, NOWDT, NOPROTECT, NOBROWNOUT, NOLVP, NOCPD, NOWRT, NODEBUG
#include <lcd.c>
unsigned int8 analog ;

#INT_TIMER0
void TIMER0_isr(void){
   if (analog >= 127 && analog < 142){ // N1
      output_low(PIN_B5);
      output_low(PIN_B6);
      output_toggle(PIN_B7);
   }
   if (analog >= 175 && analog < 191) { // N4
      output_toggle(PIN_B5);
      output_low(PIN_B6);
      output_low(PIN_B7);
   }
   if (analog >= 159 && analog < 175) { // N3
      output_low(PIN_B5);
      output_toggle(PIN_B6);
      output_toggle(PIN_B7);
   }
   if (analog >= 191 && analog < 207) { // N5
      output_toggle(PIN_B5);
      output_low(PIN_B6);
      output_toggle(PIN_B7);
   }
   if (analog >= 143 && analog < 159) { // N2
      output_low(PIN_B5);
      output_toggle(PIN_B6);
      output_low(PIN_B7);
   }
   if (analog >= 207 && analog < 223) { // N6
      output_toggle(PIN_B5);
      output_toggle(PIN_B6);
      output_low(PIN_B7);
   }
   if (analog >= 223 && analog < 239) { // N7
      output_toggle(PIN_B5);
      output_toggle(PIN_B6);
      output_toggle(PIN_B7);
   }
   
}

void main(){
   // Configuração do LCD
   lcd_init();

   // Configuração do ADC
   setup_adc_ports(AN0);
   setup_adc(ADC_CLOCK_DIV_8);
   set_adc_channel(0);
   
   setup_psp(PSP_DISABLED);
   setup_spi(SPI_SS_DISABLED);
   setup_timer_0(RTCC_INTERNAL | RTCC_DIV_2); // overflow 51,2 u
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);
   enable_interrupts(INT_TIMER0);
   enable_interrupts(GLOBAL);
   
   while (1){
      analog = read_adc();
      printf(lcd_putc, "\fLeitura: %u", analog);
      delay_ms(1000); 
   }
}

Saída gerada






















2. Faça o circuito e o programa (compilador CCS) que liga um LED 1 e desliga o LED 2 quando um botão (Bot1) estiver apertado e desligar LED1 e liga o LED 2 se o botão (Bot1) estiver solvo. Os LED 3, 4 e 5 devem ficar piscando com frequências de 1.3, 2 e 3.5 vezes n Hz. Onde n é igual a soma do último e penúltimo número da sua matrícula.















RESOLUÇÃO FEITA EM CCS C Compiler :

#include <16F877A.h>
#use delay(clock = 20MHz)

// Configuração do microcontrolador
#fuses XT, NOWDT, NOPROTECT, NOBROWNOUT, NOLVP, NOCPD, NOWRT, NODEBUG
#include <lcd.c>
// Variáveis globais
int flag1 = 0, flag2 = 0;
unsigned int16 cont1 = 0, cont2 = 0, cont3 = 0;

#int_TIMER0
void TIMER0_isr(){
   if(flag1 == 0 && flag2 == 1 && ++cont1 >= 85){
      cont1 = 0; output_toggle(PIN_B5); // 114 Hz
   }
   if(flag1 == 0 && flag2 == 1 && ++cont2 >= 55){
      cont2 = 0; output_toggle(PIN_B6); // 176 HZ
   }
   if(flag1 == 0 && flag2 == 1 && ++cont3 >= 32){
      cont3 = 0; output_toggle(PIN_B7); // 308 Hz
   }
   
}
// Função de tratamento da interrupção do TIMER1
#int_timer1
void timer1InterruptHandler(){
   if (input(PIN_B0) == 1){
      flag1 = 1;
      flag2 = 0;
      output_high(PIN_B3);
      output_low(PIN_B4);
      
   }
   if(input(PIN_B1) == 1){
      flag1 = 0;
      flag2 = 1;
      output_low(PIN_B3);
      output_high(PIN_B4);
   }
   
   // Limpa a flag de interrupção do TIMER1
   clear_interrupt(INT_TIMER1);
}

void main(){
   // Configuração do TIMER1
   setup_timer_1(T1_INTERNAL | T1_DIV_BY_1);
   
   // Configuração das interrupções
   enable_interrupts(INT_TIMER1); // Habilita a interrupção do TIMER1
   enable_interrupts(GLOBAL);    // Habilita todas as interrupções globais
   
   setup_timer_0(RTCC_INTERNAL | RTCC_DIV_1); // overflow 51,2 us
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);
   enable_interrupts(INT_TIMER0);
   
   lcd_init();
   
   while (1){
      printf(lcd_putc,"\f%d : %d",flag1, flag2);
      delay_ms(50);
      
   }
}

Saída gerada