text:
Why is EEPROM commit not registering int values?
       if(jsonDoc["delayOn"].as<int>() <= 255 && jsonDoc["delayOff"].as<int>() <= 255 && jsonDoc["delayUnitOn"].as<int>() <= 2 && jsonDoc["delayUnitOff"].as<int>() <= 2 &&
         jsonDoc["mode"].as<int>() <= 1 && jsonDoc["blink"].as<int>() <= 1 &&
         jsonDoc["timeOnHour"].as<int>() <= 23 && jsonDoc["timeOnMinute"].as<int>() <= 59 &&
         jsonDoc["timeOffHour"].as<int>() <= 23 && jsonDoc["timeOffMinute"].as<int>() <= 59) {

        int val;
        int addr_init = (relay*eepromSlotsPerRelayPin)*sizeof(int);

        val = jsonDoc["blink"].as<int>();
        EEPROM.put(addr_init,val);
        if(jsonDoc["blink"].as<int>()==1){ //0=off,1=on

          val = jsonDoc["mode"].as<int>();
          EEPROM.put(addr_init+(5*sizeof(int)),val);

          if (jsonDoc["mode"].as<int>()==0){ //blink mode

            val = jsonDoc["delayOn"].as<int>();
            EEPROM.put(addr_init+(1*sizeof(int)),val);
            val = jsonDoc["delayOff"].as<int>();
            EEPROM.put(addr_init+(3*sizeof(int)),val);
            //1=minute,0=second,2=hour
            val = jsonDoc["delayUnitOn"].as<int>();
            EEPROM.put(addr_init+(2*sizeof(int)),val);
            val = jsonDoc["delayUnitOff"].as<int>();
            EEPROM.put(addr_init+(4*sizeof(int)),val);
            EEPROM.end();

          }else if(jsonDoc["mode"].as<int>()==1){ //time switch mode

            val = jsonDoc["timeOnHour"].as<int>();
            EEPROM.put(addr_init+(6*sizeof(int)),val);
            val = jsonDoc["timeOnMinute"].as<int>();
            EEPROM.put(addr_init+(7*sizeof(int)),val);
            val = jsonDoc["timeOffHour"].as<int>();
            EEPROM.put(addr_init+(8*sizeof(int)),val);
            val = jsonDoc["timeOffMinute"].as<int>();
            EEPROM.put(addr_init+(9*sizeof(int)),val);
            EEPROM.end();
          }
          else {
            request->send(412, "text/plain", "unknown mode");
            return;
          }
        }
      }
      else {
        request->send(412, "text/plain", "a parameter is not within limits");
        return;
      }

      //initBlinkPinObjs
      int addr_init;
      int val,uom;
      for(int i = 0; i<maxRelayPins; i++) {
        bPinObjs[i].pin = relayPins[i];
        //EEPROM Slot per Relay dataStruct
        //0=>enable, 1=>durationOn, 2=>durationOnTimeMeasure,
        //3=>durationOff, 4=>durationOffTimeMeasure
        //5=>mode, 6=>timeOnHour, 7=>timeOnMinute,
        //8=>timeOffHour, 9=>timeOffMinute

        addr_init = (i*eepromSlotsPerRelayPin)*sizeof(int);

        val = 0;
        EEPROM.get(addr_init,val);
       bPinObjs[i].enable = val;

        val = 0;
        EEPROM.get(addr_init+(5*sizeof(int)),val);
        bPinObjs[i].mode = val;

        val = 0;
        EEPROM.get(addr_init+(6*sizeof(int)),val);
        bPinObjs[i].timeOnHour=val;

        val = 0;
        EEPROM.get(addr_init+(7*sizeof(int)),val);
        bPinObjs[i].timeOnMinute=val;

        val = 0;
        EEPROM.get(addr_init+(8*sizeof(int)),val);
        bPinObjs[i].timeOffHour = val;

        val = 0;
        EEPROM.get(addr_init+(9*sizeof(int)),val);
        bPinObjs[i].timeOffMinute = val;

        //delayOn
        //convert to millisec
        uom = 0;
        EEPROM.get(addr_init+(2*sizeof(int)),uom);
        switch(uom){
          case 0:
            bPinObjs[i].durationOn=0;
            val = 0;
            EEPROM.get(addr_init+(1*sizeof(int)),val);
            bPinObjs[i].durationOn = val*1000;
          break;
          case 1:
            bPinObjs[i].durationOn=0;
            val = 0;
            EEPROM.get(addr_init+(1*sizeof(int)),val);
            bPinObjs[i].durationOn = val*60000;
          break;
          case 2:
            bPinObjs[i].durationOn=0;
            val = 0;
            EEPROM.get(addr_init+(1*sizeof(int)),val);
            bPinObjs[i].durationOn = val*3600000;
          break;
          default:
          break;
        }
        //delayOff
        //convert to millisec
        uom = 0;
        EEPROM.get(addr_init+(4*sizeof(int)),uom);
        switch(uom){
          case 0:
            bPinObjs[i].durationOff = 0;
            val = 0;
            EEPROM.get(addr_init+(3*sizeof(int)),val);
            bPinObjs[i].durationOff = val*1000;
          break;
          case 1:
            bPinObjs[i].durationOff = 0;
            val = 0;
            EEPROM.get(addr_init+(3*sizeof(int)),val);
            bPinObjs[i].durationOff = val*60000;
          break;
          case 2:
            bPinObjs[i].durationOff = 0;
            val = 0;
            EEPROM.get(addr_init+(3*sizeof(int)),val);
            bPinObjs[i].durationOff = val*3600000;
          break;
          default:
          break;
        }
      }

--JSON INPUT printed from server--

relay:0
blink:1
mode:1
delayOn:56
delayOff:2
delayUnitOn:0
delayUnitOff:0
timeOnHour:5
timeOnMinute:56
timeOffHour:7
timeOffMinute:48

OUTPUT printed from server:
--Objects content--
Size of INT:4
---------0--------- init addr: 0
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------1--------- init addr: 40
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------2--------- init addr: 80
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------3--------- init addr: 120
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------4--------- init addr: 160
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------5--------- init addr: 200
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------6--------- init addr: 240
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------7--------- init addr: 280
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------8--------- init addr: 320
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0

This is inside an esp8266 async webserver server.on method.
My EEPROM.begin is in setup function.
Initially, only the first put within a block becomes committed .
Now, nothing is registering after I implemented the sizeof(int) inside addresses.
The intention is to store int data passed thru http post per relay pin [total of 9 pins]. The program then uses the data to perform on a relay:

blink
switch on/off based on time (hour,minute)
...

I've tried all sorts to fix:

commit,end after every put
EEPROM.begin(512) then commit & end on every put
add delays
use end only instead of commit
add address range for sizeof(int)

try the arduino example code

how do you know that commit applies to only the first put?

I print it in Serial. I did try the write & read from sample but it does not meet my requirement to store int.

(relay*eepromSlotsPerRelayPin)+(relayDataIndex * sizeOf(int)) will try this out as the address values based on @VictorTiamson and @RollyAvecilla suggestions.

edit: ((relay*eepromSlotsPerRelayPin)*sizeof(int))+(relayDataIndex * sizeof(int))

New challenge, now nothing is registering. Edited the code displayed in post with my updates.

Weird, i commented out the val=0; before EEPROM.gets also replaced EEPROM.end with EEPROM.commit.
This is the output now:
--Objects content--
Size of INT:4
---------0--------- init addr: 0
[0]enable: 1
[4]durationOn: 3000
[8]durationOnUom: 0
[12]durationOff: 2000
[16]durationOffUom: 0
[20]mode: 1
[24]onHr: 9
[28]onMin: 11
[32]offHr: 9
[36]offMin: 12
---------1--------- init addr: 40
[40]enable: 1
[44]durationOn: 0
[48]durationOnUom: -1
[52]durationOff: 0
[56]durationOffUom: -1
[60]mode: -1
[64]onHr: -1
[68]onMin: -1
[72]offHr: -1
[76]offMin: -1
---------2--------- init addr: 80
[80]enable: 1
[84]durationOn: 0
[88]durationOnUom: -1
[92]durationOff: 0
[96]durationOffUom: -1
[100]mode: -1
[104]onHr: -1
[108]onMin: -1
[112]offHr: -1
[116]offMin: -1
---------3--------- init addr: 120
[120]enable: 1
[124]durationOn: 0
[128]durationOnUom: -1
[132]durationOff: 0
[136]durationOffUom: -1
[140]mode: 1
[144]onHr: 5
[148]onMin: 56
[152]offHr: 7
[156]offMin: 48
---------4--------- init addr: 160
[160]enable: 1
[164]durationOn: 0
[168]durationOnUom: -1
[172]durationOff: 0
[176]durationOffUom: -1
[180]mode: -1
[184]onHr: -1
[188]onMin: -1
[192]offHr: -1
[196]offMin: -1
---------5--------- init addr: 200
[200]enable: 1
[204]durationOn: 0
[208]durationOnUom: -1
[212]durationOff: 0
[216]durationOffUom: -1
[220]mode: -1
[224]onHr: -1
[228]onMin: -1
[232]offHr: -1
[236]offMin: -1
---------6--------- init addr: 240
[240]enable: 1
[244]durationOn: 0
[248]durationOnUom: -1
[252]durationOff: 0
[256]durationOffUom: -1
[260]mode: -1
[264]onHr: -1
[268]onMin: -1
[272]offHr: -1
[276]offMin: -1
---------7--------- init addr: 280
[280]enable: 1
[284]durationOn: 0
[288]durationOnUom: -1
[292]durationOff: 0
[296]durationOffUom: -1
[300]mode: -1
[304]onHr: -1
[308]onMin: -1
[312]offHr: -1
[316]offMin: -1
---------8--------- init addr: 320
[320]enable: 1
[324]durationOn: 0
[328]durationOnUom: -1
[332]durationOff: 0
[336]durationOffUom: -1
[340]mode: -1
[344]onHr: -1
[348]onMin: -1
[352]offHr: -1
[356]offMin: -1

--JSON inputs--

relay:0
blink:1
mode:1
delayOn:3
delayOff:2
delayUnitOn:0
delayUnitOff:0
timeOnHour:9
timeOnMinute:11
timeOffHour:9
timeOffMinute:12


text:
Arduino outputting 4.7V instead of 3.3V when using I2C communication/sensor?
TOF050C-VL6180X Sensor was not responding, so I checked it with a multi-meter, and the VIN, GND solder pins on it read 4.7V. Double-checked Mega voltage, without anything connected, and it shows stable 3.6V. Connected a different ToF and it works perfectly, with a 3.6V on it.
So that proves that sensor is damaged (might've powered it with 5V at first), but I don't understand how is it taking more than the regulated 3.3V? If it was shorted, it would read 0V, and if something burnt, it would be open circuit and show ~3.3V, right? So how is it just getting 4.7V out of nowhere? Any ideas on what I'm not understanding here?
Thank you!
EDIT: More info, tried to isolate issue as much as I could
1) The non-working sensor shows 4.7V

2) The working sensor shows 3.4V and outputs distance to serial

3) This is where it gets weird. I uploaded the simple blink sketch and now the working sensor shows 4.7V too

