text:
Integrating an analog signal using Arduino Due
I have an 2 analog signal, and I want to calculate the difference between 2 signals (A0 and A1), then integrate an analog, but it doesn't work (I just started studying Arduino).
Please could you show me how to deal with this problem?
Thanks a lot
float analogInPin = A0;
float analogInPin1 = A1;
float analogOutPin = DAC1;
float FeqIn, FeqIn1, FeqIn2, FeqIn3, FeqOut, w, Triarea, Recarea, area, n, y, t;

void setup() {
  Serial.begin(9600); // use the serial port
}

void loop() {
  FeqIn1 = analogRead(analogInPin);
  FeqIn2 = analogRead(analogInPin1);
  FeqIn3 = FeqIn1 - FeqIn2
  // integration
  area(1) = 0;
  y(1) = 0;
  for (n = 1; n = t; t++) {
    Triarea(n+1) = (0.5*t(2))*(FeqIn3(n+1) - FeqIn3(n));
    Recarea(n+1) = t(2)*(FeqIn3(n));
    area(n+1) = (Triarea(n+1) + Recarea(n+1)) + area(n);
  }
}

The error message is:
Arduino: 1.6.5 (Windows 8.1), Board: "Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

_02.ino:3: error: 'DAC1' was not declared in this scope
_02.ino.ino: In function 'void loop()':
_02.ino:20: error: expected ';' before 'area'
_02.ino:21: error: 'y' cannot be used as a function
_02.ino:24: error: 'Triarea' cannot be used as a function
_02.ino:24: error: 't' cannot be used as a function
_02.ino:24: error: 'FeqIn3' cannot be used as a function
_02.ino:24: error: 'FeqIn3' cannot be used as a function
_02.ino:25: error: 'Recarea' cannot be used as a function
_02.ino:25: error: 't' cannot be used as a function
_02.ino:25: error: 'FeqIn3' cannot be used as a function
_02.ino:26: error: 'area' cannot be used as a function
_02.ino:26: error: 'Triarea' cannot be used as a function
_02.ino:26: error: 'Recarea' cannot be used as a function
_02.ino:26: error: 'area' cannot be used as a function
'DAC1' was not declared in this scope

Please copy and paste your actual code into your question (edit the question to do this) - not a screen shot of it. Then we are in a position to test it ourselves, or to amend it and post the amended code.

You tagged this question with arduino-uno and arduino-due. Which one is it? They are not the same thing.

Now please post the error messages which I can just see a tiny bit of in the screen shot. area(1) = 0; - what is that supposed to be doing?

I think your main problem here is a fundamental lack of understanding about C++.  There's numerous basic errors in your code.  Let's take a look at them:
FeqIn3 = FeqIn1 - FeqIn2

All C++ statements must be terminated by a ; otherwise it doesn't know where one statement finishes and the next one begins.
area(1) = 0;
(and many others)

You have declared a bunch of float variables in the global scope.  You are then trying to use those float variables as functions, and on top of that you are then trying to assign a value to the return value of that function.  That makes absolutely no logical sense whatsoever.
I think you meant to be using arrays of float values.  Arrays are denoted by [ and ] not ( and ).  Further, they have to be defined as arrays, including the size of the array, not a single value.  Also in C++ arrays are zero based (i.e., they start at index 0 not index 1).
For example, area could be defined as:
float area[1024]; // 1024 floating point values in an array
// ...
area[0] = 0;

Next:
Recarea(n+1) = t(2)*(FeqIn3(n));

I don't even know what to make of this bit...  If I assume you should replace (...) with [...] for indices to arrays, it still makes no sense.  You're calculating a single value (FreqIn3 = FreqIn1 - FreqIn2) then using that as an array (FreqIn3[n]) which makes absolutely no sense to me at all.  Then you're using another value t which you are incrementing (incorrectly, more on that later), which again you are then trying to use as an array (t[2]).  Which is it - arrays or single values? And how do you increment an entire array?
Now the incrementing:
for (n = 1; n = t; t++)

n starts at the value 1.  While n is assigned the value t, increment t.  Now, does that sound logical?  And what is t? when that loop starts?  It has no defined value, so it could be anything at all.  And when does the loop end?  Well, since you're using float values for your counters (which is idiotic at best) you won't ever get any integer wraparound, so t will never equal 0 and consequently the result of assigning t to n will never be 0, so the loop will never end.
I think you need to go back to absolute basics and learn a bit more about syntax of C++, arrays, functions, loops, etc, before embarking on something complex like signal integration.

As previous answers have pointed out, your understanding of C syntax has shortcomings, and you should study C further.  Besides those syntax issues, you may need to revise some of your concepts of how to program.
Firstly, the references you looked at regarding integration may have shown forms like Tₓ₊₁ = (δ/2)·(Vₓ₊₁ – Vₓ) for “triangle area” and Rₓ₊₁ = δ·Vₓ for “rectangle area” [where I've written δ in place of your t(2)].  In spite of the use of subscripts in these formulas, the array concepts mentioned in other answers are not relevant here.  Instead of saving voltage data in arrays, just save and work with two voltage values:  the current differential voltage reading and the previous differential voltage reading.  Letting Vᵣ and Vₓ stand for previous and new voltage differences, use Vᵣ where Vₓ is called for, and Vₓ where Vₓ₊₁ is called for.  At the end of each step, set Vᵣ = Vₓ.
Secondly, making separate computations of “triangle area” and “rectangle area” is verbose, unnecessary, and less accurate than a properly combined computation.  Note that Tₓ₊₁ + Rₓ₊₁, as used in computing areaₓ₊₁, is equal to  (δ/2)·(Vₓ₊₁ – Vₓ) + δ·Vₓ = (δ/2)·Vₓ₊₁ – (δ/2)·Vₓ + δ·Vₓ = (δ/2)·Vₓ₊₁ + (δ/2)·Vₓ = δ·(Vₓ₊₁ + Vₓ)/2.  Thus, instead of those three lines of code using two temporary variables and lots of indices, use code like the following for the integral:
area += deltaT*(Volt_r + Volt_s)/2;
Volt_r = Volt_s;

(In the above, Volt_s corresponds to your FeqIn3 value.)
Thirdly, your attempted for loop needs to be replaced by an actual for loop; and in addition, deltaT, a time-step delta, needs to be computed.  (Your t(2) needs to represent a change in time, not an absolute time, to represent the time-width of the rectangle and triangle you are adding to the total.)  To get a deltaT, read millis() after the analogRead lines.  For example, you could say:
Volt_s = analogRead(analogInPin) - analogRead(analogInPin1);
t_s = millis();
deltaT = t_s - t_r;
area += deltaT*(Volt_r + Volt_s)/2;
t_r = t_s;
Volt_r = Volt_s;

Fourthly, using two analogReads to get a differential voltage has two problems:  first, any common-mode voltage wastes bits of ADC resolution, so contributes to error; second, the two reads occur at different times so their voltages are not comparable.  Instead, you could use an external op-amp to subtract voltages, or could use the Due's differential-front-end ADC mode, per Section 43.6.8, Differential Inputs, on page 1326 in the ARM Cortex M3 Processor manual, plus possibly a gain of 1, 2, or 4 (per Section 43.6.9).  Also see: Analog performance ... of Due's 12 bit ADC (including how to speed up analogReads on the Cortex), Differential Sensing with Arduino, Setting ADC compare mode in a differential input, and Due pinout diagram.

float FeqIn, FeqIn1, FeqIn2, FeqIn3, FeqOut, w, Triarea, Recarea, area, n, y, t;

...

      Triarea(n+1) = (0.5*t(2))*(FeqIn3(n+1) - FeqIn3(n));

I honestly don't know what you are doing here.
Triarea is a float, right? A single variable of type float.
What is this?
      Triarea(n+1) = (0.5*t(2))*(FeqIn3(n+1) - FeqIn3(n));

Triarea(n+1) looks like you are calling a function called Triarea with the argument n+1.
That doesn't make any sense because it isn't a function.

Maybe you mean to treat it as an array?
  Triarea[n+1] = (0.5*t[2])*(FeqIn3[n+1] - FeqIn3[n]);

But you have not declared those variables as arrays.
It is pure guesswork what is going on in your mind.
However your syntax certainly explains the error messages, for example:
_02.ino:24: error: 'Triarea' cannot be used as a function

If I may suggest, read a tutorial on basic C++ programming.


text:
Read sensor and convert reading to const char*
I'm working on a home automation project using Arduino and MQTT.
I've found a problem and my limited programming knowledge find a way to solve it.
I can send text trough MQTT normally, using
client.Publish("some/topic","Some text here");

But when I try to send a variable (int, char, etc), the compiler says "invalid conversion from 'char' to 'const char*' [-fpermissive]"
How can I store DHT11 sensor reading in const char* to send it?
BTW, I've found this code where
char *tempC;
tempC = dtostrf(((((analogRead(tempPinIn) * 5.0) / 1024) - 0.5) * 100), 5, 2, message_buffer);
client.publish("arduino/temperature",tempC);

is used. But the extra sensor calibration makes it even harder for me to understand whats going on.

The function dtostrf() is prototyped as:
char *dtostrf (double          val,
               signed char     width,
               unsigned char   prec,
               char           *sout);

Where:
   val      Your float variable;
   width    Length of the string that will be created INCLUDING decimal point;
   prec     Number of digits after the deimal point to print;
   sout     Destination of output buffer;

An example of usage is as follows:
/* OPTION ONE */

    char msgBuffer[20];           // make sure this is big enough to hold your string
    char *pointer_to_created_string;

    float testFloat = 123.45;

    pointer_to_created_string = dtostrf(testFloat, 6, 2, msgBuffer);
    client.Publish("...topic...", pointer_to_created_string);

/* OPTION TWO */

    char msgBuffer[20];           // make sure this is big enough to hold your string

    float testFloat = 123.45;

    client.Publish("...topic...", dtostrf(testFloat, 6, 2, msgBuffer));

Don't be put off by the code in the link you included in your question. The first argument sent to dtostrf (everything before the first comma) is nothing more than a some calculations bundled into one single line.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
iBus transmission and read it in Arduino
I am using an Arduino Uno and I want to transmit data from FSi6 to FS-iA6B and read received data in an Arduino. After searching, I found the below link which is iBUStelemetry.
iBustelemetry
I am not able to make out how to get the data from this library and print it on the serial monitor.
I have hooked up receiver ground and power pins to ground and power pins of Arduino. Signal from the receiver is connected to D2.
The author has included an example, but I am not much clear how data is read and printed on the serial monitor.
Can someone please help by telling how do I read data from receiver using this library?

If I understand correctly, the code should look like this.
#include <iBUStelemetry.h>
iBUStelemetry telemetry(4);
byte i;

void setup(){
 Serial.begin(115200);
 telemetry.begin(115200);
 telemetry.addSensor(2);
}

void loop(){
 telemetry.setSensorMeasurement(1, i++);
 delay(1000);
 Serial.println(telemetry);
 //or
 Serial.println(telemetry.setSensorMeasurement(1, i++));
}

https://www.arduino.cc/reference/en/language/functions/communication/serial/print/

Thanks for your reply. The output should be value of each individual channels from the RC remote. This does not give any active results. Expected code should be something like:
for (i = 0; i < noOfCh; i++){  chvals[i] = IBus.readChannel(i); }
Can you kindly check and revert?

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to pad an ascii number with leading zeros?
I need to include a 3 digit ascii representation of message length number in the message header, but I am having difficulty trying to pad the number with leading '0' zeros in order to keep the number of 'length' digits needing to be appended always 3 even when the message length is only one or two digits long.
Addendum:
The problem, more specifically, is how to left-pad a char array containing the number representation.
I got as far as defining what and where, but I couldn't figure out how to shift the char[] contents right in order to insert the "0" at msglength[0].  (I tried using strcat, but that didn't work).
char msglength[4]          //(3 digits + nul)
for (int pad=1; pad<=3-strlen(msglength); pad++)
{
    // add a leading zero char to msglength, but that involves
    // somehow shifting all its contents to the right
}

