#include <Wire.h>
#include <WiFi.h>
#include "ThingSpeak.h"
#define SECRET_SSID "Wokwi-GUEST"
#define SECRET_PASS ""
#define SECRET_CH_ID 2575218
#define SECRET_WRITE_APIKEY "T99J3OQA3A62CPGV"
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
int keyIndex = 0;
WiFiClient client;
unsigned long myChannelNumber = SECRET_CH_ID;
const char *myWriteAPIKey = SECRET_WRITE_APIKEY;
int pinTEMP = 32;
float temp = 0.00;
const float BETA = 3950; // Variável do coeficiente BETA do termistor
#define interruptPin 5
uint16_t pulse;
uint16_t count;
float frequency;
void setup() {
pinMode(pinTEMP, INPUT);
analogReadResolution(10); // Define o tamanho (em bits) dos valores lido em 10 bits (valores de 0 a 1023)
Serial.begin(9600);
while (!Serial) {
;
}
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(SECRET_SSID);
while (WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, pass);
Serial.print(".");
delay(5000);
}
Serial.println("\nConnected to WiFi");
}
float pinval = analogRead(pinTEMP);
float temp = 1 / (log(1 / (1023. / pinval - 1)) / BETA + 1.0 / 298.15) - 273.15;
Frequency();
Serial.println("Temperature reading: " + String(temp));
ThingSpeak.setField(1, temp);
ThingSpeak.setField(2, frequency);
int x = ThingSpeak.writeField(myChannelNumber, 1, temp, myWriteAPIKey);
if (x == 200) {
Serial.println("Channel update successful");
} else {
Serial.print("Problem updating channel. HTTP error code: ");
Serial.println(x);
if (x == -101) {
Serial.println("WiFi network disconnected. Attempting to reconnect...");
} else if (x == -301) {
Serial.println("Unable to connect to ThingSpeak server.");
} else if (x == -303) {
Serial.println("Timeout while waiting for ThingSpeak server response.");
} else {
Serial.println("Unknown error.");
}
}
delay(1000); // Delay for 10 seconds before next iteration
}
void Frequency() {
static unsigned long startTime;
if (millis() - startTime < 1000 ) return; // 1000 milliseconds Interval
startTime = millis();
cli();
count = pulse;
pulse = 0;
frequency = count / 2.0f;
PlotInfo();
}
void PlotInfo() {
Serial.print("Freq.:= " + String(frequency, 2) + " Hz");
}