4) So I tried disconnecting the SDA/SCL, while leaving power connected, with the blink sketch running, and it's back to 3.3V!

**Tried the same steps with a different Mega, and it always shows 3.3V, no matter the configuration!
Now I'm very lost. So is the Arduino semi-damaged, with the I2C communication acting weird? Is it still safe to use with the project, if it technically works?

it is near impossible to guess correctly ... please provide a circuit diagram of the connections ... also provide a description of how you connected the voltmeter

@jsotola My project is a mess of wires and was hoping there are only so many reasons for such voltage incompatibility, but you're right, yall ain't clairvoyant. So I tried to isolate and detail the issue in the edit.

The Arduino Wire enables the internal pullup resistor on SDA and SDL. The internal pull-ups are specified at 20k to 50k. So you are providing 5V (or there about) to the sensor, though through a high resistance connection. So, the voltage isn't coming from nowhere.
It is not unlikely that there protection/clamp diodes in the sensor IC or on the sensor board that connect these signals forward through the diode to the IC's 3.3v connection.
So your SCL/SDA can be seen as very weakly (through roughly 35k) trying to backfeed your 3.3V regulator which is probably just blocking the current. If the sensor/board is using no current to speak of, either because it just doesn't normally or because it's dead, you would measure 5V minus a diode drop, or roughly the 4.7V you're seeing.
If you assume the internal resistors are both at 20K as a "worst" case scenario for a calculation, the current needed through one to drop 5v to 3.3v is 85uA. So with 170uA load on the board that would drop the 3.3V pin  connection back to its 3.3V level. About 170uA will flow through a 20k resistor with 3.3V across it. So if you want experiment take any resistor from about 470ohms all the way to just shy of 20k in parallel with your 3.3V / GND measurement and see if your 4.7V measurement doesn't drop right down to the normal 3.3V output.

Can't say I 100% understand the explanation, but tested it out with both a 560 and 18k resistor, and it really does go back to 3.3V, thanks! So the dead sensor pulls the 5V from I2C's pull-up resistor, because there's no load on the sensor...but then adding a load to 3.3V, it somehow ignores the 5V coming from I2C?
In the end, everything is fine and the board just isn't the highest "quality", with the mentioned worst case scenario of ~20K pull-up? Nothing to worry about and I can continue working with the board?

Also, since it's not exactly a specific sensor issue, is there a better title I could use? Like "Arduino outputting 4.7V instead of 3.3V when using I2C communication/sensor?". Can't find any posts about such an issue, so if someone's looking, they would realize that whatever is connected to 3.3V is just dead.

Interesting. Well, maybe I'll scrap that part of the answer. The principle part of it is that there is a path to 5V. It's not being spontaneously generated.  Internal to the ATMega2560 there is effectively a pair of resistors between 20K and 50K in value that can be enabled that connect SCL and SDA to VCC (5V).  They normally are enabled when you use the Wire library.  The load is relevant here because it is through a resistance. You could also get 5V actively driving them HIGH but I haven't seen your code. I'll watch the question for details.

Oh, was there something unexpected about my answer? Here's how the resistor testing looked, if you're curious - breadboard powered by 3.3V pin, with resistor and sensor in parallel. The code is just the basic example from "Adafruit_VL6180X" library, and there is nothing driving pins HIGH in the example, but maybe deeper in the library.
And since you're not mentioning anything about the Arduino board acting weirdly, I'll take it as a green light that it's working within acceptable parameters.

I'm not going to explain the entire thinking process in the comments. But, in short my experience with using and helping with this kind of board and attaching this kind of thing has lead me to tentative assumption a board usually fine unless user reported using voltages above 5V, smoke, heat, smell, or light or unless it has been rather definitely proved not-fine. If I get bored may play around with the same sort of experiment with resisters and a comparable Arduino or otherwise remove the part of the answer that you have more or less shown to be unhelpful.

source: Stack Exchange

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

sort: votes


text:
Why won't this work as a delay?
I'll start off by saying I'm very very new to coding, so please bare with me.
I'm doing an assignment where the task is to create a traffic light system, but blocking delays aren't allowed. I have looked into "blink without delay", but it seems that option would require me to create far too confusing and long code than is needed. So instead I used for, else and goto functions together since it was a lot simpler and cleaner, but I have heard goto isn't a preferred option,
for(int i = 0; i < 20; i = i + 1)
{
    break0:
    digitalWrite(Traffic_R, HIGH);
    long int CurrentMillis1 = millis();

    break1:
    if (millis() - CurrentMillis1 <= 250){
        digitalWrite(Pedestrian_R, HIGH);
        goto break1;
    }else{
        long int CurrentMillis2 = millis();

        break2:
        if (millis() - CurrentMillis2 <= 250){
            digitalWrite(Pedestrian_R, LOW);
            goto break2;
        }
    }
}

Then I made another way without goto function,
for(int Test1 = millis(); Test1 < 7500; Test1 + millis())
{
  digitalWrite(LED, HIGH);
}

TLDR
So my question is, are either of these methods a "blocking method", like delay is? Also what are the pros and cons of each method? Also I can upload the code for the first method if needed. Thanks heaps in advance!

I really do not agree that this code is “simpler and cleaner”. The 1st solution is what you would call “spaghetti code” and does nothing more than “busy waiting” i.e. it will not allow you to do anything else while the delay is happening (just like a normal “delay()” would). The 2nd solution is also “busy waiting” but a bit cleaner code. The reason solutions like “blink without delay” exist, is because they allow your code to delay some things (for ex. turning on an LED in a specific rythm) while continuing with others (for ex. Checking for a button or handling I/O). Your code cannot do that.

TBH, you first solution looks ugly, both in terms of control flow logic and indentation. And as StarCat says, there is no difference between a busy waiting loop and using delay(). Your second solution does not work, mainly because Test1 is not changed in the loop. -- Anyway, there is no need to call digitalWrite() repeatedly with the same arguments.

Try to avoid the use of goto, it is said to be a bad practice