if( value<10 ) Serial.print("0"); else if ( value<100 ) Serial.print("00"); Serial.print(value);

You have to move the bytes starting from the last one: for (int i = strlen(msg); i >= 0; i--) msg[i+3] = msg[i];. Make sure your char array is big enough, at least strlen(msg) + 3 (padding) + 1 (null terminator).

Yes, I understand I must move the existing array char digits plus null terminator to the right (top) of the msglength[4] array, but somehow I must also insert a '0' char into each vacated position. But my lack of programming knowledge can only come up with a solution which requires 2 for( loop passes, with a temporay value to hold the amount of steps used in the first 'right-shift' pass, in order to fill with the appropriate number of '0's from the left in a second pass.
Is there a more elegent solution other than using 2 for( loops and a temp variable?

Two loops is perfectly fine here. I do not think you can make it an better.

This is the kind of situation where printf() comes handy:
printf("%03d", number);

prints the number in the format you described. Alas, printf() is not
part of the standard Arduino API. But you can have it, nonetheless, at
least on AVR-based Arduinos, as it is provided by the avr-libc, which is
always linked with all Arduino programs. Some setup is needed to tell
avr-libc about where is its “standard output”. We can use the macro
fdev_setup_stream() to tell it to just push the bytes through
Serial.write():
static int Serial_write(char c, FILE *) {
    if (c == '\n') Serial.write('\r');  // convert LF -> CRLF
    return Serial.write(c);
}

static FILE mystdout;

void setup() {
    Serial.begin(9600);
    stdout = &mystdout;
    fdev_setup_stream(stdout, Serial_write, NULL, _FDEV_SETUP_WRITE);
}

void loop() {
    static int count;
    printf("%03d and counting...\n", count++);
    delay(500);
}

C.f. the manual of avr-libc's
stdio.h
for details.
Pros of this method:

printf() has plenty of options to control the formatting of your
messages.
It's very standard C, understood by anyone having programmed in that
language.

Cons:

This can make your compiled program bigger than it would be if
sticking with the Arduino API.
It's not the “Arduino way”.

I think you mean to use sprintf. printf tries to go to an output stream automagically, sprintf uses a destination buffer, which could then be sent via Serial.write().

@bss36504: I mean printf(). Read my answer.

sprintf is also a solution, especially since OP did't ask to print the data on the serial port.

One straightforward way to do this is to extract digits separately (using integer division and mod).  For example, the hundreds digit of a positive or unsigned int x is (x/100)%10.
A sketch shown below uses the statement
  Serial << ' ' << b/100 << (b/10)%10 << b%10;

to print a space and three digits of a positive number, with leading zeroes.  Here are the first 18 lines of output from the sketch:
 000 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015
 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031
 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047
 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063
 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079
 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095
 096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111
 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
 000 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015
 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031

Here is the sketch:
#include <Streaming.h>

//char b=0;    // char is signed; messy when hi bit is on
byte b=0;    // byte is unsigned, all ok
void setup() {
  Serial.begin(115200);
}

void loop() {
  // To emulate
  //    Serial << ' ' << setw(3) << setfill('0') << b;
  // or
  //    Serial << ' ' << b<100? '0': '' << b<10? '0': '' << b;
  // write (eg)
  Serial << ' ' << b/100 << (b/10)%10 << b%10;
  // or if b is an int instead of a byte, write
  //    Serial << ' ' << (b/100)%10 << (b/10)%10 << b%10;

  ++b;
  if (b%16 == 0) Serial.println();
  delay(17);
}

The code shown above uses Streaming.h, a contributed library that adds some “syntactic sugar” to Arduino C.  That is, at compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  If you don't have Streaming.h installed, either install it via Streaming5.zip from arduiniana.org or manually translate the Serial << ... statement to Serial.print statements.
Note, if the Streaming.h library supported setw() and setfill(), they could be used to set field width and fill character.  (See comments in sketch.)  However, the current implementation merely translates the stream insertion operator << form into print() form.  It supports four base-conversion specifiers, _HEX, _DEC, _OCT, and _BIN; a _FLOAT function with number of decimal places specified; and endl.  Some _FILL functions are suggested at the Arduiniana.org link.

There is always brute force.
char* itob(int val, char* buf, size_t n)
{
  char* bp = buf + n;
  do {
    *--bp = (val % 10) + '0';
    val = val / 10;
  } while (bp != buf);
  return (buf);
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);

  const int BUF_MAX = 3;
  char buf[BUF_MAX];

  Serial.write(itob(42, buf, BUF_MAX));
  Serial.println();
}

void loop()
{
}

Please observe that the buffer is not null-terminated, therefore the Serial.write().
Several possible optimizations from the simple solution such as detect when the value is zero and short-cut.
Cheers!

Thank you all for your suggestions.
This is what I came up with, which seems to work ok.
char lengthstr[4]="7";
Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'");
int maxsize=sizeof(lengthstr);  // size of lengthstr array
int steps=strlen(lengthstr)+1;  // number of chars to be moved
int hop=maxsize-steps;          // number of steps to be jumped over each move
if((steps>1)&&(maxsize>steps)) {
   for (int pos=steps; pos >= 0; pos--) {
      lengthstr[pos+hop] = lengthstr[pos];
      lengthstr[pos]='0';
   }
}
Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'");

Two problems here: 1) On the first iteration of the for() loop, you are writing beyond the end of the lengthstr array. This is called memory corruption and can be a very nasty bug. The loop should start at pos=steps-1. 2) Assuming you fix that previous bug, the code will work if lengthstr is of size 4, but not if it's any bigger. Your initial two-loop idea was cleaner and would work at any size.

