How to use timers in code
As you may already know, hardware can send various data types to the Widgets over the Virtual Pin like this:
sensorData = analogRead(A0); // this is an example of reading sensor data
Blynk.virtualWrite(V5, sensorData);in the
void loop ()!
If you put it code into a
void loop()it will execute "gazillion" times. This will spam the Blynk.Cloud with thousands of messages from your hardware. When it happens, Blynk.Cloud will cut off the connection between your hardware and server.
Blynk Library offers a built-in Blynk.Timer feature to send data in intervals. It allows you to send data periodically with given intervals and not interfere with other Blynk library routines.
BlynkTimeris included in Blynk library by default and there is no need to install SimpleTimer separately or include
- A single
BlynkTimerobject allows to schedule up to 16 timers
- Improved compatibility with boards like
Intel Galileo, etc.
- When a timer struggles to run multiple times (due to a blocked
loop), it just skips all the missed intervals and calls your function only once. This differs from
SimpleTimer, which could call your function multiple times in this scenario.
// Declaring a global variabl for sensor data
// This function creates the timer object. It's part of Blynk library
// This function describes what will happen with each timer tick
// e.g. writing sensor value to datastream V5
//Connecting to Blynk Cloud
Blynk.begin(auth, ssid, pass);
// Setting interval to send data to Blynk Cloud to 1000ms.
// It means that data will be sent every second
// Reading sensor from hardware analog pin A0
sensorVal = analogRead(A0);
// Runs all Blynk stuff
// runs BlynkTimer