Fun fact: (Here in Greece [i don't know if anywhere else too]) we call goto as the "black sheep" of programming

break1:
if (something)
  goto break1;

is basically a while loop - just more confusing to read.

Also I can upload the code for the first method if needed.

You can upload it, of course. Personally I would mark you down for using goto.

are either of these methods a "blocking method", like delay is?

Neither method literally blocks. The delay function blocks because it doesn't return until the time is up. Your loops don't block because you could conceivably do something else in the loop.

I have heard goto isn't a preferred option

For a good reason. Do you think that, if you looked at your code again in a year, you would easily understand it? I have been coding for years and would have to carefully follow all the ways that the goto could jump around in unexpected ways.
At least with a while loop you have a well-defined start and end of the loop.

Here I have a simple example of cycling over 3 LEDs with the same 'delay' for every LED.
void loop() {

  static unsigned long previousMillis;
  static uint8_t cycleCounter;

  if (millis() - previousMillis > 100) {
    previousMillis = millis();
    digitalWrite(LEDS_CENTRAL_PIN, cycleCounter == 0);
    digitalWrite(LEDS_LEFT_PIN, cycleCounter == 1);
    digitalWrite(LEDS_RIGHT_PIN, cycleCounter == 2);
    cycleCounter++;
    if (cycleCounter == 3) {
      cycleCounter = 0;
    }
  }
}

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


text:
Is it possible to insert your own routine into the Reset procedure
I'm working with  ATmega328 NANO boards, and I would like to know if it is possible to INSERT my own routine, to be included in the things done during reset, BEFORE any pre-C initialization is done, or any upload of new code occurs. If this is possible, I'd like to know how. I'd want to be able to "install" this routine during setup(). I also would not expect it to work after a power loss. I'm talking about a reset caused by pressing the reset button, uploading code, opening a serial port, or any reset that was NOT caused by a loss of power.
I'm including a simple example sketch illustrating what I would LIKE to do, but it obviously won't do what I want as written, because I do not know the "magic" answer I'm seeking,
I've defined and initialized a global static byte outside of any functions. The setup() simply reads a byte from EEPROM and displays it with Serial.print(), and then stores its value in that global 'number'.  Now notice I created a void(void) function called magic(). It simply increments the global number and stores it in EEPROM. I call it "magic() because what I need to do to call it is unknown. I want some way to "install" magic() during setup(), so that it runs only as part of the reset process, before anything within code or data space is affected. By install, I don't mean just call the function. It should not actually be called unless RESET occurs.   Whatever "magic" has to be added to make this happen, the proof of the pudding will be that after loading the sketch. every time you press RESET, or even upload the sketch again, the printed number will be different, because it was incremented and saved when reset was pushed. NOTE: (I just edited some stupid errors here)
#include <EEPROM.h>

static uint8_t number =0;

void setup()
{
  uint8_t n = EEPROM.read(0);
  Serial.begin(57600);
  Serial.print(n);
  number = n;

  // somehow, install "magic" routine here

}

void loop() { }

void magic(void)
{
 ++number;
 EEPROM.write(0, &number);
}

why not at first line in setup()?

Yes, it is possible. See the documentation on memory
sections, from the avr-libc manual. For example:
// Run this after initializing the stack pointer and zero_reg, but
// before initializing the RAM.
void __attribute__((naked, used, section(".init3"))) magic(void)
{
    // Whatever...
}

Note that this runs after both a warm reset and a cold boot. See
Gerben's answer if you want to tell the difference between these two
reset conditions.
Note also that, if you just want some data to be preserved through a
reset, you can put it in the .noinit section, no need to use the EEPROM.

Edit 1: In response to the OP's comment, here is a small program
demonstrating the technique. It just quickly blinks the LED three times
early in the program initialization, then three more times, more slowly,
during setup():
#include <util/delay.h>

// Blink the LED three times, fast, early in the initialization.
void __attribute__((naked, used, section(".init3"))) magic(void)
{
    DDRB |= _BV(PB5);      // pin PB5 = digital 13 as output
    for (int i= 0; i < 6; i++) {
        PINB |= _BV(PB5);  // toggle PB5
        _delay_ms(100);
    }
}

// Blink the LED three times, slowly.
void setup()
{
    pinMode(13, OUTPUT);
    for (int i = 0; i < 6; i++) {
        delay(300);
        digitalWrite(13, !(i & 1));
    }
}

void loop(){}

I tested it on an Uno, and it works.
Note that magic() runs before the Arduino core library has been
initialized. At this point, many core function, like delay(), do not
work. Any job that is done here should be done low-level, using only
direct port access and avr-libc calls.
Edit 2: In the previous version of this answer I forgot the used
attribute. It worked with the old Arduino setup I tested with, but not
with the newest IDE. Adding the used attribute fixes this.

Well first... I edited my "wishlist" sketch a little, because i had some stupid errors (Forgot the Serial.begin and wasn't properly formatting the EEPROM calls. But unfortunately what you've suggested compiles, but doesn't work. If you try it with the editing my corrected sketch with your suggestion, you'll see it compiles, but won't work. The proof is that "255"  is always printed. I even tried substituting a short for() loop instead of the EEPROM write: "pinMode(13, OUTPUT);
for (int i= 0; i < 10; i++) {digitalWrite(13, i & 1); delay(20);}"  The LED doesn't flash when you press RESET.

@Randy: What I suggested does work. The Arduino core library doesn't if it has not been initialized. See my edited answer.

Hmmm... well I don't have any UNOs, only NANO boards. Doesn't work there. I do understand the wisdom of starting with a very low level and simple example. The only thing I changed in your edited code was to make the setup blink fast (300mS delay), and the magic() one 1000mS, so i wouldn't miss it. Also tried using different init levels. It compiles, but magic() has no pixie dust here so far. ;-) I'm sure this is the best advice I've gotten yet, and most likely to work. Can you think of why I'm not having any luck?

Why would "PINB |= _BV(PB5)" alternate the LED pin state?

@Randy because the datasheet says so in §18.2.2.

@Randy: My bad. I didn't notice that the current Arduino toolset now requires the used attribute for this to work. Edited the answer accordingly.

Eureka! But I'm still not sure. 1st, as it turns out, adding my EEPROM.write(0, ++number); to magic()  does work. I know because if I EEprom.read(0) and print it in setup(),   it will displays 1, not 255. The problem is when RESET is pressed, I'd hope to see it print '2', but instead it remains "1". If magic() really ran BEFORE data space was initialized, that would be the case. I also tried removing the "=0", and also removed the static keyword, which should move it to the 'bss' section. But the sketch still prints always '1'. So magic() runs before setup(), but not before memory clear.

And I might add, the reason I want to save to EEPROM on RESET, is because I want to also survive a code change (or code improvement in a big project). I normally save this way on loss of power, with an electric circuit that lets me know well in advance of the AVR losing power, and since that works I can pretty easily just turn off my power switch, then turn it back on and upload my code change. But if I can also save to EEPROM on reset, that will be a major bonus in some projects.

@Randy: I tested the code in your question with no modification other than the added attributes. This time I tested with the IDE version 1.8.5. Repeatedly pressing RESET, it prints "207208209210211212..." as expected. Also, note that magic() runs before the memory is initialized but after the bootloader, which can itself clobber some of your RAM, thus defeating your purpose. You may have to write a custom bootloader to be safe...

Well for me its printing the same value of "1" over and over again, and upgrading to 1.8.5 made no difference. I also see that if I change its initial value of 'number' to 1 instead of 0, the same code prints 129 repeatedly!. So I guess this just doesn't work with the NANO, and in any case is not reliable. And really, if magic() is going to run AFTER after "bootloader",  then the docs are lying to us.and,that pretty much brings me back to square 1. Would be nice if they actually gave us a true init0 that happened before ANYTHING when you press RESET. Guess not.

I'd like to at least experiment with "noinit" section, as I've been told elsewhere that trying to use a high level EEPROM.write() , like my example) won't work.. But now I don't think my NANO boards respect ANY rules! I made a simple sketch with byte attribute((naked, used, section (".noinit"))) number; Then my setup() does nothing but Serial.begin(57600); and Serial.println(number++); It compiles, but pressing reset always results in '0' being printed. If 'number' were not being initialized, and power isn't lost, I'd expect number (whatever it's value) to be +1 each run. No luck. :-(

@Randy: 1. “naked” is an attribute for code, “noinit” is for data. It doesn't make sense to mix them. 2. “noinit” means the data will not be overwritten by the startup code of the C runtime, but it doesn't prevent the bootloader from writing into that part of the RAM: the bootloader knows nothing about your sketch.

@EdgarBonet OK... that's helpful. But still..can you explain this?  Simple sketch... start with a line saying "byte number attribute((used, section (".noinit"))) ; Then, setup() just Serial.print()'s the number, and then increments it. Thats all. So whatever 'number' starts out as, if I press the reset button, the sketch should print one greater than that last time. That simply doesn't happen for me... the same number (usually zero) is printed over and over. I can't easily post a whole sketch in a comment, but am I doing something wrong? Or is "noinit" lying?

@Randy: Works for me on an Uno. Presumably the bootloader of the Nano uses more RAM than the Uno's optiboot. In my test, number was stored at 0x01c3, past the Serial object, its vtable, its buffers, and the core's timekeeping variables. You will have to experiment to know what addresses your bootloader overwrites.

@EdgarBone Thanks... you've confirmed what I've been suspecting, which is that the boot loader code in my nanos is not up to date. I see a lot of folks re-programming NANOs with the OPTI-BOOT, which is for the UNO, but you can use it with the NANO, and use a define to make sure all the upper analog input pins are configured. I have to either build or buy a programmer. easy to build, but they are so cheap. I'll bet the code works on my NANO with a more up to date bootloader. Thanks again.

You can check the MCUSR register to see the cause of the reset. In your case you could use:
if( bit_is_set(MCUSR, EXTRF) )// reset button was pressed
{
    MCUSR = 0;// clear the reset-flag

    // "magic" routine here

}

Thanks. I understand this, but I don't care what caused the reset.

Are you kidding me. You specifically said reset and “NOT by loss of power”. Well; now I don’t care anymore

I think its obvious what i meant: I wanted it to WORK when a RESET occurs, but I don't expect it work if there is a loss of power.

It was so obvious that you have two people giving you an answer to the wrong interpretation of that part of the question!

If you use the latest version (7.0, July 2018) of Optiboot, you can use the MCUSR register to check the reset cause.
You need to use the latest version because previous versions of the bootloader cleared the MCUSR before starting the sketch (as recommended in §15.9.1 of the ATmega328P datasheet). This was changed in version 7.0 (a50f47b).
#include <EEPROM.h>

static uint8_t ch = MCUSR;

void setup() {
  MCUSR = 0;
  uint8_t n = EEPROM.read(0);
  Serial.begin(115200);
  Serial.print(n);
  if ((_BV(PORF) & ch) == 0) // not a power on reset
    magic(n);
}

void loop() { }

void magic(uint8_t &number) {
   EEPROM.put(0, ++number);
}

Thats interesting, but I've seen this before, and I don't really care what caused the reset. what I do want, and hope I explained, is for the routine I called magic() to run when a reset occurs, before any new sketch code is loaded, or before any pre-C cleanup or initialization of memory/variables occur.

@Randy You specifically asked: "I'm talking about a reset caused by pressing the reset button, uploading code, opening a serial port, or any reset that was NOT caused by a loss of power." What is the reason you need it to happen before the C initializations?

I'll answer, but I don't want to side track too much into why. In a complex system, I usually put everything important into a structure (states, timers, etc.), and save it all to EEprom before turning it off. The 1st thing the code does when it starts is read the struct back out of EEprom, so it can resume in the exact same state. It would be nice if uploading a code change could first trigger my save routine too. I can find a way to do the save manually first, but it would be nice to automate it. Sadly, nothing I've tried has worked. Not even the .init sections.

@Randy That doesn't make any sense to me: when the upload is started, the MCU resets, so your configuration (states, timers) are reset and lost.

Again, the ultimate goal is to save date to EEPROM. I can assure you that saving a structure, containing all your states and timers to EEPROM, does provide a solid and reliable recovery to exactly where your program "left off", if the first thing you do is recover your structure from the EEprom where you saved to.

@Randy Yes, of course, but it doesn't matter when you read back the EEPROM config, you could do it in the setup. But if you want to save the current, unsaved state before updating, you cannot do that after a reset.

apparently not, but if there were a way to steal the RESET vector as I'd hoped, it definitely would be possible to save data to EEPROM on RESET, as long as it wasn't a power up reset.


text:
Is AREF a stable output Ref voltage with analogReference(INTERNAL)
I'm using an analog input on a NANO board to measure the midpoint between two photo resistive (Cadmium) cells, with the two outside ends tied to GND and a source voltage. Basically a simple voltage divider. So it almost wouldn't matter what reference voltage I used in a case like that, as long as the AnalogReference() was correctly set corresponding to the reference voltage, AND the load did not pull down that voltage.
Well if I used the 5V for my source, and set AnalogReference(DEFAULT), then assuming a worst case load of 4K-ohm, the total load on the 5V regulator is still only 1.25mA. But even so, I figured I could minimize the system load even more by setting AnalogReference(INTERNAL), and using the VREF pin as a source for my voltage divider.
Well it seems to work fine, but I don't know that I've seen any actual examples of what I'm doing, which is using the AREF pin as a source output voltage for my voltage divider. Using vREF as a source, a 4K load would only draw 27.5 microamps with a 1.1V source. But I can't find any spec for the max current I should avoid exceeding, That has me worried maybe I'm not even supposed to be doing that!
So is it acceptable to use the VREF pin as an output for light loads, when using the INTERNAL AnalogReference?
Thoughts?
EDIT: After receiving a "no" answer yesterday, I did some bench checking. I configured my NANO board for Internal, and connected a fully open 100K linear pot from AREF to Ground, with a DVM in parallel. The AREF terminal output was about 1.076, with or without the 100K load. Not quite the 1.1 specified but close enough. I then slowly rotated the pot to increase load. At just under 9K the voltage dropped a somewhat insignificant amount, to 1.075. From there on there were additional small decreases, down to about 1K, at which point i measured about 1.062V. Below 1K, there was a very steep decrease.
Note that this was a "quickie" test, done while powering the NANO from a USB port. However, repeating the test with 12V on the DV input did not alter the results significantly.
Even considering the USB source, from this test I conclude:
1) There does appear to be some buffering on the VREF output. It certainly did not behave as there was a simple case of a 1.1V source in series with a high impedance.
2) Up to a load of 10K, the VREF output seems at least as stable as the 5.0V regulator output.
3) Since a 1.062 drop from an initial no-load voltage of 1.076 equates to less than a 2% difference, I have to conclude that a load on VREF (to ground) greater than 1K (lets say 2K for margin) makes VREF probably useful in cases like i described, with a worst case load of 4K.
4) I repeated my test with a second NANO board. This time the initial no-load voltage was salightly higher, 1.084. However, the response to increasing load and the K point where the slope changed dramatically were unchanged.
Again, this is an arduino NANO board, and probably a clone. Can anyone else verify or disprove my results? I'm sure someone else will need to consider using VREF as I did, and it would be good to know.

No, it is not acceptable.
The datasheet states:

AVCC is connected to the ADC through a passive switch. The internal 1.1V reference is generated from the internal bandgap reference (VBG) through an internal amplifier. In either case, the external AREF pin is directly connected to the ADC, and the reference voltage can be made more immune to noise by connecting a capacitor between the AREF pin and ground. VREF can also be measured at the AREF pin with a high impedance voltmeter. Note that VREF is a high impedance source, and only a capacitive load should be connected in a system.

The 1.1V reference is only presented on the AREF pin for the purpose of adding an external bypass capacitor, or for measuring it using a very high impedance meter. Any load applied to the pin will cause the reference voltage to droop.
While it may work in certain circumstances it's certainly not recommended. If you want to use it externally you should buffer it through a high-impedance unity-gain voltage follower:

simulate this circuit – Schematic created using CircuitLab

Hmm! OK that's good information! I've been doing it wrong, though it "worked", I suppose it only did so because for a voltage divider it did not matter as much as it otherwise might have! I'll have to re-think my circuit a little bit though. Since I just need an ADC count representative of the voltage divider, it looks like I'd do better to simply use the DEFAULT and work with the 5V terminal for my reference!