Thanks Edgar, I very much appreciate your help and advice, so I will redo using 2 loops, which is easier to get my head around anyway.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Particle-like wifi configuration
Can anybody tell me how the Particle (Photon/Core) WiFi setup works?
I am looking to mimic this WiFi configuration format for my own device.
The basic steps are as follows:

Power device on; put in "listening mode" if not already active;
Connect smartphone to the wireless network that you want to connect your device to;
Open the Tinker/Spark/whatever-it's-called App on your smartphone; choose "Add New Device";
Enter wireless password;
Wait for device to be discovered by the App; device is now connected to WiFi.

How is the information (SSID, password) transferred from the smartphone to the device?
Thanks in advance.

Are you on about WPS?

What does this have to do with Arduinos?

@NickGammon It has as much to do with Arduinos as the Intel Edison, Galileo and the Teensy range. Those are welcome here, should the Particle/Spark system not be too?

Oh well, what is the question here? Any idea how does particle (photon/core) wifi works - that's too broad then.

I've edited the question so that it asks about the wireless setup, which I think is a valid and non-broad question. I'd also like to know the answer!

The Particle Photon is a replacement for the Spark Core module. This module was exploiting the Texas Instrument CC3000 chip. It was this chip that handle the very simple and convenient Wi-Fi configuration of the Spark Core. Texas Instrument named this method : SimpleLink.
The Particle Photon is now using a different module than the Core : a Broadcom BCM43362 instead of the CC3000. It's seems to work in a similar manner even if I was not able to find any information on it.
I've found on the George Howkins Depletion Region blog  multiple articles that explain how the CC3000 SimpleLink works.

CC3000 Smart Config - transmitting SSID and keyphrase
CC3000 advertises presence on network via DNS-SD

All the posts : http://depletionregion.blogspot.fr/search?q=smart+config


text:
Improvised Keyboard?
I want to make a keyboard type panel, which will only have 7 buttons and two knobs, and connect it arduino to program it with functions, he heard that he needed the Keyboard library. but it is not available with arduino uno, which is what I work with, he heard about what I should do a keyboard mapping, it would help me explain to lay a foundation and carry out the project that I want "please do not leave me with the doubt". first of all, Thanks.

it is unclear what is your question

The Uno can't (easily) do keyboard functionality. Get a Leonardo or Micro instead.

If you plan to trigger function on a PC by keystroke and want to simulate a PC keyboard on the PC with your computer than I recommend to use the keyboard lib which is able to map your button to key codes and send them to a PC over USB. But the communication over USB and the simulation of a HID (Human Interface Device) connection is (as far as I know) not possible with an Arduino. (You need a 32u4 or SAMD micro based board) like the leonardo.
But if you just plan to trigger functions, that run on the Arduino, the kb lib is not necessary. That a standard job for the Arduino and can be done with 7 input pins and 2 analog pins.

It is actually a game of reactions, the game appears on the computer and the subject reacts from the panel, if possible? I don't know how to do it, they tell me, that I should do a keyboard mapping that I want to implement, but I don't have a micro or leonardo, what can I do?

is that it is my project to pass intern of my studies

I'm very busy this morning, but this evening I try to find a solution. In the meanwhile, there is a software called processing ( https://processing.org/ ), that can interact with arduinos of all kind. It something like the Arduino IDE and must also be programmed in a C/C++ dialect. Perhaps you find some ideas, if you look at the example projects. Can you control the game with serial input, I mean, have you access to the games code, and can write your own controlling interface? If not, you have to simulate keyboard events.

the game is made in java,
I will add the hardware part
and good
If you have any ideas, I would appreciate it !!
and thanks I will look at the page you recommended.
thanks for answering i'm stressed

If I understand you right, you build the hardware (the control panel) and some others write the game in Java. If they are nice guys, you and your colleagues  could create a text based control protocol and you use this protocol to send control statements to the game over the serial interface. That's easy for you and the game writers too. And it is the only easy way a UNO can communicate with a PC. In the arduino you only need Serial.print("control statement")` commands;  An in Java thei can use a serial communication lib like https://fazecast.github.io/jSerialComm/

Keep the protocol short and easy. e.g. assign a letter to a key. key1='A', key2='B', ... key7='G'. So if for instance key2 is pressed you send a Serial.print("pB") and if the key is released you send a Serial.print("rB"). In the game they use the first letter in the recieved string to indicat if the button is pressed or relased and the second letter to indentify the key.  The same is for the analog values of the knob use e.g. a "aA123" to indicate an analog value of 123 for knob A and "aB1023" to indicate an analog value of 1023 for knob B.

If you connect the arduino to a windows computer it should automatically create a COMxx port that can be used by the Java programm (the game).

Hope this helps you a little bit. And good luck with your project.

Thank you so much for everything

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Function pointer call results in InstrFetchProhibited (ESP32)
I have the following issue which I'm unable to resolve by myself. Perhaps one of you could point me to issues in my code which I don't see.
There is a class called communicator which handles an MQTT connection. I use PubSubClient as a MQTT client. The constructor of communicator looks like the following. Besides connection arguments, it also receives an array of structs SubscriptionHandler. These structs define which topics should be subscribed to and also point to a callback method. When a communicator receives a MQTT message, it compares the topic to the known ones and calls the appropriate callback.
Communicator(char * mqttBrokerIP, uint16_t mqttBrokerPort, char *mqttUsername, char * mqttPassword, char * mqttClientHostname, SubscriptionHandler subscriptionHandlers[], int lenHandlers);

SubscriptionHandler. is defined like this:
typedef void (*callback)();

struct SubscriptionHandler
{
    char *Topic;
    callback Callback;
};

I tried the following: In the main file, I defined two methods for demonstration purposes:
void enableHandler()
{
  Serial.println("enable handler");
}

void disableHandler()
{
  Serial.println("disable handler");
}

The communicator is created in the setup()-Method:
SubscriptionHandler handlers[] = {{&strEnable, enableHandler},
                                    {&strDisable, disableHandler}};

callback (in communicator.h) typedef void (callback)();
strings : String strEnable = ("test/" + hostname + "/command/enable"); and the same for disable. Those are also defined in main.cpp –
As soon as the communicator receives a MQTT message, the ESP32 crashes with the following message:
Guru Meditation Error: Core  1 panic'ed (InstrFetchProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x3ffc9306  PS      : 0x00060c30  A0      : 0x8017e97c  A1      : 0x3ffb1ed0
A2      : 0x3ffc9306  A3      : 0x3ffc9306  A4      : 0x3ffc9306  A5      : 0x3ffc1318
A6      : 0x3ffb1f44  A7      : 0x00000000  A8      : 0x800d4df0  A9      : 0x3ffb1eb0
A10     : 0x0000000d  A11     : 0x0000000b  A12     : 0x3ffc24a4  A13     : 0xa98b32f8
A14     : 0x3ffc1318  A15     : 0xff000000  SAR     : 0x00000004  EXCCAUSE: 0x00000014
EXCVADDR: 0x3ffc9304  LBEG    : 0x400014fd  LEND    : 0x4000150d  LCOUNT  : 0xffffffff

Backtrace: 0x3ffc9306:0x3ffb1ed0 0x4017e979:0x3ffb1f00 0x400e280e:0x3ffb1f20 0x400d4f3e:0x3ffb1f70 0x400d5cff:0x3ffb1f90 0x400e4c45:0x3ffb1fb0 0x400889dd:0x3ffb1fd0

