Hey,
I am trying to get my project to work with Blynk. Currently we send the temperature out to a database as you can see in the code below. But I am wondering what the best approach is to this. We want the temperature to be read every 30 seconds and sent to the database while we want the Blynk app to keep an constant update on the temperature. Currently, because of the 30 second delay the Blynk app is only online for a few seconds then goes offline. If we take the delay away it works but the database is spammed with temperature readings. Would you have any recommendations on how to achieve this?
Thanks
Details:
Board: Arduino MKR1000
Blynk App on iOS 13.3.1
#define BLYNK_PRINT SerialUSB
#include <SPI.h>
#include <WiFi101.h>
#include <BlynkSimpleWiFiShield101.h>
#include "arduino_secrets.h"
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
char server[] = "172.20.10.3";
char auth[] = "";
int status = WL_IDLE_STATUS;
IPAddress gateway;
WiFiClient client;
int tempPin = A0;
int tempValue = 0;
double temp;
int redPin= 10;
int bluePin = 11;
int greenPin = 12;
BlynkTimer timer;
void printWiFiData() {
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
Serial.println(ip);
}
void getTemp() {
tempValue = analogRead(tempPin);
temp = (double)tempValue / 1024;
temp = temp * 5;
temp = temp - 0.5;
temp = temp * 100;
temp = temp - 32;
temp = temp * 0.5556;
Serial.print("Current Temperature in oC: ");
Serial.println(temp);
if (temp > 21) {
RGB_color(255, 0, 0);
}
else if (temp <18 ) {
RGB_color(0, 0, 255);
}
else {
RGB_color(0, 255, 0);
}
}
void myTimerEvent()
{
tempValue = analogRead(A0);
Blynk.virtualWrite(V6, tempValue);
}
void dbSend() {
if (client.connect(server, 8888)) {
Serial.println("Connected to database\n");
Serial.print("Sent data to database\n");
client.print("GET /database.php?temperature=");
client.print(temp);
client.print(" ");
client.print("HTTP/1.1");
client.println();
client.println("Host: 172.20.10.3");
client.println("Connection: close");
client.println();
} else {
Serial.println("Connection Failed");
}
}
void RGB_color(int redLedValue, int greenLedValue, int blueLedValue)
{
analogWrite(redPin, redLedValue);
analogWrite(greenPin, greenLedValue);
analogWrite(bluePin, blueLedValue);
}
void setup() {
Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
timer.setInterval(1000L, myTimerEvent);
while (!Serial) {
}
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true);
}
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
delay(10000);
}
Serial.print("You're connected to the network\n");
printWiFiData();
}
void loop() {
getTemp();
Blynk.run();
timer.run();
dbSend();
}