Please see my edit. At least based on my bench test, it seems that using the AREF pin to power a low load voltage divider works, within the constraints I documented

It may work, but it's not what it's designed for. My car works when I drive it off a cliff. It's not designed for that though, and I doubt the long-term outcome would be good.  If you want to use it externally you should buffer it through a high impedance unity-gain voltage follower.

I note that you quoted the spec as saying AREF should only be measured with a high impedance voltmeter. But did YOU add the phrase "Note that VREF is a high impedance source, and only a capacitive load should be connected in a system."?
Your car analogy is  poor one. I've been doing what I came for confirmation on for a few years now with no trouble, and it was the lack of examples that made me second guess. I guarantee if you drive your car off a cliff and measure the results, they won't lead you to the reasonable question I raised.

Also I'll point out that a unity gain buffer done with a TL081 (not exactly a "rail-to rail" spec OPAMP) will also start to droop beyond a 1k load. But based on my bench test, I'd not be surprised if I found there already was such a buffer internal to the ATmega328. I don't have the internals, but based on my measurements, there must be some kind of buffer there already.

The tl081 is just what the schematic editor dumps in by default. Select suitable components for your application. Everything I stated is direct from the datasheet. If you think it is wrong then take it up with microchip.

Good point! I will write to them and include my findings!

Now, having had the benefit of a support ticket and subsequent discussion with an engineer at TI on this subject, I can confidently offer a qualified YES to my own question. It turns out my case is probably the only one that would be within those qualifications.

In the case where the RATIO between two hi-resistances is the ONLY thing needed from an A/D measurement, it is acceptable to use AREF and GND for the applied voltage, provided the load is low (see item 2). The main reason is that any droop in the AREF caused by the added load would not affect the ratio.
The use of AREF for such a situation should still ensure limiting any load on the AREF pin to about 91uA. For the 1.1V (INTERNAL) source selection, that equates to about a 12K load. The number is based on a reverse calculation that would cause a 1 LSB difference in analog readings, IF other analog inputs are expected to be used for other non ratio-metric measurements.
Using the AREF pin this way makes it even more important to add a capacitor from the pin to GND.
Apparently there is no danger of harming the chip in any way, should the AREF pin become shorted.

I will comment that the engineer responding to my support ticket understood I was trying to avoid a PCB change, but recommended a different approach if I had occasion to make other board changes anyway. His recommendation was to use the EXTERNAL Analog reference option, using the available 3.3V pin for AREF voltage, and using a digital output to supply my voltage divider. The idea here is that I would still have the benefit of short circuit protection, and since I was concerned about power saving, I could switch the Digital output pin to a low state until readings needed to be taken, observing sensible delay for settling time.
A good suggestion indeed, but my reason for answering my own question here is because under the constraints given, using AREF as described in my OP is acceptable, will not affect the ratio measurement, and could not harm the chip.


text:
Arduino Uno - Firmata/Serial Communication in Visual Studio C++
I need to pass std::vector <double> values from a C++ console program (written in Visual Studio 2015) running on a PC to Arduino in real-time using USB serial communication. Can anyone of you give any advice on how to implement Firmata or something similar into a C++ console application?
I googled everywhere and could not find a decent example for C++. Almost everything can be computed in console app, Arduino needs to work only with LCD display and beside that it can have StandardFirmata uploaded.

If you are willing to use python to write a simple scripts you can use Telemetry (See on github) to exchange the data to Pytelemetry. Using a technique called indexing you can send arrays and sparse arrays. The C implementation of the protocol doesn't support it out of the box but it's 2 lines of code to add to your embedded application. Let me know (I am the author)

Do you have an upst date on this issue?  I looking to compile the FIrmata test app in VIsual Studio 2017 in C++

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


text:
Serial: What is different between Gammon's RS485 (blocking) and RS485 "non blocking" libraries?
The RS485 master-slave communication library on Nick Gammon's page http://www.gammon.com.au/Arduino/RS485_protocol.zip is working for me OK, but on the same hardware wiring is not working for the non-blocking library http://www.gammon.com.au/Arduino/RS485_non_blocking.zip.
I can not find information about the connection of MAX485 on Arduino for non-block version. Is MAX485/RS485 from HW serial (ie Rx=0 and Tx=1)?
If so, how can a slave on the same line at the same time receive from master the message "hello world" and print it to the serial monitor?
Thank you for the explanation.
When I added the SoftwareSerial library into Nick's example for non-blocking, so it works, but is it still a non-blocking?
//Master:
#include <RS485_non_blocking.h>
#include <SoftwareSerial.h>
const byte ENABLE_PIN = 4;
SoftwareSerial mySerial(2,3); //RX = 2 TX = 3

size_t fWrite (const byte what) {
  return mySerial.write (what);
}

RS485 myChannel (NULL, NULL, fWrite, 0);

void setup () {
  Serial.begin (9600);
  mySerial.begin (28800);
  myChannel.begin ();

  pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
}  // end of setup

const byte msg [] = "Hello world";

void loop () {
  digitalWrite (ENABLE_PIN, HIGH);  // enable sending
  myChannel.sendMsg (msg, sizeof (msg));
  digitalWrite (ENABLE_PIN, LOW);  // disable sending
  delay (1000);
}  // end of loop

//Slave:
#include <RS485_non_blocking.h>
#include <SoftwareSerial.h>
const byte ENABLE_PIN = 4;
SoftwareSerial mySerial(2,3); //RX = 2 TX = 3

int fAvailable () {
  return mySerial.available ();
}

int fRead() {
  return mySerial.read ();
}

RS485 myChannel (fRead, fAvailable, NULL, 20);

void setup() {
  Serial.begin(9600);
  mySerial.begin(28800);
  myChannel.begin();
  pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
}  // end of setup

void loop() {
  if (myChannel.update()) {
    Serial.write (myChannel.getData(), myChannel.getLength());
    Serial.println();
  }
}  // end of loop

Regards, Vava
(Sorry for my English... :-)

While tangential to your question, you should verity that the sendMsg() method blocks until the message has been fully emitted (and not merely hardware or software buffered), as if it does not your immediate disabling of the transmit enable pin after that call will truncate your message.

Reference page: http://www.gammon.com.au/forum/?id=11428

The blocking library is intended where you want to wait for incoming data, and are prepared to do nothing else while it arrives. There is also a timeout parameter which lets the code proceed if nothing happens for a specified number of milliseconds.
The non-blocking library is intended for where you need to do other things (like control motors, or read switches) at the same time you are receiving data. For that situation you call an update function periodically which assembles the incoming packet, byte-by-byte if necessary.
When the data is fully received the update returns true, and you can process the packet.

If so, how can a slave on the same line at the same time receive from master the message "hello world" and print it to the serial monitor?

As I stated above in neither case do you receive and print "at the same time", however the non-blocking one does not simply wait until all the data has arrived.

Example code from the linked page:
void loop ()
  {
  if (myChannel.update ())  // returns true when packet fully received
    {
    Serial.write (myChannel.getData (), myChannel.getLength ());
    Serial.println ();
    }

  // do other things while waiting

  }  // end of loop

If in example for non-blocking libraries is the same wiring as in the example of blocking library, where is (in non-blocking example) definition of RX(=2) and TX(=3) pins?

The hardware is the same.

there is limitation for use - only pins which supports change interrupts.

Of course. If the underlying protocol is SoftwareSerial then the usual limitations apply (that is for the Rx pin).

Thank You for the explanation. Let me have a 2 small supplementary questions - 1) If in example for non-blocking libraries is the same wiring as in the example of blocking library, where is (in non-blocking example) definition of RX(=2) and TX(=3) pins? 2) In description of SoftwareSerial (https://www.arduino.cc/en/Reference/SoftwareSerial), there is limitation for use - only pins which supports change interrupts. Is the same limitation for RS485 non-blocking library ?

See amended reply.

The hardware connection should be the same, as blocking vs non-blocking is referring to how you handle the incoming data packets.
Don't quote me on this, but generally, blocking vs non-blocking refers to the use of delay() or similar, which will block anything else from running while that function is being executed.

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


text:
Servomotor AND Button
I am having trouble trying to make servomotor and button work together. The button code here below works fine when alone in a separate code but when it is transferred to the code with the servomotor function in it, it doesn't work.
Is there anything I need to be wary of when integrating the button code here to the preexisting code?
#include <Servo.h> // Library required for the servomotor (Make sure to download)
#include <Button.h> // Library required for the microswitch (Make sure to download)

// Parameters for the experiment
// Note: 1000 is one second
char Experiment = 'Acclimatization';
char Bird_Name = 'birdname here';
int Frequency = 30 * 1000; // The motor moves every x seconds
int Frequency_Deviation = 5 * 1000; // There are x second deviations plus and minus from the frequency set above
int Duration = 3 * 1000;  // The food is uncovered for x seconds

int servoPin = 9; // Declare the servomotor pin (Can be varied from setup to setup)
Button button(7); // Declare the microswitch pin (Can be varied from setup to setup)

Servo Servo1;

void setup() {
   Servo1.attach(servoPin);
   //analogWrite(servoPin, 0);
   Serial.begin(9600);
   button.setDebounceTime(100); // set debounce time to 100 milliseconds
}

void loop(){
   // Get onset and offset times of when the bird arrives and leaves the perch
   button.loop();
   if(button.isPressed())
    Serial.println("OnsetTime");
   if(button.isReleased())
    Serial.println("OffsetTime");

   // Calculate the acclimatization parameters below
   delay(random(Frequency-Frequency_Deviation,Frequency+Frequency_Deviation)); // Calculates frequency (See paramaters above)
   Servo1.write(0); // Starts from 0 degrees
   delay(Duration); // Duration that the food is uncovered (See parameters above)
   Servo1.write(75); // Goes to the x degrees
}

In your code, you used delay() function two times. This may make Arduino miss some pressing event. Use timestamp instead of delay. See BlinkWithoutDelay example  to see how to use timestamp.
Please note that debouncing function of library does NOT use delay() function. Therefore, you do NOT need to worry about blocking issue

Short answer: You have a blocking delay interrupting your button debounce time of 100ms.
Your button library has a debounce time of 100ms. This means you must be holding the button down for more that 100ms before it will register as pressed.
You have a 3 second blocking delay at the end of your loop. When you call delay(XX), your processor cannot do anything during this time (like check for a button), it's just waiting.
Think about how the code is running. In your main loop, you are calling the function button.loop(), and it's checking to see if your button is pressed. If it's pressed, it's starts a timer (your debounce). The goal of this timer is for another 100ms to pass by with your button still being pressed to make sure you actually pressed it. Button.isPressed() fails, and it moves to its next set of instructions, which is move the servo and wait 3 seconds, during which time it cannot check the button. Then it starts all over again, and it calls button.loop() again. This all happens MUCH faster than 100ms. From the start of void loop() to the time it takes for it to wind back up at the 3 second blocking delay is in the nano seconds. This never gives your button library the 100ms of "pressed down" button it needs for button.isPressed() to return true.
I suggest spending some time looking at the behind the scenes of your button library and see how the debounce works. You can do that, or you can use the example debounce sketch off the main arduino website and learn how that works. The next thing you'd want to do is to learn how to make your code "wait" without using the blocking call delay(). This is done by using timers with millis(). A good way to learn this is the example arduino sketch "Blink Without Delay".
Hope that clears some things up.

Thank you for the feedback. What if I need the day function though? Can I still make the button work while using the delay duration of 3 seconds for example?

@John "This is done by using timers with millis()."

@HavocRC, That library does NOT block in debounce time. The library uses timestamp for debouncing. It does NOT use delay() function. Please read the library reference before anwsering

@John like I said you can get your code to work exactly how you want it to, but you need to use slightly more complicated code. I'm pointing you in the right direction in my answer, if you study and use those two sketches I suggested, you'll have all the knowledge you'll need to accomplish what you wish.

@RozonaZoro I didn't say there was a delay in the debounce library I'm talking about the 3 second delay in the OP's sketch (3rd line from the bottom).


text:
Lolin NodeMCU V3 and 5V sensors
I am new to Arduino and electronics so please correct me if I made a mistake.
Many sensors and actuators require 5V. The Lolin NodeMCU V3 has outputs of 3.3V. I want to have them working together.
I have read that the VIN pin outputs the voltage of the USB power source, which is around 5V. I bet that many sensors and actuators can be connected to VIN.
I guess that the main difference with the VCC pin of other boards is the accuracy and stability of the potential.
1) What about the amperage? (I guess that the max amperage of the USB power supply is divided between the board and sensors/actuators connected). How does it compare with the VCC output of, let say, an Arduino UNO?
2) How important is in most practical cases not having exactly 5V? (clearly, I am not considering using the sensors for extremely accurate measurements). I am interested in things like movements/distance/light/accelerometers/humidity etc. sensors and LCD displays, relays, small motors, etc..
I have seen that many sensors have a not so narrow range of working voltages. That makes me think that small oscillations in the USB voltage may not be significant.
3) Is there a better yet simple way to connect 5V devices to this board?
Thank you in advance.