Therefore, something is wrong with how I use the function pointer (or somewhere which I don't even think about). Could anyone give me a hint where I could start?

What is callback defined as? And the str... variables - what are they?

callback  typedef void (*callback)();
strings** : String strEnable = ("test/" + hostname + "/command/enable"); and the same for disable.
Those are also defined in main.cpp

And those strEnable a strDisable strings? If it's char array, you shouldn't have & here and for better readability it should be before function names.

You're passing the address of a String object to a char * pointer. That's very bad.

have you seen this? https://randomnerdtutorials.com/esp32-mqtt-publish-subscribe-arduino-ide/

@Majenko, I was indeed unsure about this. But this mqtt lib uses this data type, therefore I thought about using it too. Is there a better way?

@jsotola, the thing is I'm subscribing to multiple topics and I want to call method x of class y when i receive something on topic z. Publishing&Subscribing works on the examples I tried before. But calling the function after receiving a message and determine which function to call crashes.

I found the issue. After moving SubscriptionHandler handlers[] = ... out of the setup()-method, the function calls work. Perhaps handlers gets overwritten after leaving the setupfunction scope. Could anyone validate my suspected reason?

Anything in local scope (defined in a function) is gone after the function ends. Even if you store a pointer to it somewhere. It's gone.


text:
Receive whole string in serial sending data?
I connect my NodeMCU to Arduino Uno. The goal is to receive the whole string for example "12", every 1 sec.
This is my code on Arduino Uno side ( the sender)
int mock = 0;

void setup() {
  Serial.begin(115200);
  s.begin(115200);
}

void loop() {
    //Write mock to NodeMCU
    s.print((int)mock,DEC);
    s.println();

    mock++;
    delay(1000);
}

On NodeMCU side ( the receiver)
 char data; //Initialized variable to store recieved data
 String line;
 void setup() {
   Serial.begin(115200);
   s.begin(115200);
   while (!Serial) {
    ;
  }
}

void loop() {

    if( s.available() >= 2) {
        for (int i = 0; i< 2; i++ ) {
            data = s.read();
            line += data;
        }
        delay(1000);
    }

    Serial.print(line);

}

But the result on the serial panel is not what I expected

How can I make it so that I can receive something like
12
(wait one sec)
13
(wait one sec)
....

Node MCU just prints the whole thing, I can't delay it.

I don't see you printing what you have read. Also line is not defined in your code. Please provide a full minimal example

@chrisl Sorry i forgot to include the variable's declaration. I plan to use "line" to store all data that received and then print it to the console.

in your nodemcu use
void loop() {
    if(s.readBytesUntil('\n',data ,2)>0)
      Serial.println(data);
    delay(1000);
}

Serial.readBytesUntil(character, buffer, length)

Serial.readBytesUntil() reads characters from the serial buffer into an array. The function terminates (checks being done in this order) if the determined length has been read, if it times out , or if the terminator character is detected (in which case the function returns the characters up to the last character before the supplied terminator). The terminator itself is not returned in the buffer.
Serial.readBytesUntil() returns the number of characters read into the buffer. 0 means that the length parameter <= 0, a time out occurred before any other input, or a termination character was found before any other input.

readBytesUntil waits a second for the data. it is better to wait for the first character with Serial.available(). and you don't handle \r

yeah he is going to print it in console \r\r means twice return to beginning of line no diffrence in result
if he wants a better approach he needs to define two bytes or more  header and a checksum then define a constant size packet so he can reach a better solution with even faster speed beside I would change sender s.print((int)mock,DEC);
s.println(); to s.print((int)mock,DEC);
s.print('\n')

If you send "12" you send 4 characters/bytes: '1', '2' and a new line which is two characters:  ('\r', '\n').
On the receiver side you check for two characters (not the new line), so you should take it into account.
Actually, since you will eventually reach "100" you will receive 5 characters ('1', '0', '0', '\r', \'n').
So it is better to change the receiver side to store the bytes in line UNTIL a new line is received (than you can support values of any length).
Also remove the delay on the receiver side, or at least decrease it a lot, because it doesn't matter to check (too) often. if there is no byte available, it will check again. Now it can happen at time 1001 ms a byte would be received, but at time 1000 ms it is checked and it will not be checked again until time 2000 ms.

println() is \r\n

@Juraj Thanks (I should have known).


text:
Infinite loop if Serial.println() is not used
I'm trying to reset my program from software using the third method described here: Reset an Arduino Uno in code
The function is basically showing some data on an OLED display and afterwards should reset the processor
void setup() {
  MCUSR = 0;
}

void showCharacter(int char_number) {

  // [...]

  display.println(character_buffer);
  display.display();

  for (int j = 0; j < 3; j++) {
    enableLED(x, y);
    publishLEDs();
    delay(500);
    clearLEDs();
    publishLEDs();
    delay(500);
    Serial.println(j);
  }

  keyscan.sleep();

  // Reset system
  wdt_enable(WDTO_15MS); // turn on the WatchDog and don't stroke it.
  for (;;) {}
}

For whatever reason it makes a difference if the Serial.println() line is there. If the line is there, the code behaves as expected. The LED blinks three times, afterwards the Arduino is reset.
If I remove that line however, the LED continues to blink infinitely and the code does not reset. I really have no idea why that line has such a big difference, I wouldn't expect any difference to be honest. Anybody has an idea what's going on?
Edit:
I got a hint from a friend of mine that using the volatile keyword in the for loop could fix the problem. He vaguely remembered having a similar problem somehow related to compiler optimisation. And indeed, the following code works as expected:
for (volatile int j = 0; j < 3; j++) {
  enableLED(x, y);
  publishLEDs();
  delay(500);
  clearLEDs();
  publishLEDs();
  delay(500);
}

So let me rephrase my question a little bit - what is happening here, why is the volatile keyword needed?

Is that Serial initialized? I'm not sure we can answer this question, as there are no details about it. Why do you even need the restart?

replace the Serial.println()  with an equivalent delay

How do you know, that the code does not reset? A continuos blink is not possible with this for loop. When we have a question like "it works with serial print, but not without", it is often just, that it could not be seen, if it works, since there is no serial print. Please show us a complete minimal example, that shows your problem. The code above is not complete.

@KIIV, yes it is initialised and works.
jsotola, there is a 500ms delay just before the Serial.println(), why should that make a difference?
chrisi: after reset and init, the LED does not blink and also the OLED is reset. If the serial command is there, the devices resets, LED stops blinking and OLED shows correct content. If the command is not there, nothing of that happens and the LED keeps blinking (OLED content remains). I'll try to post more code tomorrow, but its somehow complex

I like the resetFunc style better.  Looping and waiting for watchdog just seems clunky to me.

a Serial.println() command takes a certain amount of time to execute


text:
How to Measure many voltages (Uno) - Analog extenders a good option?
I am trying to make a battery capacity tester (3.7v li-ion 18650 battery) using arduino uno. If possible i'd like to test 20 or more batteries at the same time. I need to measure the voltage of each battery every 1 second.
The uno has 6 anolog inputs iirc so too little for this application.
I think using analog multiple extenders (connected using I2C) chained together to create enough analog inputs.
For example this one: https://nl.aliexpress.com/item/32858973834.html?spm=a2g0o.productlist.0.0.57206143DNgWKp&algo_pvid=526d42f2-f7ee-4781-932b-947744ac631e&algo_expid=526d42f2-f7ee-4781-932b-947744ac631e-0&btsid=89c452fa-1d7c-4ae9-9dd5-ed8fc9bff128&ws_ab_test=searchweb0_0,searchweb201602_8,searchweb201603_52
Do you think I'll be able to get relatively accurate voltage measurements using this approach?
The purpose of the circuit is to measure the amount of mah (battery capacity) of the 18650 battery which is being discharged via the 10Ohm resistor. The battery will be discharged from 4.2volt (fully charged) to approx 2.5V using the 10ohm resistor, each second the voltage drop over the resistor will be measured and using it and the time passed the integral of time*current will be calculated to determine the capacity.
This is the basic circuit used to connect each 18650 battery, the ANALOG1 pin will be connected to the input of the analog extenders:

(I based it off of the circuit from this video: https://www.youtube.com/watch?v=WScPyfQz_f8)
The idea is to measure the voltage drop over the 10Ohm10W power resistor and calculate the current using the known resistance value, calculate the integral of current*time to get a capacity value for the battery.
Is this a good approach? Would you recommend using analog extenders for this? If not what would be a better solution? Thank you very much!

@jsotola My mistake I don't indeed, only need 1, will edit post

I'd go for a set of 8-input ADCs, such as https://www.digikey.com/product-detail/en/microchip-technology/MCP3208-BI-P/MCP3208-BI-P-ND/319443  8 channels, 12-bit resolution, fast SPI access.  That 10 ohm resistor may get pretty warm. How will you disconnect the battery when it gets low on charge so that it doesn't become damaged from over-discharge?

Your circuit will draw about 360 mA from each battery through your 10 Ω resistor. Do you have a way to disconnect the batteries when they are not being tested?

@Duncan C For disconnecting the battery i will use a mosfet which i will turn off using arduino when battery voltage gets too low. I forgot to draw it in the circuit

@Crossroads thank you for the suggestion i will look inyo using that approach. The battery will be disconnected using a mosfet which is controlled by arduino which turns off the mosfet when the battery voltage gets too low

I personally made good experience with using analog multiplexers (that's the same thing that the arduino does to provide 8 analog inputs while only having 1 ADC, but of course CrossRoad's approach is fine, too. The circuit you provided doesn't work, you measure the battery's voltage directly which potentially can destroy the arduino. Take a look at the circuit shown in the video again. you need 2 analog inputs to measure the voltage drop over the shunt (current) and at least a voltage divider to measure the voltage

So you're going to have a 10 Ω power resistor wired into your circuit at all times? That means you'll be draining almost .4 A of current from your battery at all times. If it's a 4 Ah battery, your measurement resistor will drain your battery in 10 hours, with no actual load. Seems to me that you should have the MOSFET off by default, turn it on for an instant, measure the input into your analog pin, then turn the MOSFET back off.

@ Duncan C Thank you for your concern. I have not explained the purpose of the circuit properly, sorry. The purpose of the circuit is to measure the amount of mah (battery capacity) of the 18650 battery which is being discharged via the 10Ohm resistor. The battery will be discharged from 4.2volt (fully charged) to approx 2.5V using the 10ohm resistor, each second the voltage drop over the resistor will be measured and using it and the time passed the integral of time*current will be calculated to determine the capacity.

Actually it is two separate questions and I answer your first question of reading multiple analog values using one ADC and the answer is Yes you can use this approach but  you should give enough time for each channel to charge internal ADC capacitor when you change channel .so if you use more independent ADC you get more time for each channel and result is better


text:
How to add colour change to the strobe coding?
I have this strobe effect working. However, I would like to change the colour of the LEDs after each 'strobe sequence'. How can it be achieved?
The code I am using is this one:
    // Basic code NeoPixel
    // wwww.arduinoplatform.com

    #include <Adafruit_NeoPixel.h>
    #ifdef __AVR__
     #include <avr/power.h> // Required for 16 MHz Adafruit Trinket
    #endif

    // Which pin on the Arduino is connected to the NeoPixels?
    // On a Trinket or Gemma we suggest changing this to 1:
    #define LED_PIN    6

    // How many NeoPixels ar
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, 6, NEO_GRB + NEO_KHZ800);

    void setup() {
      strip.begin();
      strip.show(); // Initialize all pixels to 'off'
    }

    // *** REPLACE FROM HERE ***

    void loop() {
      // Slower:
      // Strobe(0xff, 0x77, 0x00, 10, 100, 1000);
      // Fast:
      Strobe(0xFF, 0x00, 0xF8, 10, 50, 1000);
    }

    void Strobe(byte red, byte green, byte blue, int StrobeCount, int FlashDelay, int EndPause){
      for(int j = 0; j < StrobeCount; j++) {
        setAll(red,green,blue);
        showStrip();
        delay(FlashDelay);
        setAll(0,0,0);
        showStrip();
        delay(FlashDelay);
      }

     delay(EndPause);
    }

    // *** REPLACE TO HERE ***

    void showStrip() {
     #ifdef ADAFRUIT_NEOPIXEL_H
       // NeoPixel
       strip.show();
     #endif

    }

    void setPixel(int Pixel, byte red, byte green, byte blue) {
     #ifdef ADAFRUIT_NEOPIXEL_H
       // NeoPixel
       strip.setPixelColor(Pixel, strip.Color(red, green, blue));
     #endif
    }

    void setAll(byte red, byte green, byte blue) {
      for(int i = 0; i < 64; i++ ) {
        setPixel(i, red, green, blue);
      }
      showStrip();
    }

change the first three parameters in Strobe(0xFF, 0x00, 0xF8, 10, 50, 1000);

I guess you want to cycle through a list of defined colors with your strobe effect. For that you can save the colors in a 2-dimensional array and then cycle through the array with a for loop. The 2-dimensional array is then a group of colors, each defined by the 3 numbers for a RGB value. Somewhat like this:
#define NUM_COLORS   5
byte colors[NUM_COLORS][3] = {
    {0xFF, 0, 0},
    {0, 0xFF, 0},
    {0, 0, 0xFF},
    {0xFF, 0xFF, 0},
    {0, 0xFF, 0xFF}
};

void loop(){
    for(int i=0;i<NUM_COLORS;i++){
        Strobe(colors[i][0], colors[i][1], colors[i][2], 10, 50, 1000);
    }
}

Note, that this is not a complete code, but only the interesting parts. You can incorporate this into your code. You can change the number of colors and the colors itself to your liking (I only took some example values, that are easy to recognize).


text:
How to track a pressure sensor from analog inputs?
I am a beginner with arduino. I have been researching pressure sensors composed of 2 conductors that sandwich a layer of velostat. My understanding is the velostat when compressed creates resistance between the conductive plates meaning when stepped on the charge decreases. I wanted to inquire about a wiring scheme for connecting these sensors to my analog inputs of a arduino nano with ideally 8 sensors connected to the 8 analog inputs. What is the wiring scheme? I would like to detect a gradation in sensitivity as best as possible for tracking someone applying pressure to that sensor. I have not built the sensors yet so that aspect of the project is open ended. Thanks for your attention in the matter. I am new to the world of electronics so please explain in elementary terms.

It is not really clear, what exactly is your question here.
You are correct: The resistance of the velostat goes down, as pressure is applied to it. You have to build a voltage divider with the sensor and a normal resistor. The best value for that resistor highly depends on the sensor you build, because the way and the size you build it will control it's resistance. Then you can feed the middle pin of that voltage divider to an analog input.
The precision depends on many factors, including the sensor itself and the noise, that gets introduced into the analog input. Try and tweak your circuit, until it suits your needs.

What exactly is a voltage divider?

Two resistors in series, often (and also in this case) one of it with a variable resistance. One side connected to the supply voltage, the other side to ground. Then the voltage at the point between these resistors depends directly on the ratio of the resistors values. This is often used for analog measurement. For further explanation google voltage divider. There are many tutorials and sites on the web, that explain this perfectly.


text:
I cannot upload any code to my arduino uno
I am using ardunio uno on a windows 10 machine.
I have never been able to upload any code whatsoever.
Every time i get different errors, sometimes it's about com port, sometimes about memory, baud rate and what not.
This time I am getting the following error.
What should I do next?
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Jayesh Patel\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982 -warnings=none -build-cache C:\Users\JAYESH~1\AppData\Local\Temp\arduino_cache_625197 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jayesh Patel\Documents\Arduino\sketch_jun21a\sketch_jun21a.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Jayesh Patel\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982 -warnings=none -build-cache C:\Users\JAYESH~1\AppData\Local\Temp\arduino_cache_625197 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jayesh Patel\Documents\Arduino\sketch_jun21a\sketch_jun21a.ino
Using board 'uno' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Detecting libraries used...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp" -o "nul"
Generating function prototypes...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp" -o "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\preproc\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp" -o "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp.o"
Compiling libraries...
Compiling core...
Using precompiled core
Linking everything together...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.elf" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp.o" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/..\arduino_cache_625197\core\core_arduino_avr_uno_0c812875ac70eb4a9b385d8fb077f54c.a" "-LC:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982" -lm
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.elf" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.eep"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -R .eeprom  "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.elf" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.hex"
Sketch uses 1030 bytes (3%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "\\.\COM5": The semaphore timeout period has expired.

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Is it a genuine Arduino or does it have the CH340 USB to serial chip on it?

how did you choose COM5 serial port?

What board are you using? Is it a clone? Any chance of a picture?

If you have arduino with ch340 you need to install driver for board.

The OP seem to have a COM port ready (COM5), which means the driver is already installed.


text:
Function Millis() Arduino
I would like to make a countdown with arduino.
To do this I'm using the millis () function, but I have a problem, I can not reset this.
Reading on the internet I read that it is not possible to do this.
So how can I find an alternative for this?
In practice, when I pressed the button I started the countdown, while if I put it back, I went into the pause mode.

void inizio(){
  Serial.println("INIZIO");

  currentMillis1_general = millis();
  total_1 = currentMillis1_general - currentMillis_general;
  Serial.println(total_1);

  buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH){
    step_funzione = 1;
    delay(200);
  }
}

void countdown(){
  Serial.println("COUNTDOWN");

  display.setBrightness(7);

  currentMillis_general = millis();
  total_general = currentMillis_general - total_1;

  if(total_general - previousMillis_general >= interval_general){
    previousMillis_general += interval_general;
    //previousMillis_general = currentMillis_general;
    m = new_tempo/60;
    s = new_tempo%60;
    new_tempo--;
  }

  display.showNumberDec(m, true,2,0);
  display.showNumberDec(s, true,2,2);

  Serial.println(total_general);

  buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH){
    step_funzione = 0;
    delay(200);
  }
}

think about this ....How do you know when it is time to replace the oil in your car's engine? .... you cannot reset the odometer to zero

A way to accomplish "Reset" is to set your starting value equal to millis() again. To do the equivalent of "Pause", you need a pause counter. When you begin a pause, save millis() to pauseTime. When you resume running again, add millis() - pauseTime to your pauseCounter. Then your interval should not expire until millis() - pauseCounter > Interval).


