#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "pico/stdlib.h"
#include "hardware/uart.h"
#include "hardware/gpio.h"
#define UART_ID uart1
#define BAUD_RATE 9600
#define DATA_BITS 8
#define STOP_BITS 1
#define PARITY UART_PARITY_NONE
// Pinagem do sensor
#define UART_RX_PIN 13
// Variáveis globais para armazenar os valores
int ap = 0; // Potência Ativa (PAPP) - KW
int hchc = 0; // Horário Consumidor Fora de Pico - KWh
int hphc = 0; // Horário Ponta Consumidor (HPHC) - KWh
void process_line(char *line) {
// Exemplo de formato: "POTENCIA_ATIVA:2 kW"
char *label = strtok(line, ":");
char *value_str = strtok(NULL, " ");
if (label && value_str) {
int value = atoi(value_str);
// Atualização das variáveis com todos os rótulos
if (strcmp(label, "PAPP") == 0) {
ap = value; // Correlação PAPP -> ap
} else if (strcmp(label, "HCHC") == 0) {
hchc = value;
} else if (strcmp(label, "HPHC") == 0) { // Novo rótulo adicionado
hphc = value;
}
}
}
int main() {
stdio_init_all();
// Configuração inicial
printf("Iniciando a conexão...\n"); // Movido para fora do loop
// Configuração da UART
uart_init(UART_ID, BAUD_RATE);
gpio_set_function(UART_RX_PIN, GPIO_FUNC_UART);
uart_set_hw_flow(UART_ID, false, false);
uart_set_format(UART_ID, DATA_BITS, STOP_BITS, PARITY);
uart_set_fifo_enabled(UART_ID, false);
char buffer[256];
int buffer_index = 0;
while (true) {
// Leitura UART
while (uart_is_readable(UART_ID)) {
char c = uart_getc(UART_ID);
if (c == '\r') {
buffer[buffer_index] = '\0';
process_line(buffer);
buffer_index = 0;
} else if (buffer_index < sizeof(buffer) - 1) {
buffer[buffer_index++] = c;
}
}
// Exibição periódica
static absolute_time_t last_print = {0};
absolute_time_t now = get_absolute_time();
if (absolute_time_diff_us(last_print, now) >= 1000000) {
printf("\nLeitura dos Dados:\n");
printf("Potência Ativa: %d kW\n", ap);
printf("Consumo fora de pico: %d kWh\n", hchc);
printf("Consumo horário de pico: %d kWh\n\n", hphc);
last_print = now;
}
sleep_ms(1000);
}
return 0;
}