I fear you lost your bet. ;-) As the name VIN suggests the Vin pin is used to supply your nodemcu with an external power (up to 20V). That's if you do not want to connect the USB port, or need more power than your USB supply can handle. There is a VU pin that provides the power 5V from the USB connection. See the following link for more details: http://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/ It would be more practicable, if you power the sensors and use that power also for the nodemcu.

Also, be careful if you connect 5V sensor pins with the 3.3 V nodemcu pin (IO pins). That could (sorry would) kill your nodemcu.The maximal current you can draw from the nodemcu power pins is defined by the voltage regulator (~ 800 mA) and the capabilities of your power supply (which we do not know).  That is valid for the USB port and VU pin too.

nodemcu's vin is more like 4.4v than 5.0v. the nodemcu's IO is generally 4.4v tolerant. i use lots of 5v sensors with mine just fine, running at 3.3v or 4.4v. if in doubt you can level shift, but i've only had to do that once (of dozens+dozens) fwiw.

@PeterPaulKiefer, Thank you!

@dandavis, Do you connect your sensors to VIN? The Peter's comments seems to suggest connect them to VU

i've not seen a nodemcu with a "VU" pin. not saying they don't exist, but indeed all the ones on amazon seem to mark that slot "RSV". if your board has it, and you don't need the inline diode, then go for it.

@dandavis The OP told us about a Lolin NodeMCU. I have some of them at home. I confess I'm careless like you and often thought "Can 1 and a halve Volt make a difference" Unfortunately I had not the luck you had and grilled two of my little friends. I know, I will be careless in the future too, but here on SE I can not give an advice, that probably kill the MCUs.

@user1420303 Sorry I might not be exact/clear enough. I don't advised you to use the VU pin ( that can also have different names ). I just mentioned it, as the pin where you have access to the USB power.  My advice would be use an external 5 Volt power supply to power the sensors and the NodeMCU with it. To power the MCU use the Vin pin.  In case you want to drive motors or servos or power LEDs, it's even better to use separate power supplies for them. My PC has USB ports that can only drive 500mA. That wouldn't be enough to drive the NodeMCU and a couple of motors.

You've mentioned projects that use the Vin Pin to access the 5Volt line of the MCU. I don't know what projects you've seen. But the ones I know have routing nets that are named "5V", that are connected to the Vin pin and the sensors VCC pins. But they are also connected to a e.g 7805 Regulator or a LM317 or some more efficient ones. So effectively they power the NodeMCU and the Sensors with that external supply. (As I advised you in the last comment.)

What about the amperage? (I guess that the max amperage of the USB power supply is divided between the board and sensors/actuators connected). How does it compare with the VCC output of, let say, an Arduino UNO?

The 5V pin is connected directly to the 5V of the USB. Whatever your USB port can provide the 5V can provide, minus the current used by the ESP8266.

How important is in most practical cases not having exactly 5V? (clearly, I am not considering using the sensors for extremely accurate measurements). I am interested in things like movements/distance/light/accelerometers/humidity etc. sensors and LCD displays, relays, small motors, etc..

That all depends on the device. Read the datasheet. Look at the Electrical Characteristics. It will tell you the recommended (and the absolute maximum) voltage range.

Is there a better yet simple way to connect 5V devices to this board?

Again, it all depends on the devices. Many many devices that are marketed as 5V are in fact "anything from 2.8V to 5.5V" or something like that. Read the datasheets!
The NodeMCU is a tricky board to use with 5V because there is no isolation between the USB power and the 5V pin's power. You can't power the board through the 5V pin and still be able to use the USB port or you risk destroying the USB port or computer that the NodeMCU is plugged into.  If possible you really want to be running as many 3.3V devices as you can, or to keep any external 5V supplies completely separate (except ground, of course) from the 5V of the NodeMCU.

the 5v pin isn't directly connect to usb, it's a misnomer; there's a diode in series. a rather measly current capability diode too, imho, which makes it tougher to run 5V RGB LED strips...

@dandavis Not according to the schematic I saw. The diode was between both the USB and the 5V pin and the input to the regulator.

On my amica boards I see ~4.5 volts, and can pull up to half an amp or so. on my lolin boards, the voltage is actually somewhere under VCC: I can't power anything from it, not even a DHT-11. I suppose there may be several designs being sold as "nodemcu" though, so we could all be right.

@dandavis There is a lot of Chinese crap out there now with zero documentation, yes.

nodemcu gives 3.3 V output voltage. This output voltage is not considered sufficient by many components. So my recommendation is logic converters. The most logical solution to convert 3.3V voltage to 5V. Thus, the elements used with 5V will work stably.


text:
Avoiding float math to speed up arduino
I read and heard that the floating point math is much slower than int math.
And I saw a converting process in here floath math to integer math
So I want to to convert my floating math calculations to integer math.
Here is the code that include floating math:
float sensval, lpf, lps;
float sensinitial; // used to store the initial sensor data
float x, y, z;
int heigh;
int dA;

void setup() {

  runSensor();
  sensval = readSensorData();
  sensinitial = sensval; // Setting the initial data
  lpf = lps = sensval;
}

void loop() {
  sensval =  readSensorData();
  heigh = (float)44330 * (1 - pow(((float) sensval/sensinitial), 0.190295));
  lpf = lpf + (sensval - lpf) * 0.1;
  lps = lps+ (sensval - lps) * 0.05;
  x = (lps - lpf) * 50;
  y = x+ (z - y) * 0.1;
  z = constrain(y, -500, 500);
  dA += z * 100 + 2000;
}

readSensorData(); returns 7 decimals maximum(752.4543 for example)
There is pow calculation too.
So how can I convert floath math to int math?
Any optimization code are welcome.

The general idea is that you look at your calculations and decided how many binary places (binary equivalent of decimal places) you need in your calculations, or at different stages of the calculations, and do your calculations in an order and/or with a word length that will avoid overflows. You will be using integer data types thoughout your calculations, mentally keeping track of the binary point at each stage of the calculation. Search for Fixed Point Arithmetic to find a lot of information.

overflow is not problem, ı just want to convert my floating point calculations to integer calculations to speed up arduino little bit.

Have you actually noticed that it is running too slow? Don't try and optimize without a benchmark handy.

What you are asking for is not simple, especially since you have this
power function that can be hard to approximate.
First, you have to figure out the range and the required precision of
each of the floating point numbers you are manipulating. You wrote that
readSensorData() returns 7 decimals. If by that you mean that you
require a relative accuracy of 10−7, then I predict it will
be extremely hard to optimize this as a fixed point calculation. If
you can live with a much lower relative accuracy (say, around
10−3 or 10−4), then it may be worth trying
something.
I would start by writing the expression of height as
height = f(sensval/sensinitial-1)

where
f(x) = 44330 * (1 - pow(1+x, 0.190295))

I would expect sensval and sensinitial to be close to one another,
which would imply that x is small. At this point you should try to
estimate the likely range for x, because the feasibility of what
follows strongly depends on it. Next step is to approximate f() by a
polynomial. A simple Taylor
expansion gives:
f(x) ≈ -x*(8435.78-x*(3415.25-x*2060.2))

You may start by trying this, just to see if it looks kind of OK or
completely hopeless. You will notice that the above approximation is
great when |x| is tiny, but it very quickly degrades as |x|
increases. This is why you don't use Taylor expansions in real
approximations, I showed it to you only to give you an idea of the
feasibility of a polynomial approximation.
To do better than Taylor, you must specify the range of x, then you
can scale that range to [−1, 1] and expand on the basis of the
Chebyshev
polynomials. And
then you could fine-tune to get the optimal
polynomial, but
it's likely to be only marginally better than the Chebyshev expansion.
If all this works with a reasonable polynomial degree (say, no more than
5), then you can start converting to integer math. If it doesn't, you
may try a different type of approximation, like interpolating over
tabulated values. If the problem is the range of x being too large,
you may instead write the power function as
ab = 2b × log2a
and write polynomial approximations to the base-2 exponential and
logarithm (the polynomials only needs to cover one octave). If you try a
rational fraction approximation, beware that divisions are slow on the
AVR platform.
If all the above looks like too complex, or too much work, then just get
a faster CPU, or try to live with your program being slow.

Since you are dealing with fractions, you can use fixed point arithmetic. For example, you can use unsigned short _Accum for readSensorData() if you only need 8 bits for the fraction part. http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1169.pdf tells you about fixed point types in c.


text:
is #ifdef __SD_H__ considered a bad practice?
Say I'm working on a library^1 to which I want to add support for SD.h^2 but knowing for a fact that many microcotrollers don't support SD.h (therefore they result in compilation errors [eg. Attiny85]) I don't want to just #include <SD.h> (or even #ifndef __SD_H__ then #include <SD.h>) in Mylibrary.h and make it totally unusable for some microcontrollers. So I was wondering, is it considered ok to just add the functionality like...
// Mylibrary.h

#ifdef __SD_H__
    // Save functionality for those including `SD.h` to their `sketch.ino`
    void Mylibrary::save(String filename){
        SD.open(filename, FILE_WRITE)
        // ...
    }
#endif

...without ever including the SD.h in Mylibrary.h and hence force the user whenever he\she wants to use some SD functionallity, to just include SD.h in his\her sketch.ino?  +(it sound exhausting to do something like this for every MCU, as an alternative way)
[1] (in my case this library)[2] (in my case  something related to this)PS. The reason I'm asking is because I don't remember seeing it anywhere being used that way and I'm slightly confused as to if this is the right or wrong thing to do so