text:
Include in different file make different compiling error
I'm have problem compiling a code.
ardutest.ino:

#include "mylib.h"
#include <SD.h>

void setup() {

}

void loop() {
  fn();
}

mylib.h:
#ifndef mylib_h
#define mylib_h

#include "Arduino.h"

void fn(File &_file);

#endif

mylib.c:
#include "mylib.h"

void fn(File &_file)
{
  _file = SD.open("LOG.TXT", FILE_WRITE);
  _file.println(42);
  _file.close();
}

When checking code in Arduino IDE I have this error:
In file included from sketch/mylib.c:1:0:
mylib.h:7: error: expected ')' before '&' token
 void fn(File &_file);
          ^
mylib.c:3: error: expected ')' before '&' token
 void fn(File &_file)
          ^
Multiple libraries were found for "SD.h"
 Used: /home/mario/Arduino/libraries/SD
 Not used: /home/mario/Programs/arduino/libraries/SD
exit status 1
expected ')' before '&' token

But if I put SD.h in mylib.h (other files are the same):
#ifndef mylib_h
#define mylib_h

#include "Arduino.h"
#include <SD.h>

void fn(File &_file);

#endif

I have this error:
In file included from /home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:26:0,
                 from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:29,
                 from /home/user/Arduino/libraries/SD/src/SD.h:20,
                 from sketch/mylib.h:5,
                 from sketch/mylib.c:1:
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:423:14: error: unknown type name 'pin_map_t'
 static const pin_map_t digitalPinMap[] = {

              ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:447:69: error: 'pin_map_t' undeclared here (not in a function)
 static const uint8_t digitalPinCount = sizeof(digitalPinMap)/sizeof(pin_map_t);

                                                                     ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h: In function 'getPinMode':
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:455:32: error: request for member 'ddr' in something not a structure or union
     return (*digitalPinMap[pin].ddr >> digitalPinMap[pin].bit) & 1;

                                ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:455:58: error: request for member 'bit' in something not a structure or union
     return (*digitalPinMap[pin].ddr >> digitalPinMap[pin].bit) & 1;

                                                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h: In function 'setPinMode':
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:464:26: error: request for member 'ddr' in something not a structure or union
       *digitalPinMap[pin].ddr |= 1 << digitalPinMap[pin].bit;

                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:464:57: error: request for member 'bit' in something not a structure or union
       *digitalPinMap[pin].ddr |= 1 << digitalPinMap[pin].bit;

                                                         ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:466:26: error: request for member 'ddr' in something not a structure or union
       *digitalPinMap[pin].ddr &= ~(1 << digitalPinMap[pin].bit);

                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:466:59: error: request for member 'bit' in something not a structure or union
       *digitalPinMap[pin].ddr &= ~(1 << digitalPinMap[pin].bit);

                                                           ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h: In function 'fastDigitalRead':
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:475:32: error: request for member 'pin' in something not a structure or union
     return (*digitalPinMap[pin].pin >> digitalPinMap[pin].bit) & 1;

                                ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:475:58: error: request for member 'bit' in something not a structure or union
     return (*digitalPinMap[pin].pin >> digitalPinMap[pin].bit) & 1;

                                                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h: In function 'fastDigitalWrite':
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:484:26: error: request for member 'port' in something not a structure or union
       *digitalPinMap[pin].port |= 1 << digitalPinMap[pin].bit;

                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:484:58: error: request for member 'bit' in something not a structure or union
       *digitalPinMap[pin].port |= 1 << digitalPinMap[pin].bit;

                                                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:486:26: error: request for member 'port' in something not a structure or union
       *digitalPinMap[pin].port &= ~(1 << digitalPinMap[pin].bit);

                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:486:60: error: request for member 'bit' in something not a structure or union
       *digitalPinMap[pin].port &= ~(1 << digitalPinMap[pin].bit);

                                                            ^
In file included from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:29:0,
                 from /home/user/Arduino/libraries/SD/src/SD.h:20,
                 from sketch/mylib.h:5,
Multiple libraries were found for "SD.h"
 Used: /home/user/Arduino/libraries/SD
 Not used: /home/user/Programs/arduino/libraries/SD
                 from sketch/mylib.c:1:
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h: At top level:
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:70:1: error: initializer element is not constant
 uint8_t const  SD_CHIP_SELECT_PIN = SS;

 ^
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:79:1: error: initializer element is not constant
 uint8_t const  SPI_MOSI_PIN = MOSI;

 ^
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:81:1: error: initializer element is not constant
 uint8_t const  SPI_MISO_PIN = MISO;

 ^
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:83:1: error: initializer element is not constant
 uint8_t const  SPI_SCK_PIN = SCK;

 ^
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:176:1: error: unknown type name 'class'
 class Sd2Card {

 ^
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:176:15: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
 class Sd2Card {

               ^
In file included from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:30:0,
                 from /home/user/Arduino/libraries/SD/src/SD.h:20,
                 from sketch/mylib.h:5,
                 from sketch/mylib.c:1:
/home/user/Arduino/libraries/SD/src/utility/FatStructs.h:405:1: error: initializer element is not constant
 uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY);

 ^
In file included from /home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Print.h:27:0,
                 from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:31,
                 from /home/user/Arduino/libraries/SD/src/SD.h:20,
                 from sketch/mylib.h:5,
                 from sketch/mylib.c:1:
/home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Printable.h:25:1: error: unknown type name 'class'
 class Print;
 ^
/home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Printable.h:33:1: error: unknown type name 'class'
 class Printable
 ^
/home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Printable.h:34:1: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
 {
 ^
In file included from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:31:0,
                 from /home/user/Arduino/libraries/SD/src/SD.h:20,
                 from sketch/mylib.h:5,
                 from sketch/mylib.c:1:
/home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Print.h:37:1: error: unknown type name 'class'
 class Print
 ^
/home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Print.h:38:1: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
 {
 ^
In file included from /home/user/Arduino/libraries/SD/src/SD.h:20:0,
                 from sketch/mylib.h:5,
                 from sketch/mylib.c:1:
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:39:1: error: unknown type name 'class'
 class SdVolume;

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:55:1: error: initializer element is not constant
 uint8_t const O_RDONLY = O_READ;

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:59:1: error: initializer element is not constant
 uint8_t const O_WRONLY = O_WRITE;

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:61:1: error: initializer element is not constant
 uint8_t const O_RDWR = (O_READ | O_WRITE);

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:63:1: error: initializer element is not constant
 uint8_t const O_ACCMODE = (O_READ | O_WRITE);

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:94:1: error: initializer element is not constant
 uint8_t const FAT_FILE_TYPE_MIN_DIR = FAT_FILE_TYPE_ROOT16;

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:137:1: error: unknown type name 'class'
 class SdFile : public Print {

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:137:14: error: expected '=', ',', ';', 'asm' or '__attribute__' before ':' token
 class SdFile : public Print {

              ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:431:1: error: unknown type name 'class'
 class SdVolume {

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:431:16: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
 class SdVolume {

                ^
In file included from /home/user/Arduino/libraries/SD/src/SD.h:21:0,
                 from sketch/mylib.h:5,
                 from sketch/mylib.c:1:
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h: In function 'FreeRam':
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:43:7: error: 'reinterpret_cast' undeclared (first use in this function)
   if (reinterpret_cast<int>(__brkval) == 0) {

       ^
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:43:7: note: each undeclared identifier is reported only once for each function it appears in
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:43:24: error: expected expression before 'int'
   if (reinterpret_cast<int>(__brkval) == 0) {

                        ^
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:45:36: error: expected expression before 'int'
     free_memory = reinterpret_cast<int>(&free_memory)

                                    ^
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:49:36: error: expected expression before 'int'
     free_memory = reinterpret_cast<int>(&free_memory)

                                    ^
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h: In function 'SerialPrint_P':
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:62:52: error: 'Serial' undeclared (first use in this function)
   for (uint8_t c; (c = pgm_read_byte(str)); str++) Serial.write(c);

                                                    ^
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h: In function 'SerialPrintln_P':
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:72:3: error: 'Serial' undeclared (first use in this function)
   Serial.println();

   ^
In file included from sketch/mylib.h:5:0,
                 from sketch/mylib.c:1:
/home/user/Arduino/libraries/SD/src/SD.h: At top level:
/home/user/Arduino/libraries/SD/src/SD.h:26:1: error: unknown type name 'namespace'
 namespace SDLib {
 ^
/home/user/Arduino/libraries/SD/src/SD.h:26:17: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
 namespace SDLib {
                 ^
/home/user/Arduino/libraries/SD/src/SD.h:119:1: error: unknown type name 'using'
 using namespace SDLib;
 ^
/home/user/Arduino/libraries/SD/src/SD.h:119:17: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'SDLib'
 using namespace SDLib;
                 ^
/home/user/Arduino/libraries/SD/src/SD.h:123:14: error: expected '=', ',', ';', 'asm' or '__attribute__' before ':' token
 typedef SDLib::File    SDFile;
              ^
/home/user/Arduino/libraries/SD/src/SD.h:124:14: error: expected '=', ',', ';', 'asm' or '__attribute__' before ':' token
 typedef SDLib::SDClass SDFileSystemClass;
              ^
In file included from sketch/mylib.c:1:0:
mylib.h:7: error: expected ')' before '&' token
 void fn(File &_file);
              ^
mylib.c:3: error: expected ')' before '&' token
 void fn(File &_file)
              ^
exit status 1
expected ')' before '&' token

If I use SD.h function in mylib, I need this in mylib.h file. Why is it happens?
The first error is about passing object as function argument. I'm following sample I found in others forum, then I don't know why it isn't working.
[SOLVED]
I rename mylib.c to mylib.cpp and solved the problem.

in first case you have SD.h included after mylib.h so File is not known

Firstly, there are different strategies for organizing header file structure. I don't know which one you follow. Within the popular approach that strives to keep all header files in self-sufficient state, mylib.h should include <SD.h> since mylib.h uses File type.
Secondly, when you actually included <SD.h> into mylib.h, you ran into a different problem. SD library is written as a C++ library. Its header files will not compile as C code. Meanwhile, you are trying to compile <SD.h> in C mode by indirectly including it into a mylib.c file, which is what causes the errors.

This library's header files contain many bizarre coding patterns that might create an impression as if someone was trying to make these headers compatible with C code (static const? static inline? Etc.), but this is an illusion. The code is exclusively C++, not C.

SD.h defines class File. Without that definition, 'File' is taken to be the name of an untyped argument (which will be assumed to be an int). Given that assumption, '&_file' is unexpected.


text:
Blynk app, DotStar bluetooth control code help
This is my setup:

Arduino Mega;
HM-10 bluetooth module (bought off ebay, so not sure if genuine but works);
Adafruit Dotstar addressable LED strip;
iOS Blynk app;

Hardware-wise, everything is connected and working properly.
My ultimate goal is to implement this LED strip on my car in the headlights.
At this point though, I want to have everything working off the Blynk app with 3 on/off switch buttons, linked to 3 virtual pins and not consider any code priority for the lights.
I have 3 light "shows" for the strip, which are in their own void functions.
These are:

Daytime runing lights: DRL();
Signal turn indicator: STI();
Police display: POL();

This is my first serious project so consider me a first time coder.
Each switch button should be linked to each light show and turn the strip on and off.
What I want more specifically: when I press the DRL switch, DRL should stay on. Only turn off when switch is pressed again. This works fine.
The STI I want to loop. but when I push the switch, it goes through the function only once. This is what I don't understand, as the Blynk.run() is in the void loop function, and the state of the virtual pin hasn't changed.
It's the same for the police lights, it goes through the sequence only once, but i want it looped.
So my question is: How can I loop the STI and POL functions in my code?
I have tried with a while function but i can't get out of it by reading the the virtual pin within the function.
Here is the entire code:
I am aware that the code might be messy, any input is appreciated.

#define BLYNK_PRINT Serial
#include <SPI.h>
#include <BlynkSimpleSerialBLE.h>

#include <Adafruit_DotStar.h>
#define NUMPIXELS 72

#include <SoftwareSerial.h>

Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DOTSTAR_BRG);

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "***";

uint32_t amber = 0x020600;
uint32_t white = 0x020202;
uint32_t red = 0x000200;
uint32_t blue = 0x000002;
//SoftwareSerial SerialBLE(10, 11); // RX, TX

BLYNK_WRITE(V1)
{
  int pinValue1 = param.asInt(); // assigning incoming value from pin V1     to a variable

  if (pinValue1 == 1) {
    Serial.print("Daytime running lights: ON ");
    Serial.println(pinValue1); //showing the actual virtual pin status 0/1
    DRL();
  }
  else {
    Serial.print("Daytime running lights: OFF ");
    Serial.println(pinValue1); //showing the actual virtual pin status 0/1
    OFF();
    Serial.print("off ok"); // this just helps me check where the code has   progressed
  }
}

BLYNK_WRITE(V2)
{
  int pinValue2 = param.asInt(); // assigning incoming value from pin V2 to    a variable

  if (pinValue2 == 1) {
    Serial.print("Dynamic turn indicator: ON ");
    Serial.println(pinValue2);  //showing the actual virtual pin status 0/1
    STI();
  }
  else {
    Serial.print("Dynamic turn indicator: OFF ");
    Serial.println(pinValue2);  //showing the actual virtual pin status 0/1
    OFF();
    Serial.print("off ok"); // this just helps me check where the code has  progressed
  }
}

BLYNK_WRITE(V3)
{
  int pinValue3 = param.asInt(); // assigning incoming value from pin V3 to a variable

  if (pinValue3 == 1) {
    Serial.print("Police Lights: ON ");
    Serial.println(pinValue3);
    POL();
  }
  else {
    Serial.print("Police Lights: OFF ");
    Serial.println(pinValue3);
    OFF();
    Serial.print("off ok"); // this just helps me check where the code has progressed
  }
}

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Blynk.begin(Serial1, auth);
  Serial.println("Waiting for connections...");

  strip.begin();  //initializes the strip
  strip.show();  //turn off LEDs within NUMPIXELS
}

void OFF() {
  for (int i; i <= 72; i++) { //turn off strip
    strip.setPixelColor(i, 0);
    strip.show();
  }
}

void DRL() {
  for (int i = 0; i <= 72; i++) {
    strip.setPixelColor(i, white);
    strip.show();
    delay(4);
  }
}

void STI() {
  //turn on dinamic indicator
  for (int i = 0; i <= 72; i++) {
    strip.setPixelColor(i, amber);
    strip.show();
    delay(2);
  }

  //turn off dinamic indicator
  for (int i; i <= 72; i++) {
    strip.setPixelColor(i, 0);
  }
  delay (200);  //on condition delay
  strip.show();
  delay (500);  //off condition delay
}

void POL() {

  for (int i = 0; i <= 36; i++) {
    strip.setPixelColor(i, red);
    strip.show();
  }
  delay(30);

  for (int i = 0; i <= 36; i++) {
    strip.setPixelColor(i, 0);
    strip.show();
  }
  delay(30);

  for (int i = 0; i <= 36; i++) {
    strip.setPixelColor(i, red);
    strip.show();
  }
  delay(30);

  for (int i = 0; i <= 36; i++) {
    strip.setPixelColor(i, 0);
    strip.show();
  }
  delay(30);

  for (int i = 0; i <= 36; i++) {
    strip.setPixelColor(i, red);
    strip.show();
  }
  delay(30);

  for (int i = 0; i <= 36; i++) {
    strip.setPixelColor(i, 0);
    strip.show();
  }
  delay(30);

  for (int i = 0; i <= 36; i++) {
    strip.setPixelColor(i, red);
    strip.show();
  }
  delay(30);

  for (int i = 0; i <= 36; i++) {
    strip.setPixelColor(i, 0);
    strip.show();
  }
  delay(100);

  for (int i = 37; i <= 72; i++) {
    strip.setPixelColor(i, blue);
    strip.show();
  }
  delay(30);

  for (int i = 37; i <= 72; i++) {
    strip.setPixelColor(i, 0);
    strip.show();
  }
  delay(30);

  for (int i = 37; i <= 72; i++) {
    strip.setPixelColor(i, blue);
    strip.show();
  }
  delay(30);

  for (int i = 37; i <= 72; i++) {
    strip.setPixelColor(i, 0);
    strip.show();
  }
  delay(30);

  for (int i = 37; i <= 72; i++) {
    strip.setPixelColor(i, blue);
    strip.show();
  }
  delay(30);

  for (int i = 37; i <= 72; i++) {
    strip.setPixelColor(i, 0);
    strip.show();
  }
  delay(30);

  for (int i = 37; i <= 72; i++) {
    strip.setPixelColor(i, blue);
    strip.show();
  }
  delay(30);

  for (int i = 37; i <= 72; i++) {
    strip.setPixelColor(i, 0);
    strip.show();
  }
  delay(100);
}

void loop()
{
  Blynk.run();
}

The way the BLYNK_WRITE functions works is that they are called every time device gets an update of Virtual Pin value from the app. Now if you want to run something on a timer, or in a loop there is a function called BlynkTimer. You write your own function that you want to be looped and use this feature to define how often it should repeat. You can control execution by setting a boolean flag in the BLYNK_WRITE function and checking it in the loop, or by running the enable() and disable() methods of the timer. So, you can do something like this (without libraries, just an example):
BlynkTimer timer; // create timer

void myTimer()
{
    // toggle an LED
    static bool state;
    digitalWrite(13, state);
    state = !state;
}

void setup()
{
  Blynk.begin(details); // blynk start
  timer.setInterval(1000L, myTimer); // repeat the timer once a second
  pinMode(13, OUTPUT); // LED pin as output
}

void loop()
{
  Blynk.run(); // Runs all Blynk stuff
  timer.run(); // runs BlynkTimer
}

You can read more about it in the docs.


text:
Start VL53l0X measurement failed
The initialization of the ToF fails with this code. I'm trying to frankenstein it with Radiohead RFM69, so far no luck.
// rf69_reliable_datagram_client.pde
// -*- mode: C++ -*-
// Example sketch showing how to create a simple addressed, reliable messaging client
// with the RHReliableDatagram class, using the RH_RF69 driver to control a RF69 radio.
// It is designed to work with the other example rf69_reliable_datagram_server
// Tested on Moteino with RFM69 http://lowpowerlab.com/moteino/
// Tested on miniWireless with RFM69 www.anarduino.com/miniwireless
// Tested on Teensy 3.1 with RF69 on PJRC breakout board

#include <RHReliableDatagram.h>
#include <RH_RF69.h>
#include <SPI.h>

#include "Seeed_vl53l0x.h"
Seeed_vl53l0x VL53L0X;

#define CLIENT_ADDRESS 1
#define SERVER_ADDRESS 2

// Singleton instance of the radio driver
RH_RF69 driver;
//RH_RF69 driver(15, 16); // For RF69 on PJRC breakout board with Teensy 3.1
//RH_RF69 rf69(4, 2); // For MoteinoMEGA https://lowpowerlab.com/shop/moteinomega

// Class to manage message delivery and receipt, using the driver declared above
RHReliableDatagram manager(driver, CLIENT_ADDRESS);

void setup()
{
  VL53L0X_Error Status = VL53L0X_ERROR_NONE;
  Serial.begin(115200);
  if (!manager.init())
    Serial.println(F("init failed"));

  // Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM

  // If you are using a high power RF69, you *must* set a Tx power in the
  // range 14 to 20 like this:
  // driver.setTxPower(14);

  Status = VL53L0X.VL53L0X_common_init();
  if (VL53L0X_ERROR_NONE != Status) {
    Serial.println(F("start vl53l0x mesurement failed!"));
    VL53L0X.print_pal_error(Status);
    while (1);
  }

  VL53L0X.VL53L0X_long_distance_ranging_init();

  if (VL53L0X_ERROR_NONE != Status) {
    Serial.println(F("start vl53l0x mesurement failed!"));
    VL53L0X.print_pal_error(Status);
    while (1);
  }

}

unsigned int findDistance() {
  VL53L0X_RangingMeasurementData_t RangingMeasurementData;
  VL53L0X_Error Status = VL53L0X_ERROR_NONE;

  memset(&RangingMeasurementData, 0, sizeof(VL53L0X_RangingMeasurementData_t));
  Status = VL53L0X.PerformSingleRangingMeasurement(&RangingMeasurementData);
  if (VL53L0X_ERROR_NONE == Status) {
    if (RangingMeasurementData.RangeMilliMeter >= 2000) {
      Serial.println(F("out of range!!"));
    } else {
      //Serial.print("Measured distance:");
      //Serial.print(RangingMeasurementData.RangeMilliMeter);
      //Serial.println(" mm");
      return RangingMeasurementData.RangeMilliMeter;
    }
  } else {
    Serial.print(F("mesurement failed !! Status code ="));
    Serial.println(Status);
    return 0;
  }
}

uint8_t data[] = "Hello..there";
// Dont put this in the stack:
uint8_t buf[RH_RF69_MAX_MESSAGE_LEN];

void loop()
{
  //Serial.println("Sending to rf69_reliable_datagram_server");

  // Send a message to manager_server
  if (manager.sendtoWait(data, sizeof(data), SERVER_ADDRESS))
  {
    // Now wait for a reply from the server
    uint8_t len = sizeof(buf);
    uint8_t from;
    if (manager.recvfromAckTimeout(buf, &len, 2000, &from))
    {
      Serial.print(F("got reply from : 0x"));
      Serial.print(from, HEX);
      Serial.print(F(": "));
      Serial.println((char*)buf);
    }
    else
    {
      Serial.println(F("No reply, is rf69_reliable_datagram_server running?"));
    }
  }
  else
    Serial.println(F("sendtoWait failed"));
  delay(500);
}

Please try the  I2C Scanner sketch to check, if it can find the sensor on the standard address 0x29, which is used in the library. If it cannot find any device, the communication does not work.Then check the wiring, add strong pullup resistors to the I2C lines (4.7kOhm for example). And include your wiring in the question.

@chrisl thanks for your response, an important point to mention is that the code works when run alone, its only when I combine the sensor code with the radio module code i run into problems. Thanks again


text:
Safe changes in the Arduino Libraries and use them
I changed 2 Arduino Libraries because i have a 9 bit data protocol, now i want use the amended Libraries on my Arduino mega2560.
At first i have set a 9 bit data mode that can i do when i set the UCSZ12 bit on 1(original code under the following link: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.cpp#L103 ):
void HardwareSerial::begin(unsigned long baud, byte config)
  ...
  sbi(*_ucsrb, RXCIE0);
  sbi(*_ucsrb, UCSZ12);  // chance: set 9-bit data mode on 1
  cbi(*_ucsrb, UDRIE0);
  ...

At second i want throw an interrupt when the 9th bit is an 1 that can i do when i change the code like the follow (original code under the following link : https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial_private.h#L101 ):
void HardwareSerial::_rx_complete_irq(void)
  if (bit_is_clear(*_ucsra, UPE0)) {
    bool is_address = UCSR0B & _BV(RXB80);
    unsigned char c = *_udr;
    if (is_address) {
      do_something_with_address(c);
      return;
    }
  rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;
...

What must i do with the two file´s?
How can i use the changed Libraries?

If you edited them in your local IDE installation then there's nothing to do. I don't quite understand your question - you edited the files, now you want to know what to do with them? They have been edited. If you saved the files after editing them (which you would have done) then what is it you are now hoping to do with them?

I write a new file because i did´t find them in the local IDE. It will be nice when you have a path than i know what i have to do.

Oh sorry i find it, in the link from Github is the path i didn´t see it the whole weekend sry that was my fail.

I'd rename them to something new, and add them to the libraries folder.

In Linux, after building the data base, "locate HardwareSerial.cpp" results in: /usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp and several other hits.  This works for Mac as well.  If you are on a Windows machine, the search feature varies from version to version of Windows.   And some implementations are very slow.  If you can not find the file ... consider upgrading to the latest version of the Arduino IDE.

How can i close that question when i have the answer but no community answer?

I found the path to the files i want change in the github link so i can change the files(C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino).
I enable the uart for 9 bit, i add sbi(*_ucsrb, UCSZ12);  in HardwareSerial::begin
I decided that i only send a Flag to my PC when the 9th bit is set. For that i change the _rx_buffer to a 2 byte matrix (short _rx_buffer). Now i send the databyte in the low-byte and flags for 9 bit, framing error and overrun error in the high-byte. That i can do that i change the void HardwareSerial::_rx_complete_irq(void) code like the follow:
void HardwareSerial::_rx_complete_irq(void)
{
  if (bit_is_clear(*_ucsra, UPE0))
  {
    bool is_address = UCSR0B & _BV(RXB80);
    bool is_framError = UCSR0A & _BV(FE0);
    bool is_overError = UCSR0A & _BV(DOR0);
    unsigned char c = *_udr;
    rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;

    if (i != _rx_buffer_tail)
    {
     _rx_buffer[_rx_buffer_head] = c;
     _rx_buffer[_rx_buffer_head] |= is_address << 8;
     _rx_buffer[_rx_buffer_head] |= is_framError << 9;
     _rx_buffer[_rx_buffer_head] |= is_overError << 10;
     _rx_buffer_head = i;
    }
  }
  else {    *_udr;  };
}

I hope this will work and i can evaluate the data right at the PC.
Frindly wishes sniffi