Projeto Final de Sistemas Embebidos — ESP32 simulation

Fix Rs calculation and remove clamping that forced 3290

An interactive ESP32 circuit simulation you can run free in your browser on Velxio, by joao-e-rafael-ribeiro.

Components

Sketch code

#include "config.h"

RTC_DS1307 rtc;
bool rtcOk = false;
bool sdOk  = false;

// Devolve a mensagem/motivo consoante o sinal recebido pelo ESP32
const char* motivoReinicio(esp_reset_reason_t motivo) {
  switch (motivo) {
    case ESP_RST_POWERON:   return "arranque normal (ligado à energia)";
    case ESP_RST_SW:        return "reinício por software";
    case ESP_RST_DEEPSLEEP: return "saída de deep sleep";
    case ESP_RST_PANIC:     return "reinício por erro do programa (panic)";
    case ESP_RST_INT_WDT:
    case ESP_RST_TASK_WDT:
    case ESP_RST_WDT:       return "reinício por watchdog";
    case ESP_RST_BROWNOUT:  return "quebra de tensão (brownout)";
    default:                return "motivo desconhecido";
  }
}

void iniciarLogs() {
  Wire.begin();   // SDA 21, SCL 22
  rtcOk = rtc.begin();
  if (rtcOk && !rtc.isrunning()) {
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));   // hora de compilação
  }

  sdOk = SD.begin(PINO_SD_CS);
  if (!sdOk) Serial.println("Falha ao iniciar o cartão SD");

  registarLog("INFO", "Nó iniciado");

  esp_reset_reason_t motivo = esp_reset_reason();
  char msg[80];
  snprintf(msg, sizeof(msg), "Motivo do arranque: %s", motivoReinicio(motivo));

  // Verificar se o arranque foi anormal
  bool anormal = (motivo == ESP_RST_PANIC || motivo == ESP_RST_INT_WDT ||
                motivo == ESP_RST_TASK_WDT || motivo == ESP_RST_WDT ||
                motivo == ESP_RST_BROWNOUT);

  // Registar tipo de arranque
  registarLog(anormal ? "WARNING" : "INFO", msg);
}

void acertarRelogioNTP() {
  if (!rtcOk) return;
  configTzTime("WET0WEST,M3.5.0/1,M10.5.0", "pool.ntp.org");   // hora de Portugal
  struct tm t;
  if (getLocalTime(&t, 5000)) {
    rtc.adjust(DateTime(t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
                        t.tm_hour, t.tm_min, t.tm_sec));
  }
}

void registarLog(const char* nivel, const char* texto) {
  if (!sdOk) return;

  char dataHora[24] = "--/--/---- --:--:--";
  if (rtcOk) {
    DateTime agora = rtc.now();
    snprintf(dataHora, sizeof(dataHora), "%02d/%02d/%04d %02d:%02d:%02d",
             agora.day(), agora.month(), agora.year(),
             agora.hour(), agora.minute(), agora.second());
  }

  File f = SD.open(FICHEIRO_LOGS, FILE_APPEND);
  if (!f) {
    Serial.println("Erro a abrir logs.txt");
    return;
  }
  f.printf("[%s] %s %s\n", nivel, dataHora, texto);
  f.close();
}

More projects by joao-e-rafael-ribeiro