Chat-GPT says it's reasonable, but I really want to know your thoughts about how would you approach such an issue

Do not trust ChatGPT, always assume it is hallucinating.

It is bad and I have seen it :)

Note that identifiers that start with two underscores (or one underscore and a capital letter) are reserved: "All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use."

Since you asked ChatGPT, I asked it as well: "in C++ is it good practice to put all of your code in a .h file?" And the answer was: "No, it is not considered good practice to put all of your code in a .h (header) file in C++. In C++, code is typically organized into header files and source files, and there are specific conventions for what should go in each type of file."  So no, putting all your code (declarations and definitions, that is, function prototypes and implementations) is not considered good practice. You can search other parts of the Internet for other opinions on that.

@NickGammon, When I started building this library, there wasn't ChatGPT available. Based on my research (and sure also empirically) that's what I found out that it was working. Also, I once had them seperate I later decided that I had to merge them into the .h for the sake of better MACRO optimization

Yes, it is in general a bad practice to use include guard define to detect if the header file is included. It will work only in a header file in a compilation unit which includes the detected header file.
In Arduino all ino files of the sketch are one compilation unit. But every C or C++ file is a separate compilations unit. They would not 'see' the include guard from an include in the ino file(s).
If you want to use the include guard define, don't relay on it exclusively. Use your own define and set it if you detect the include guard. This way user can set it if theirs SD library has a different name for the include guard.
#ifdef __SD_H__
#define XY_USE_SD_LIB
#endif

#ifdef XY_USE_SD_LIB
    // Save functionality for those including `SD.h` to their `sketch.ino`
    void Mylibrary::save(String filename){
        SD.open(filename, FILE_WRITE)
        // ...
    }
#endif

I use this in my popular ArduinoOTA library here.
There is other way to detect includes and it works across compilation units, but it doesn't work on all Arduino platforms. It is the __has_include 'directive'. I use it here.

That's so cool! clever one! It's exactly what i was looking for! Thanks!

you are fast :-). please read the last paragraph for an alternative

That's so interesting I didn't know about __has_include

I don't think this will work, however you could try it and see. Just set the board type to something that doesn't support SD.h.
My problem would be that your library is a separate compilation unit (ie. file) that would be compiled against the things you put as header files.
If your library user uses SD.h in the main .ino file, then your library (which is compiled separately) would not know about that. In other words, it wouldn't know whether or not to implement the Mylibrary::save function.
I think a fairly simple solution would be to put a define in the include file for your library, eg.
#define USE_FILE_SAVING false

Then check that in your code. You don't need a whole list of MCUs, just inform the user that if they want file saving implemented to change that one line.

For more information see How the IDE organizes things

Thanks! it's really interesting though, I also just realised that it depened if it works or not based on which board i select (eg. on arduino uno works, with espressif's ESP32 it doesn't consider that SD.h is already defined)

Wait It's so weird, it copiles just fine on both boards but with ESP32 the #ifdef __SD_H__ #pragma message("YES SD.h") #else #pragma message("NO SD.h") #endif  says "No ..."

Adding SD.h to your main project is not  going to affect how your library compiles. That is a separate compilation unit and does not look at what includes you have in your .ino file. See: https://arduino.stackexchange.com/a/13182/10794

It actually does effect in some cases (eg. with Arduino UNO)

@GiorgosXou This isn't a library, though, right? Of course it affects a compilation unit. You are showing in that GIF that putting the include inside a file in a compilation unit (that is, the file we are looking at) will of course affect how that file is compiled. But if you put that include in file A it won't affect  how file B (your library) is compiled.

Your library is compiled separately (in another compilation) from your .INO file. The library cannot know what includes you may or may not have put in your .INO file.

My whole library is in the .h file. There are no seperate cpp files, I just organise each class implementation with #pragma region file.cpp inside the .h (for the exact reason of extreme macro optimization)

"The library cannot know what includes you may or may not have put in your .INO file." in many cases like #ifdef __SD_H__ it knows, in other cases like @juraj said you have to use __has_include like #if defined __has_include #if __has_include(<SD.h>) #include <SD.h> .... But from what I understand, you shouldn't 100% only depend on those

OK, so the whole library is in a .h file? Then rather than asking whether it will work or not (which you can find out for yourself empirically) how about telling us whether or not it works, and if not, ask us why not?

I thought I made it clear, I even had a comment // Mylibrary.h on my code snippet. I didn't ask "whether it will work or not", I asked  "how would you approach such an issue" because empirically, I know I make mistakes...


text:
Arduino with LCD Display does not reset/restart/start on connection to power
A friend and I have been working on an Arduino Sketch that does a request to a local API, parses that data and prints it out on an LCD Display.
When we upload the sketch to the Arduino it does exaclty what it should and shows the following on the LCD Display:

But when we disconnect the Arduino from the PC and reconnect it to the PC (or to any other power source), the following shows up on the LCD:

It seems as if the Arduino simply does not restart the Sketch and stays idle, while giving the LCD a weird output. When we open the Serial Monitor, in the Arduino IDE, the Arduino reboots and the correct information shows up again. Pressing the reset button on the Arduino itself did not work and seems to do nothing.
When trying other examples (e.g. Blink) it does restart on reconnecting to the PC, so it seems that the problem lies with our code.
Here is our full code:
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoJson.h> // Library to deserialize JSON
#include <Wire.h> // Library for I2C communication
#include <LiquidCrystal_I2C.h> // Library for LCD

LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4);

char ssid[] = "WifiSSID";
char pass[] = "WifiPassword";
bool reading = false;

int refreshRate = 5000;

int status = WL_IDLE_STATUS;
IPAddress server(192,168,1,201);

WiFiClient client;

char json[512];
StaticJsonDocument<512> doc;

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

  memset(json, 0, sizeof json);

  lcd.init();
  lcd.backlight();

  lcd.setCursor(4, 1);
  lcd.print("CONNECTING..");
  status = WiFi.begin(ssid, pass);

  if (status != WL_CONNECTED) {
    while(status != WL_CONNECTED) {
      Serial.println("Retrying connection in two seconds...");
      delay(2000);
      status = WiFi.begin(ssid, pass);
    }
  }
  else {
    lcd.setCursor(0, 1);
    lcd.print("                    ");

    Serial.println("Connected to wifi");
    Serial.println("\nStarting connection...");
    sendRequest();
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    if (c == '[') {
      reading = true;
      memset(json, 0, sizeof json);
    } else if (c == ']') {
      reading = false;
      printJson();
    } else if (reading) {
      int len = strlen(json);
      json[len] = c;
      json[len+1] = '\0';
    }
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    client.stop();
    delay(refreshRate);
    sendRequest();
  }
}

void sendRequest() {
  if (client.connect(server, 80)) {
      Serial.println("Connected to server. Requesting data...");
      client.println("GET /api/v1/smartmeter?json=object&limit=1&round=on HTTP/1.0");
      client.println();
    }
}

void printJson() {
  DeserializationError error = deserializeJson(doc, json);

  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.f_str());
    return;
  }

  int energy = doc["CONSUMPTION_W"];
  float gas = doc["CONSUMPTION_GAS_M3"];
  Serial.println(json);
  Serial.println(energy);
  Serial.println(gas);

  lcd.setCursor(0, 0);
  lcd.print("CONSUMPTION ENERGY:");
  lcd.setCursor(0, 1);
  lcd.print(energy);
  lcd.setCursor(8, 1);
  lcd.print("WATT");

  lcd.setCursor(0, 2);
  lcd.print("CONSUMPTION GAS:");
  lcd.setCursor(0, 3);
  lcd.print(gas);
  lcd.setCursor(8, 3);
  lcd.print("M3");
}

Would any of you maybe know why the Arduino refuses to restart on reconnecting to the PC or a power source, and how to fix it?
Thanks in advance!

You've tagged the question with both nano and arduino-nano-33-iot, but I'm guessing between the two you're using the latter, because on Arduinos with native USB (not a plain Arduino Nano) while (!Serial) continue; waits for a serial connection, e.g. Serial Monitor, to be connected.
This doesn't happen when you're on a power supply, or just connecting it to a machine without opening the port.
If you want blink an led inside this loop to see that it is in fact stuck there.

Hey mage! We removed the while (!Serial) continue; from the code and it works perfectly now! Thanks so much for the quick answer. Cheers!


text:
Anyone know why my pushbutton is always returning HIGH?
Been trying to figure this out for a couple hours, despite how ridiculously simple it should be. I have no idea why it's always returning 1, even when i'm pushing the button. Fritzing sketch:

My code:
#include <Servo.h>
#define button 3

Servo myservo1;
Servo myservo2;
Servo myservo3;

char incomingByte = "";
int timer;
int timer2;
int interval;
int numservo = 3;
int press1 = 90;
int letup = 0;
int val = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  myservo1.attach(9);
  myservo1.write(0);
  myservo2.attach(7);
  myservo2.write(0);
  myservo3.attach(5);
  myservo3.write(0);
  pinMode(button, INPUT_PULLUP);

}

void loop() {
  // put your main code here, to run repeatedly:

  val = digitalRead(button);
  Serial.println(val);

  //checkerthing();

    while (Serial.available() > 0) {
      incomingByte = Serial.read();
      timer  = incomingByte - '0';
      Serial.println(timer);
      timer2 = timer * 60;
      interval = timer2/numservo;

     motor1_control(press1, letup, interval);
     checkerthing();
     motor2control(press1, letup, interval);
     checkerthing();
     motor3control(press1, letup, interval);
     checkerthing();

     timer = 0;
     timer2 = 0;
     interval = 0;
    }

  }

void checkerthing() {
  val = digitalRead(button);
  if (val == LOW){
    Serial.println("Stopped");
    timer = 0;
    timer2 = 0;
    interval = 0;

  }
  if (val == HIGH){
    Serial.println("Still going");
  }

}
void motor1_control(int angle, int originalangle, int lengthoftime){
    myservo1.write(angle);
    delay(1000);
    myservo1.write(originalangle);
    delay(lengthoftime * 1000);

}

void motor2control(int angle, int originalangle, int lengthoftime){
    myservo1.write(angle);
    delay(1000);
    myservo1.write(originalangle);
    delay(lengthoftime * 1000);

}

void motor3control(int angle, int originalangle, int lengthoftime){
    myservo1.write(angle);
    delay(1000);
    myservo1.write(originalangle);
    delay(lengthoftime * 1000);

}

Basically, the point of this is to have the servo motors go off at specific intervals as given by the user in the serial monitor. The button exists so that the user can restart the timer at any point in the code. But the problem is, I can't even get it to register the button being pushed. It always returns "HIGH", which leads me to believe there's something wrong with the circuits. I've tried using some different methods, but no luck. Can anyone tell me what the issue here is?
Edit: ...I hadn't pushed the pushbutton all the way into the breadboard. I'm gonna go cry in the corner for a bit. And then get back to coding I guess lol. Thanks for the answers.

Is your breadboard one of the "split power rail" variety?

@Majenko no, it's a full power one

Well, if your real schematic is the same as the drawing then it should work.

Hade you checked you're using the correct terminals on the push button and it's making proper contact with the breadboard ?

What Bra1n said. I have to check those 4-lead pushbuttons every... single... time... because they're like Micro USB connectors; takes three tries to get the orientation right. Check continuity to make sure you're using the correct leads.

@Bra1n Oh god, I hadn't pushed the button in all the way. Ugh. Thank you.

@Crystal For those pushbuttons I flatten the leads; they ship with a "bump" which is great for PCBs, not so much for breadboards--squoosh 'em with pliers.

For people with trouble with those switches, I've seen it suggested to just always connect them by opposite (diagonal) corners.

@DaveNewton To be honest, all USB connectors have 3 sides...

you have INPUT_PULLUP so it should return HIGH if the button doesn't connect the pin to ground

You can try to ise a simple wire to pull the pin down to ground (connecting it to GND on the arduino board); if it works, then it's the wiring or the button, if it doesn't it's something else.

"I hadn't pushed the button in all the way." - You can write this as an answer and accept it. That will show that it has been solved, plus it will keep the question from being resurrected forEVER, waiting for an accepted answer that's never going to arrive.

https://meta.stackexchange.com/questions/116101/is-it-ok-to-add-solved-to-the-title-of-a-question

Hadn't pushed the button all the way in lol

it has happened to me. sometimes, I had forgotten to power on UNO or connect USB!!


text:
Designing around Output pin limitations
I'm new to Arduino and am working on a project with my son.  We are using the LillyPad USB board (schematic) to drive a bunch of LEDs (LED Datasheet).  Our project is based loosely off of the 'Turn Signal Biking Jacket'.
Our project calls for 7-11 LEDs in parallel on a single circuit.  In the 'Turn Signal' project the LEDs are driven off of a pair of output pins (1 HIGH and 1 LOW).  In a circuit that looks like this...

simulate this circuit – Schematic created using CircuitLab
Is this ideal?  Would it make more sense to connect the LED-chain to Vcc and have the return line connected to a single output set to LOW (to turn on the lights)?
If we were to have 3-4 of these LED-chains on at once, do I have to be concerned with total draw on the microcontroller?
Help? Thoughts?

Why are you using 2 digital pins for 1 output? Instead of writing LOW to one pin, you can wire the leds to GND directly, so that the current doesn't have to flow back into your digital pin hardware and you are saving an extra pin. (In his answer Majenko also wires them to GND)

@chrisl That was my thought as well.  That's how it is drawn up in the original 'Turn Signal' project.

If you know the forward voltage of the LEDs you can easily do some calculations.
For a typical red LED the forward voltage is around 2V.  Other colours vary.  So we can work out that, at 5V supply, each LED with its own 150R resistor, would take:
     V    5-2
I = --- = --- = 20mA
     R    150

With 11 LEDs in parallel on at once that would be 0.02 * 11 = 220mA.
That is far more than the 25mA an IO pin is able to supply, so you will damage the Arduino doing it like that.
Instead you will need to switch each chain of LEDs with a transistor of some form.  I'd choose a logic-level N-channel MOSFET as a "low-side" switch:

simulate this circuit – Schematic created using CircuitLab
Now your Arduino doesn't care about the current - all it sees is the MOSFET.
If your LED forward voltages are less than 2.5V you can also chain them together to halve the current:

simulate this circuit
Since the forward voltage is now double you use a smaller resistance to set the current (R=V/I, where V is 5-2Vf).

if I'm reading the datasheet correct, the forward voltage is 'typically' 3.3v 'max' 4.0v.  I'll add a link to my Question.  Also, Vbattery should be 3.7V as that's the output from the Lithium Battery.  And, I think, Vcc is 3.3v (I'll update the question with the datasheets)

So you won't be able to double them up then.

Using your math with the updated datasheet info (Vbatt = 3.7V, Vf = 3.3v), I get 3.7-3.3/150 = 3.33mA per LED.  Or 37mA for 11.  That is still more than the 25mA per pin.  How does the ~120Ohms of thread resistance figure in?  That would lower the voltage (slightly) and thus the voltage drop across the LED, right?

Yep. you would probably just get away with 11 LEDs. The absolute max for a Io pin is 40mA.

And if we keep the LED count to 9 we'd have a bit more room.  Thanks.

Yup. Or if you want more just split it between two pins as two separate chains.


text:
Changing outputs infinitely for no reason
Im a student and working on a arduino project for IoT competition and me and my team have built a house and I made this code below.
For some reason when I upload it to my Arduino MKR1000 it constantly turns D6 and D8 on and right after their both on it turns them off and so on for ever. I cant figure out why is it doing that because its only these 2 but not the rest of them.
Quick help would be appreciated.
Please note that I'm by any means a PRO at this but I do know my share about programming.
        //Definiramo ispis na serial port
#define BLYNK_PRINT Serial

//Ucitavamo biblioteke
#include <SPI.h>
#include <WiFi101.h>
#include <BlynkSimpleMKR1000.h>

// Autorizacijski kod za aplikaciju Blynk
char auth[] = "Token";

// Podatci za WiFi
char ssid[] = "SSID";
char pass[] = "PASSWORD";

// ----- Inicializacija ledica -----
const int ledBorDim = 2;
const int ledKuh = 6;
const int ledTrp = 7;
const int ledKup = 8;
const int lediceUlaz = 9;
const int ledSpav = 10;

// ----- Inicializacija gumbova -----
const int gumbKuh = 11;
const int gumbKup = 12;
const int gumbSpav = 13;
const int gumbBor = 14;

// ----- Kontrolne varijable -----
int stanjeLedKuh = 0;
int stanjeLedKup = 0;
int stanjeLedBor = 0;
int stanjeLedSpav = 0;

int gumbStanjeKuh = 0;
int gumbStanjeSpav = 0;
int gumbStanjeBor = 0;
int gumbStanjeKup = 0;

//Led kuhinja
BLYNK_WRITE(V3)
{
  int pinValue = param.asInt(); //Pinvalue postavljamo da bude vrijednost ono sto postavimo na aplikaciji
  Serial.print("ledKuh = "); //Ispis na ekran trenutno stanje
  Serial.println(pinValue);
  if (pinValue == 1)
  {
    digitalWrite(ledKuh, HIGH);
    stanjeLedKuh = 1;
  } if (pinValue == 0)
  {
    digitalWrite(ledKuh, LOW);
    stanjeLedKuh = 0;
  }
}

//Ledica za kupaonicu
BLYNK_WRITE(V5)
{
  int pinValue = param.asInt(); //Pinvalue postavljamo da bude vrijednost ono sto postavimo na aplikaciji
  Serial.print("ledKup = "); //Ispis na ekran trenutno stanje
  Serial.println(pinValue);
  if (pinValue == 1)
  {
    digitalWrite(ledKup, HIGH); //Promjena stanja na izlazu arduina
    stanjeLedKup = 1;
  } if (pinValue == 0)
  {
    digitalWrite(ledKup, LOW); //Promjena stanja na izlazu arduina
    stanjeLedKup = 0;
  }
}

//Paralelni spoj ledica na ulazu
BLYNK_WRITE(V6)
{
  int pinValue = param.asInt(); //Pinvalue postavljamo da bude vrijednost ono sto postavimo na aplikaciji
  Serial.print("lediceUlaz = "); //Ispis na ekran trenutno stanje
  Serial.println(pinValue);
  if (pinValue == 1)
  {
    digitalWrite(lediceUlaz, HIGH); //Promjena stanja na izlazu arduina
  } if (pinValue == 0)
  {
    digitalWrite(lediceUlaz, LOW); //Promjena stanja na izlazu arduina
  }
}

//Dimmer za Boravak
BLYNK_WRITE(V1)
{
  int pinValue = param.asInt(); //Ucitamo vrijednost
  Serial.print("Dimmer vrijednost: "); //Ispisemo na serial
  Serial.println(pinValue);
  analogWrite(ledBorDim, pinValue); //Na izlaz postavljamo vrijednost
  if (pinValue == 0)
  {
    Blynk.virtualWrite(V50, 1);
    stanjeLedBor = 0;
  } else if (pinValue > 0)
  {
    Blynk.virtualWrite(V50, 0);
    stanjeLedBor = 1;
  }
}

BLYNK_WRITE(V50)
{
  int pinValue = param.asInt();
  if (pinValue == 1)
  {
    analogWrite(ledBorDim, 255);
    Blynk.virtualWrite(V1, 255);
    stanjeLedBor = 1;
  } if (pinValue == 0)
  {
    digitalWrite(ledBorDim, LOW);
    Blynk.virtualWrite(V1, 0);
    stanjeLedBor = 0;
  }
}

void gumbKuhinja()
{
  gumbStanjeKuh = digitalRead(gumbKuh);
  if (gumbStanjeKuh == LOW)
  {
    if(stanjeLedKuh == 1)
    {
      digitalWrite(ledKuh, LOW);
      Blynk.virtualWrite(V3, 0);
      Serial.println("Ledica na V3/D6 je LOW");
      stanjeLedKuh = 0;

    } else if (stanjeLedKuh == 0)
    {
      digitalWrite(ledKuh, HIGH);
      Blynk.virtualWrite(V3, 1);
      Serial.println("Ledica na V3/D6 je HIGH");
      stanjeLedKuh = 1;

    }
    delay(500);
  }
}

void gumbKupaonica()
{
  gumbStanjeKup = digitalRead(gumbKup);
  if (gumbStanjeKup == LOW)
  {
    if(stanjeLedKup == 1)
    {
      digitalWrite(ledKup, LOW);
      Blynk.virtualWrite(V5, 0);
      Serial.println("Ledica na V5/D8 je LOW");
      stanjeLedKup = 0;

    } else if (stanjeLedKup == 0)
    {
      digitalWrite(ledKup, HIGH);
      Blynk.virtualWrite(V5, 1);
      Serial.println("Ledica na V5/D8 je HIGH");
      stanjeLedKup = 1;
    }
    delay(500);
  }
}

void gumbSpavaca()
{
  gumbStanjeSpav = digitalRead(gumbSpav);
  if (gumbStanjeSpav == LOW)
  {
    if(stanjeLedSpav == 1)
    {
      digitalWrite(ledSpav, LOW);
      Blynk.virtualWrite(V6, 0);
      Serial.println("Ledica na V6/D10 je LOW");
      stanjeLedSpav = 0;
    } else if (stanjeLedSpav == 0)
    {
      digitalWrite(ledSpav, HIGH);
      Blynk.virtualWrite(V6, 1);
      Serial.println("Ledica na V6/D10 je HIGH");
      stanjeLedSpav = 1;
    }
    delay(500);
  }
}

void gumbBoravak()
{
  gumbStanjeBor = digitalRead(gumbBor);
  if (gumbStanjeBor == LOW)
  {
    if(stanjeLedBor == 1)
    {
      analogWrite(ledBorDim, 0);
      Blynk.virtualWrite(V1, 0);
      Serial.println("Ledica na V1/D2 je 0");
      stanjeLedBor = 0;
    } else if (stanjeLedBor == 0)
    {
      analogWrite(ledBorDim, 255);
      Blynk.virtualWrite(V1, 1);
      Serial.println("Ledica na V1/D2 je 255");
      stanjeLedBor = 1;
    }
    delay(500);
  }
}

void setup()
{

  pinMode(ledBorDim, OUTPUT);
  pinMode(ledKuh, OUTPUT);
  pinMode(ledKup, OUTPUT);
  pinMode(lediceUlaz, OUTPUT);
  pinMode(ledSpav, OUTPUT);

  pinMode(gumbKuh, INPUT);
  pinMode(gumbKup, INPUT);
  pinMode(gumbSpav, INPUT);
  pinMode(gumbBor, INPUT);

  // Debug console
  Serial.begin(9600);
  //Povezivanje na WiFi i na aplikaciju Blynk
  Blynk.begin(auth, ssid, pass);
}

void loop()
{
  Blynk.run();
  gumbKuhinja();
  gumbKupaonica();
  gumbSpavaca();
  gumbBoravak();
}

Serial outpout:
Ledica na V6/D10 je HIGH
Ledica na V1/D2 je 255
Ledica na V6/D10 je LOW
Ledica na V1/D2 je 0
Ledica na V6/D10 je HIGH
Ledica na V1/D2 je 255
Ledica na V6/D10 je LOW
Ledica na V1/D2 je 0
Ledica na V6/D10 je HIGH
Ledica na V1/D2 je 255
Ledica na V6/D10 je LOW
Ledica na V1/D2 je 0
Ledica na V6/D10 je HIGH
Ledica na V1/D2 je 255

Little label reading D14 means that that pin isnt suppoast to go to D4 but to D14 of the MKR1000 but since i dont have that board in the program im stuck with arduino Uno.
Short explanation of the code...
We build a house out of styrofoam and placed 6 Led's around and almost all can be controlled from the Blynk app on my device. Also there are 4 buttons controlling 4 Led's. I have it setup so that when i press a button it changes the state of a particular LED and then sets the appropriate value on the app (If LED is on then set app value to 1). Pretty much that that about this code. Sorry if you cant understand but I had to write it in my native language since this is going to be a compettition and I was told that they wouldn't like if the code was in english for some reason.

pinMode(gumbKuh, INPUT); what's connected this pin, a button? with external pullup/pulldown? The repeadetly called function could flip the D6 pin in gumbKuhinja() when is D11 oscillating.. Do you also get any serial output when the pin toggles?

Let me upload a quick schematic so you could see better.

But yes it is a button.

Can you try changing all the pinMode(x, INPUT) lines to pinMode(x, INPUT_PULLUP) and change your program logic to "if the pin is LOW, the button is pressed and we must do something" (if it isn't already)? Without a pullup or pulldown on the buttons they will randomly read noise (like an antenna) which might trigger your logic to toggle the pin.

Oooohhh, very clever, i didnt think of that!
Ill try it right away.
But, wouldn't that affect the code? Because i want the light to toggle only when i press the button.

No change. When i set it to INPUT_PULLUP it just blinks slower. Dont't think i metioned buy i have NOTHING else but a LED and 200Ohm resistor connected to the board and its blinking.

In all your functions like gumbKuhinja, gumbBoravak and gumbBoravak you need to change the first if statement from if( .. == HIGH) to if( .. == LOW) since the button is low-active (LOW when pressed, normally HIGH when unpressed). You can edit your question to include your new code.

Still the same but now instead of D6 and D8 its now V1/D2 and V6/D10

KEEP IN MIND that i have nothing connected to the arduino. Im monitring it trough the serial monitor.

Your new code still has INPUT instead of INPUT_PULLUP. With pulled up pins and checking if the pin LOW, nothing should happen if you have nothing connected. Please try https://pastebin.com/zYESFnSU . If that does not work start a new sketch with minimal code in which you only try to toggle the LED by button press and nothing else, to track down the problem.

Its no longer blinking randomly but now my buttons donw work. I tried shorting 5V and pin 11 and nothing happend.

Tried minimalist code. This is the one I used when i was figuring out how to toggle buttons.
https://pastebin.com/esTESF3j

This comment section is getting rather messy. With your minimal test code, did you try to short the button pin, which is D8, to GND to trigger it? Work on getting the "toggle LED by button press" working (follow https://www.arduino.cc/en/Tutorial/InputPullupSerial) first, then re-integrate code. If you are unsure on what voltage level a pin is, use a multimeter.

I would appreciate if you would now post your answer as a answer because you just solved my problem good sir.
Just to elaborate. Now sisnce im using INPUT_PULLUP in need to connect lets say pin 11 to GND for the code activate ledKuh?
Because that's how I did it now and it works prefectly.

You had the following general problem:
The code you were using was configuring a pin into INPUT mode and reading the value on it. On this pin you conencted a button without extern pullup or pulldown resistor. This means that if the button is not pressed, it is not connected to anything and thus a floating pin. You cannot realibly read the value of the floating pin, as its voltage level may be on pretty much anything. It picks up interference like an antenna.
To solve this the button pin must be pulled to known voltage level if it is not connected (aka button is not pressed). We achieve this by using a resistor which is on one end connected to the button pin and on the other end connected to either VCC (+5V) or GND (0V). This has the effect that when the button is not pressed, the resistor pulls the voltage level of this pin up (if connected to VCC), or down if connected to GND.
We can either attach a resistor (e.g. 10K Ohm) in the circuit or active the internal (weak) pull-up resistors in our microcontroller. In Arduino, this is achieved by using pinMode( buttonPin, INPUT_PULLUP).

In this circuit with INPUT_PULLUP on D2, we have:

if the button is not pressed down, no connection to GND is made. The activated pull-up resistor will pull the voltage level of D2 to HIGH
if the button is pressed down, it makes a connection to GND and overrides the pullup resistor. Pin D2 now reads LOW.

The logic can of course also be inverted -- you can use a PULLDOWN resistor and instead of connecting the button to GND on the other side connect it do 5V. This make the button read LOW when unpressed and HIGH pressed.
So the modified code must be changed from
  pinMode(gumbKuh, INPUT);
  pinMode(gumbKup, INPUT);
  pinMode(gumbSpav, INPUT);
  pinMode(gumbBor, INPUT);

to
  pinMode(gumbKuh, INPUT_PULLUP);
  pinMode(gumbKup, INPUT_PULLUP);
  pinMode(gumbSpav, INPUT_PULLUP);
  pinMode(gumbBor, INPUT_PULLUP);

and the logic which detects a button pressed must be changed to trigger an action when the pin is LOW (because a PULLUP is used, button reads LOW when pressed, HIGH else).
So from code of the form
void gumbBoravak()
{
  gumbStanjeBor = digitalRead(gumbBor);
  if (gumbStanjeBor == HIGH)
  {
    /* LED toggling and debouncing */
    delay(500);
  }
}

To
void gumbBoravak()
{
  gumbStanjeBor = digitalRead(gumbBor);
  if (gumbStanjeBor == LOW)
  {
    /* LED toggling and debouncing */
    delay(500);
  }
}

Also I recommend you to watch this youtube video to learn more about floating pins and pullup/pulldown resistors: Pull up Resistor Tutorial


text:
What is a safe way to power arduino nano with 7.4V Lipo battery?
I'm trying to power Arduino Nano with 7.4V LiPo battery and use it to run 2 DC motor using L293D. I have figured out how power it with the connection just like in the figure below(the diagram uses Uno and the battery is 9V but try to imagine it as Nano and 7.4V).  I also found another way to power it by connecting the red wire from battery to Vin on the Arduino instead of connecting it to the positive power rail.
So, my question is which is a safer way to power it and what is the difference and risk of one the way I mention.

you ask if it is ok to connect the battery to Vin instead of the power rail of the breadboard from where it is connected to the Vin? there is no difference

What I mean is that, instead of having the red wire on the power rail, connect it directly to the Vin of the Arduino. Both of this works but my question is there any difference and which is safer to do?

on the fritzing schema the battery is connected to 5V. it would damage the Atmega. the battery should be connected to Vin. And it makes no difference if direct, over the power rail or with T junction.

Connect it via the Vin pin. That way the 6-8.4 volt of the battery will go through the voltage regulator on the Nano, giving you a stable 5v.
What you show in your diagram is the wrong way of connecting the battery. The absolute maximum you can supply to the Arduino's 5V pin is 6 Volt. Atmel recommends no more than 5.5V. So your battery exceeds this when it's full.

sorry, where in the question you see Vcc pin mentioned?

I thought the Arduino pin was labeled Vcc, but it was 5V. Updated my question.

right. on the fritzing it is connected to 5 V. that is wrong

That is what I was trying to say.


text:
Higher than 12V Arduino Uno
On many tutorials I have looked at, they say that you should power your Arduino with a 5 - 12V external power supply, but on the Arduino, there is a voltage regulator. Is there anything wrong with powering your Arduino with power outside this range?
Solved

it won't work very well below 5 V ... the regulator has to dissipate too much power when the input voltage is high .... this sort of question has been asked before

Thank you for your answer.

it is 7 to 12 V

Let me just give you an example of what happens even with 12V: One time I was working on a claw machine that I made for the Arduino and when I plugged in 12V while the 5V USB port plugged into the computer, guess what happened. Well, I'll tell you: the Arduino burned up and it was broken. I couldn't even put in the code because it was so cooked. I don't think it turned on either. You see, 7-12V is just a range. You typically want to use what is in between the voltage rating. Even with 12V, you have to be careful. So, hopefully that clarifies. Basically, it will burn up your Arduino into hot plastic, sort of like a hot glue gun. The datasheets agree if you don't believe us. You can try it, but just be aware that I warned you not to. This is the datasheet for the Mega 2560 rev3 It's all because of voltage, which is a sort of pressure for electricity. You could say the same for the water specifications. What happens when you add too much pressure to a water container? It bursts, right? In a way, this can be applied to the Arduino. Thanks for reading, hopefully this helped.

Well, things are a bit more complicated. For the MEGA, if you use the barrel jack the power is fed by the LD1117 IC. It has a roughly 1x1cm heatsink, but in order to be more conservative I'll ignore it. Consequently the thermal resistance is 110°C/W. If the arduino remains at 30°C, the maximum power the 1117 can dissipate is about 860mW. Let's remove 10% to be a bit safer (so 780mW). When the mega is idle with no external devices, it draws 73mA; consequently the 1117 can bear a 10.5V drop, which puts the maximum input voltage at 15.5V. If, on the other hand, you [...]

[...] want to add two bright LEDs (20mA each), the current jumps to 113mA, lowering the voltage drop the 1117 can withstand to 6.9V (and so a maximum input voltage of 11.9V). As you can see, the maximum input voltage highly depend on what you are building...

This sounds more like a power supply or board issue; there should be zero issues with powering through the barrel jack and having USB plugged in at the same time; that's a very common scenario when, e.g., you're directly connected to a 3D printer or CNC machine through USB.

Well, it is a clone. I am not sure if that has to do with anything, if you want I can delete my answer, if it doesn't make sense.

You could use a step-down converter to lower the voltage and also stabilize it to 12V or even lower and you wouldn't have any problem even if you power supply isn't really stable and outputs higher voltage.
(Instead of buying one you can even build it, it isn't really hard to make one)