text:
How to speed application up (if possible)
I have an ARD 2560, which I communicate with through a special written Delphi 7 program (USB handling is done in the D-7 program).
I use the command syntax:
<REG> <COMMAND) <:> <NUMBER> <CR>

where
REG is  A - K (the registers in the ARD 2650)
COMMAND can be a 2-chars command, but mostly 1-char commands.
EG:  AR:255<cr>  // AR configures DDRA to out- or in-put , depending on the parameter - (here 255 / 0xff) .

AI:0<cr>  Read port A input (actually return content of ARD2560 port A input register)

AO:<number><CR>   Send Number to port A (and return result to D-7 ).

......

All those command are valid for Reg A to Reg K.
The response time from transmit (d7) to I ("D/7") get the answer is approx. 1 1/2 second. I have a feeling that my code is a big, big kludge (it actually works), but I would like any advice(s) to to improve code // speeding it up.
If I drop the line:
 if (char (pport[0] == '*' ))  // '*' can be 'A' to 'K'

The response time increases to appr. 2 seconds.
(sorry that there are no comments!)
Here's the code:
#include <Esplora.h>

void setup()
{
    Serial.begin(9600);
}

void loop()
{

  String chr;

  if (Serial.available() > 0)
  {
    String pport = Serial.readStringUntil(':');
    {
      String pos = Serial.readStringUntil('\n');

      if (char (pport[0] == 'A' ))        /* A */
      {
        if (pport == "AR")
        {
          DDRA = pos.toInt();
          DOCRLF("//AR+", pos.toInt());
        }
        else
        if (pport == "AI")
        {
          if (DDRA == B00000000)
          {
            Serial.print(PORTA);
            chr = "//AI";
          }
          else
          {
            chr ="//AI-";
          }
          DOCRLF(chr , pos.toInt());
        }
        else
        if (pport == "AO")
        {
          if (DDRA == B11111111)
          {
            PORTA = pos.toInt();
            chr = "//AO+";
          }
          else
          {
            chr = "//AO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "AU")
        {
          Serial.print(PORTA);
          DOCRLF("//AU+", pos.toInt());
        }
        else
        if (pport == "ABW")
        {
          PORTA = pos.toInt();
          DOCRLF("//ABW+", pos.toInt());
        }
        else
        if (pport == "ABR")
        {
          Serial.print(PORTA);
          DOCRLF("//ABR+", pos.toInt());
        }
      }
      else
      if (char (pport[0] == 'B' ))        /* B */
      {
        if (pport == "BR")
        {
          DDRB = pos.toInt();
          DOCRLF("//BR+", pos.toInt());
        }
        else
        if (pport == "BI")
        {
          if (DDRB == B00000000)
          {
            Serial.print(PORTB);
            chr = "//BI+";
          }
          else
          {
            chr = "//BI-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "BO")
        {
          if (DDRB == B11111111)
          {
            PORTB = pos.toInt();
            chr = "//BO+";
          }
          else
          {
            chr = "//BO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "BU")
        {
          Serial.print(PORTB);
          DOCRLF("//BU+", pos.toInt());
        }
        else
        if (pport == "BBW")
        {
          PORTB = pos.toInt();
          DOCRLF("//EBW+", pos.toInt());
        }
        else
        if (pport == "BBR")
        {
          Serial.print(PORTB);
          DOCRLF("//BBR+", pos.toInt());
        }
      }
      else
      if (char (pport[0] == 'C' ))        /* C */
      {
        if (pport == "CR")
        {
          DDRC = pos.toInt();
          DOCRLF("//CR+", pos.toInt());
        }
        else
        if (pport == "CI")
        {
          if (DDRC == B00000000)
          {
            Serial.print(PORTC);
            chr = "//CI+";
          }
          else
          {
            chr = "//CI-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "CO")
        {
          if (DDRC == B11111111)
          {
            PORTC = pos.toInt();
            chr = "//CO+";
          }
          else
          {
            chr = "//CO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "CU")
        {
          Serial.print(PORTC);
          DOCRLF("//CU+", pos.toInt());
        }
        else
        if (pport == "CBW")
        {
          PORTC = pos.toInt();
          DOCRLF("//CBW+", pos.toInt());
        }
        else
        if (pport == "CBR")
        {
          Serial.print(PORTC);
          DOCRLF("//CBR+", pos.toInt());
        }
      }
      else
      if (char (pport[0] == 'D' ))        /* D */
      {
        if (pport == "DR")
        {
          DDRD = pos.toInt();
          DOCRLF("//DR+", pos.toInt());
        }
        else
        if (pport == "DI")
        {
          if (DDRD == B00000000)
          {
            Serial.print(PORTD);
            chr = "//DI+";
          }
          else
          {
            chr = "//DI-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "DO")
        {
          if (DDRD == B11111111)
          {
            PORTD = pos.toInt();
            chr = "//DO+";
          }
          else
          {
            chr = "//DO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "DU")
        {
          Serial.print(PORTD);
          DOCRLF("//DU+", pos.toInt());
        }
        else
        if (pport == "DBW")
        {
          PORTD = pos.toInt();
          DOCRLF("//DBW+", pos.toInt());
        }
        else
        if (pport == "DBR")
        {
          Serial.print(PORTE);
          Serial.println("//DBR+");
        }
      }
      else
      if (char (pport[0] == 'E' ))        /* E */
      {
        if (pport == "ER")
        {
          DDRE = pos.toInt();
          DOCRLF("//ER+", pos.toInt());
        }
        else
        if (pport == "EI")
        {
          if (DDRE == B00000000)
          {
            Serial.print(PORTE);
            chr = "//ER+";
          }
          else
          {
            chr = "//ER-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "EO")
        {
          if (DDRE == B11111111)
          {
            PORTE = pos.toInt();
            chr = "//EO+";
          }
          else
          {
            chr = "//EO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "EU")
        {
          Serial.print(PORTE);
          DOCRLF("//EU+", pos.toInt());
        }
        else
        if (pport == "EBW")
        {
          PORTE = pos.toInt();
          DOCRLF("//EBW+", pos.toInt());
        }
        else
        if (pport == "EBR")
        {
          Serial.print(PORTE);
          DOCRLF("//EBR+", pos.toInt());
        }
      }
      else
      if (char (pport[0] == 'F' ))        /* F */
      {
        if (pport == "FR")
        {
          DDRF = pos.toInt();
          DOCRLF("//FR+", pos.toInt());
        }
        else
        if (pport == "FI")
        {
          if (DDRF == B00000000)
          {
            Serial.print(PORTF);
            chr = "//FI+";
          }
          else
          {
            chr = "//F1-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "FO")
        {
          if (DDRF == B11111111)
          {
            PORTF = pos.toInt();
            chr = "//FO+";
          }
          else
          {
            chr = "//FO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "FU")
        {
          Serial.print(PORTF);
          DOCRLF("//FU+", pos.toInt());
        }
        else
        if (pport == "FBW")
        {
          PORTF = pos.toInt();
          DOCRLF("//FBW+", pos.toInt());
        }
        else
        if (pport == "FBR")
        {
          Serial.print(PORTF);
          DOCRLF("//FBR+", pos.toInt());
        }
      }
      else
      if (char (pport[0] == 'G' ))        /* G */
      {
        if (pport == "GR")
        {
          DDRG = pos.toInt();
          DOCRLF("//GR+", pos.toInt());
        }
        else
        if (pport == "GI")
        {
          if (DDRG == B00000000)
          {
            Serial.print(PORTG);
            chr = "//GI+";
          }
          else
          {
            chr = "//GI-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "GO")
        {
          if (DDRG == B11111111)
          {
            PORTG = pos.toInt();
            chr = "//GO+";
          }
          else
          {
            chr = "//GO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "GU")
        {
          Serial.print(PORTG);
          DOCRLF("//GU+", pos.toInt());
        }
        else
        if (pport == "GBW")
        {
          PORTG = pos.toInt();
          DOCRLF("//GBW+", pos.toInt());
        }
        else
        if (pport == "GBR")
        {
          Serial.print(PORTG);
          DOCRLF("//GBR+", pos.toInt());
        }
      }
      else
      if (char (pport[0] == 'H' ))        /* H */
      {
        if (pport == "HR")
        {
          DDRH = pos.toInt();
          DOCRLF("//HR+", pos.toInt());
        }
        else
        if (pport == "HI")
        {
          if (DDRH == B00000000)
          {
            Serial.print(PORTH);
            chr = "//HI+";
          }
          else
          {
            chr = "//HI-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "HO")
        {
          if (DDRH == B11111111)
          {
            PORTH = pos.toInt();
            chr = "//HO+";
          }
          else
          {
            chr = "//HO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "HU")
        {
          Serial.print(PORTH);
          DOCRLF("//HU+", pos.toInt());
        }
        else
        if (pport == "HBW")
        {
          PORTH = pos.toInt();
          DOCRLF("//HBW+", pos.toInt());
        }
        else
        if (pport == "HBR")
        {
          Serial.print(PORTH);
          DOCRLF("//HBR+", pos.toInt());
        }
      }
      else
      if (pport == "RA")
      {
        int aport = (pos.toInt());

        if (aport > -1 && aport < 16)
        {
          Serial.println (" OK ");
        }
      }
      else
      if (pport == "KO")
      {
        Serial.print("//KO+");
        if (DDRA == B11111111)
        {
           Serial.print("A");
        }
        else
        {
           Serial.print("a");
        }
        if (DDRB == B11111111)
        {
           Serial.print("B");
        }
        else
        {
           Serial.print("b");
        }
        if (DDRC == B11111111)
        {
           Serial.print("C");
        }
        else
        {
           Serial.print("c");
        }
        if (DDRD == B11111111)
        {
           Serial.print("D");
        }
        else
        {
           Serial.print("d");
        }
        if (DDRE == B11111111)
        {
           Serial.print("E");
        }
        else
        {
           Serial.print("e");
        }
        if (DDRF == B11111111)
        {
           Serial.print("F");
        }
        else
        {
           Serial.print("f");
        }
        if (DDRG == B11111111)
        {
           Serial.print("G");
        }
        else
        {
           Serial.print("g");
        }
        if (DDRH == B11111111)
        {
           Serial.print("H");
        }
        else
        {
           Serial.print("h");
        }
        Serial.println();
      }
    }
  }
}

void DOCRLF (String txt, int vval)
{
  Serial.print(txt);
  Serial.println(vval);
}

You wrote: “readStringUntil('\n')”. Your problem looks to me like a timeout in readStringUntil(). Are you sure your Delphi program does send that LF character? And your serial port driver does not convert it to CR?

First check which commands take so much time, 1.5 seconds is a lot for a CPU. When knowing what statements take so much time, you can pinpoint how to improve the performance, high likely it's only one statement (or several times the same statement).

why 9600 baud rate? CR is \r not \n. \n is LF

This is not really a proper answer to your question. As I mentioned in
a comment, I believe your actual problem is the Delphi program not
sending the LF character you sketch expects. Instead, I am giving here a
coding style suggestion: do not repeat yourself.
Whenever you find yourself coding with copy-paste, you should try to
simplify the program using arrays and/or loops. Below is a suggested
alternative version of your loop(), with most of its redundant
repetitive repetitions removed:
struct port_t {
    volatile uint8_t *ddr;
    volatile uint8_t *port;
};

static const port_t ports[] = {
    { &DDRA, &PORTA },
    { &DDRB, &PORTB },
    { &DDRC, &PORTC },
    { &DDRD, &PORTD },
    { &DDRE, &PORTE },
    { &DDRF, &PORTF },
    { &DDRG, &PORTG },
    { &DDRH, &PORTH },
    { NULL,  NULL   },  // there is no port I
    { &DDRJ, &PORTJ },
    { &DDRK, &PORTK },
    { &DDRL, &PORTL }
};

void loop()
{
    // Read the command line.
    if (Serial.available() == 0) return;
    String pport = Serial.readStringUntil(':');
    String pos = Serial.readStringUntil('\n');

    // The "KO" command reads all ports.
    if (pport == "KO") {
        Serial.print("//KO+");
        for (char port_id = 'A'; port_id <= 'H'; port_id++) {
            if (*ports[port_id - 'A'].ddr == 0xff)
                Serial.print(port_id);
            else
                Serial.print(tolower(port_id));
        }
        Serial.println();
        return;
    }

    // Identify the port to act on.
    char port_id = pport[0];
    if (port_id < 'A' || port_id > 'L' || port_id == 'I') {
        Serial.println(F("Error: unknown port."));
        return;
    }
    port_t port = ports[port_id - 'A'];

    // Perform the requested action.
    String command = pport.substring(1);
    String chr = String("//") + port_id + command;
    if (command == "R") {
        *port.ddr = pos.toInt();
        DOCRLF(chr + "+", pos.toInt());
    } else if (command == "I") {
        if (*port.ddr == 0)
            Serial.print(*port.port);
        else
            chr += "-";
        DOCRLF(chr , pos.toInt());
    } else if (command == "O") {
        if (*port.ddr == 0xff) {
            *port.port = pos.toInt();
            chr += "+";
        } else {
            chr += "-";
        }
        DOCRLF(chr, pos.toInt());
    } else if (command == "U" || command == "BR") {
        Serial.print(*port.port);
        DOCRLF(chr + "+", pos.toInt());
    } else if (command == "BW") {
        *port.port = pos.toInt();
        DOCRLF(chr + "+", pos.toInt());
    }
}

I wanna thank you. As a newbie to C (C++)  in Arduino programming I wanted to do it in a way  you just showed me.  Using "ARRAYS"  but I did not know how to. (A little easier in Delphi- I think ). ANyway I want to give you a very special "Thanks  a lot" for 2 reasons.   1: You showed me at  way to solve the problem and 2: by supplying a code example.

@ Juraj:   DARN - I need to update my basics.  Thanks a lot for correcting (always thougt that '\n'  == CR.) Now I'm wiser (a least a little !)

I changed the '/n' to '\r'  added  LF to to the D-7 tx-routine (now transmits  + CRLF . That totally improved the speed on the old "KLUDGE"- version. Responsetime is no > 1.sec (I can' measure to be precise.)   Added my "missing" rutines (void Setup() + DOCRLF(..) ) to the new version, compiled , corrected a typo , compiled again- and VOILA - it worked.  Much faster than before - response time again far under 1  sec (unmeasured) .  I am very ,very pleased.  Thank you to both of you.

@KristianSander, you can set faster baud rate. try 115200 baud or more

@Juraj:  I will set the Baud-rate later, when the D-7 program is improved. There is a speed increase (opimizing code) there,  too .


text:
Is it possible to disable functions/methods?
I recently started using the TimeAction library (which allows for proto-threading) and I noticed it has a really useful function for enabling/disabling threads. I want to use the same idea but apply it to a general function, though I haven't been able to find a possible solution to doing such a task on the internet. Here is a potential way for how I would like to implement it:
#include <TimedAction.h>

boolean disableCheck = false;
boolean checking = false;
boolean state = false;
const int motionPin = 5;
void checkMotion();
void motion();
void DisableCheckMotion();

TimedAction checkable = TimedAction(6000, DisableCheckMotion);

void setup() {
   pinMode(motionPin, INPUT);
   Serial.begin(9600);
}

void loop() {
  checkMotion(); //this will be the function I wish to enable and disable

  if(checking == true)
  {
    motion();
  }
  if(disableCheck == true)
  {
    checkable.check();
  }

}
void checkMotion()
{
   checking = true;
}
void motion()
{
   if(digitalRead(motionPin) == HIGH)
{
   Serial.println("motion");
   checking = false;
   checkable.check();
}
}
void DisableCheckMotion()
{
  state ? state = true : state = false;
  if(state == false)
{
  checkMotion.disable(); //this is where I would like to disable the function
  disableCheck = true;
}

  if(state == true)
{
  checkMotion.enable(); //this is where I would like to enable the function
  disableCheck = false;
}
}

The purpose of this task is to output one value for whenever a PIR scanner (set at pin 5) picks up motion. Without any form of delaying it will flood the output with values (which is undesirable). A thread is used to offer this delay, I cannot put the code for checking for motion within the thread as I could risk the chance of a reading being missed.
The ideal setup would be for the Arduino board to receive the input and then delay the input from being received again for a period of time while not delaying the entire program. What would be the best way to implement this?

" I cannot put the code for checking for motion within the thread as I could risk the chance of a reading being missed" Wouldn't you miss a reading when the function is a disabled?

You probably don't want threads for this. Instead, check elapsed time in your main loop, and call the less frequent functions only if enough time has elapsed since you last ran them.

@ChrisStratton That's basically what TimedAction.h does. It does the same thing as SimpleTimer.h - it just encapsulates a check of millis() and runs functions when the required delay passes. Nothing you can't do with a simple check of millis() in your main loop. Ideal if you don't have a clue about simple programming...

If you don't want a function to run you can just return at the start of that function:
void myFunction() {
    if (!myFunctionShouldRun) return;
    ... rest of function ...
}

If myFunctionShouldRun is false the if will be true (due to the !) and the function will return.  If it's true the rest of the function will execute.

source: Stack Exchange

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

sort: votes


text:
Burn hex with optiLoader
Can optiLoader be used to burn custom hex?
For example, there's hex representation stored in optiLoader.ino in image_328, if that value is replaced with content of my pre-compiled hex, should that work right out of the box or some additional tweaking is needed?
EDIT
Discussion about the same topic on arduino forum as well.

ISP is for writing hex. bootloader or program or booth together. why do you want to use optiload? AVRISP sketch in IDE examples does it too.

The reason why I want to use it is because I want to try it without IDE, basically without computer. So I just want to write firmware on new blank IC by pressing a button from my proto board.
AVRISP in should work as well, but I feel like I will have to change much more code in order to make it to work without IDE, because it's using Serial to get data and pass it to target IC, right? ...and if optiLoader works as I thought above, then I can just simply replace HEX content with my.

ISP is not Serial. ISP uses SPI connection

It does but only to talk with target IC, but communication between programmer IC and IDE is done via serial.

@Juraj BTW I was referring to these methods getch and avrisp in that ArduinoISP sketch.

ok, I understand, you want to have the hex as part of the flashing sketch. but hex is more then twice larger then the binary representation of the program. you would be limited to a small program with hex. or you want to use SD card to store the hex?

Yes, that's correct, for now I would like to stick with small program with HEX. Later I want to move to SD card to store hex.

sure is, it is possible. the esp8266 AVRISP library does it with SPI connected AVR. the HEX is first received over WiFi there. try it with optiload. btw, WestfW is active on arduino.cc forum

Thanks @Juraj I will take a look at this one as well.

What do you really want to do? Burn a bootloader, or burn some useful code that does something? (A bootloader is just for uploading code)

hex is more then twice larger then the binary representation of the program - So? The .hex file stores each byte as readable hex, so the byte 0xAB is stored as "AB". However it only takes up one byte in the program memory.

Also see parse intel hex into SPI commands for arduino ICSP AVR

@NickGammon this looks amazing! So, basically in order to achieve what I mentioned above, in your sketch I would just need to replace this part ifstream sdin (fName); in readHexFile method, to read from hard-codded value, instead of using SD card as data source. Ofc, to remove the part related to display, sd card, etc. but this is how you are reading content of that HEX file, line by line?

@NickGammon, what was wrong on my statement about the size? the 'more' was for line endings

@Juraj - I didn't see why "you would be limited to a small program with hex". The hex digits in the .hex file are just an intermediate way of representing the same data. There is no limitation in size because you are reading from the .hex file.

@NickGammon, it was about in-memory hex. like the in-memory  bootloader hex in OptiLoader, Chris has it strong in the answer

Yes, it should work provided that your desired target image is stored in the same form, with correct metadata, and that it is small enough to fit in the programmer device.
The storage format of the payload-to-program could be made more optimal by a factor of almost two; however, for the original purpose of injecting compact Arduino-style bootloaders that is scarcely needed, and would have made preparing payloads more complicated.

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


text:
Using SD shield for extra external memory?
I am an Arduino beginner and I am planning to make a musical instrument with it. I want to add record and playback functionalities into the instrument.
I figure I will have to store lots of data to meet this feature, but the Arduino I'm using (Uno/Nano) probably won't have enough memory to hold lots of songs.
My question is, is using an SD card with an SD shield a good way to expand memory? If not, what should I use to do so?
Thanks

As a beginner this MIGHT be a bit of a big thing to take on. Not that you shouldn't do it, just be aware that trying to write the code that will read and process data from SD is not trivial.   Also don't think of this as EXPANDING the memory of the arduino, as the memory you are adding cannot be used for your program.

they make hardware audio modules, for example with mp3 playback from sdcards or bluetooth, and that would be mounds eaiser than implementing it all yourself using low-lever hardware and from-scratch software. Checkout adafruit et al.'s offerings in that area before you spend week re-inventing a wheel.

By "record and playback" do you mean audio recording, or something more akin to MIDI where you just record the instructions of what notes to play when?

@Majenko I would be recording what note/pitch is being played, and playback would just play audio based on this data

So like MIDI then.  Sure, you can do that with SD.

@ChadG I'm assuming there are libraries I can use from online to read/write to SD?

Yep, there are 'built in' ones with examples in the IDE

There are different options:

SD shield: much memory (GB's), however keep in mind that it will take time to retrieve the data from the SD card. Also you can retrieve 512 bytes every time (which also means it costs 512 precious bytes of arduino SRAM).
External SRAM: There are external SRAM ICs, like 23LC1024 or 24K256. These are much faster and offer 128 or 32 KB. There are many others too, these are most 'common'. These are much faster than SD cards, you can get 1, 2 or more bytes per time. But it's not the same as Arduino SRAM, e.g. you cannot really store variables, so you have to copy data to internal SRAM to be used.

So first, check how much you need, and more important: what is the latency you can live with.

SRAM is probably not going to get the OP very far when it comes to audio, although it could be used as a buffer between "disk" and the arduino to improve latency issues.

True, I now read playback and record.

ESP32 modules have more RAM and 4mb of flash for less money than those ICs ;)

For audio processing, you might better use a Raspberry PI.

Thanks for the response! Based on your description I think an external SRAM would probably be better for the purpose.

@ChadG could you clarify on why it wouldn't work?

Also keep in mind this is for a educational project, and I'm not that willing to spend a lot of money on it. (Which is why Arduinos are being used rather than raspberry pi)

It depends on how much memory you need, the types I mentioned are 32 KByte or 128 KByte, if you want to store samples on stero 44.1 KHz you will run out of memory very quickly.

The recorded data would be very small, something that size should be sufficient.

In that case it should work ... a 23K256 cost about a dollar, but are mostly found not in DIP8 format so you have to do some 'smd' soldering, or buy a 23LC1024 for about 5 dollar.

Would it be difficult to get it working with beginner experience?

The 23K256 is easier (but need some tricky soldering), the 23LC1024 involves a lot of wires (has many more pins).

Since you are working just with instructions on how to play audio, not the audio itself, you effectively have very small amounts of data (comparatively).
You can store that data in a file on SD card and read it back simply enough (there's plenty of examples for reading from and writing to SD).
You don't need the whole song in memory all the time - you only care about the note you're playing (or recording) at any one instance in time, so you don't need lots of memory.
How you format the data is entirely up to you, but I would suggest following the MIDI standard which will allow you to work with other tools to create and edit the files as well as the Arduino. You can also then export your music simply to other applications, such as MuseScore, Finale, Sibelius, Ardour, etc.


text:
Genuino UNO 5V pin is reading 0.3V
So I was trying to set up the LCD screen that came with my Genuino starter kit when I noticed that the board screen did not power on at all, unlike a few days ago when it worked.
In order to verify that the UNO was delivering power I simply connected an LED in series with a 220Ω resistor, between the 5V and ground pins. The LED did not power on.
I then, with the UNO still connected over USB, measured the voltage between across the resistor and LED and found it to be around 0.2-0.3V. Going further, reading the voltage between the 5V and ground solder connections on the back of the board and the reading is about the same.
I can power the LED from a digital pin that I set to HIGH, the issue seems to just be with the 5V pin.
Is there anything simple that I am missing (I hope there is) or is there likely a problem with my board? If there is a problem, could I use a digital pin to power a larger circuit such as that with an LCD or would the current supplied be too low?

Are you sure you have the 5V pin and not Vin?   And that driving an LED from a digital output worked under the same circumstances where the 5V pin did not?

Positive, disconnecting only the power connection and moving it to either 3.3V, Vin or a HIGH digital output results in the LED powering on.

Maybe you should try where the pin sticks through the bottom of the board.  It is possible for the sockets you plug into from above to fail mechanically and not make contact with whatever you plug in.

I have tested both the sockets and the solder connections under the board to no avail, the behaviour is consistent.

Power it off, get an ohm meter with sharp leads and start tracing continuity from the ATmega VCC pin to the inactive 5v pin.  Or if your time is worth more than the board, replace it.

And you do know that there are two ground pins, right?

I have tried but can't seem to find the fault. I may just replace it. And yes I have tried all three ground pins. Thank you for your time.

If the chip is running the only thing that can stop the 5v pin getting power is physical damage. There is only metal between the chip and the pin.

the LCD can be powered by a digitalWrite(HIGH), but the backlight cannot.

There are a couple more places you can sample the 5V signal, see the photo here:

On the right, on the ICSP header, the pin marked VCC is also connected to the 5V signal. Try testing that.
(The other one is pin 2 of the ICSP interface for the USB chip, but the one on the right should be adequate for testing).
I don't know why you are mucking around with LEDs and resistors, just put your meter between Gnd and 5V.
I find sometimes that the hookup cable has failed, try testing that (or try with a different cable).


text:
Configure Arduino IDE to not quit when the last sketch is closed
The Arduino app takes a long time to launch on MacOS. (The Initializing Packages... stage takes over a minute.) It's very frustrating when you accidentally close the last sketch window and the app quits. Then you have to wait for it launch again.
Is there anything that can be done to stop it from closing automatically?

no, it's a single-document-interface (one app instance per sketch), so there's no "basket" to keep around like with multiple-document interfaces such as photoshop, notepad++, excel, etc

But opening additional documents happens instantly. You don't have that slow launch experience until after you close the last document.

It used to warn you when you tried to do that, I don't know why that warning was removed.

yes, some of the background processes, notably java, are shared between instances, so the first one is slower. You can try using some tool to hide the first instance so it can't be closed. on windows there was an app called "process control" which allowed that, not sure about mac...


text:
"Bad request" error (HTTP) while posting to PHP server using Arduino and ESP8266
I'm doing an IoT project where the temperature and humidity values from a DHT11 sensor is sent to a PHP server using HTTP post. When I run the Arduino, the Serial Monitor says "Bad request". The sensor values are not appearing on the webpage. Please, help me figure out the problem. I am using an Arduino Uno with and an ESP-01.
// Code to use SoftwareSerial
//The final sketch
#include "SoftwareSerial.h"
#include <dht.h>

#define dht_dpin 8

String data;
String ssid = "TRAK family";

String password = "rukman12345";

SoftwareSerial espSerial(6, 7); // RX, TX

dht DHT;

float t;
float h;

String server = "svce-ece-b.000webhostapp.com";

String uri = "esp.php";

boolean DEBUG = true;

void showResponse(int waitTime)
{
    long t = millis();
    char c;
    while (t + waitTime > millis()) {
        if (espSerial.available()) {
            c = espSerial.read();
            if (DEBUG)
                Serial.print(c);
        }
    }
}

void setup()
{
    DEBUG = true;

    Serial.begin(115200);
    delay(500);

    espSerial.begin(115200);

    espSerial.println("AT+RST");
    showResponse(1000);

    // espSerial.println("CIOBAUD=9600");
    // showResponse(1000);

    espSerial.println("AT+CWMODE=1");
    showResponse(1000);

    espSerial.println("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"");
    showResponse(5000);

    if (DEBUG)
        Serial.println("Setup completed");
}

void httppost()
{
    espSerial.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");

    if (espSerial.find("OK")) {
        Serial.println("TCP connection ready");
    }
    delay(1000);

    String postRequest =
        "POST " + uri + " HTTP/1.0\r\n" +
        "Host: " + server + "\r\n" +
        "Accept: *" + "/" + "*\r\n" +
        "Content-Length: " + data.length() + "\r\n" +
        "Content-Type: application/x-www-form-urlencoded\r\n" +
        "\r\n" + data;

    String sendCmd = "AT+CIPSEND=";
    espSerial.print(sendCmd);
    espSerial.println(postRequest.length());

    delay(500);

    if (espSerial.find(">")) {
        Serial.println("Sending..");
        espSerial.print(postRequest);

        if (espSerial.find("SEND OK")) {
            Serial.println("Packet sent");
            while (espSerial.available()) {
                String tmpResp = espSerial.readString();
                Serial.println(tmpResp);
            }

            // close the connection
            espSerial.println("AT+CIPCLOSE");
        }
    }
}

void loop()
{
    // Read sensor values
    DHT.read11(dht_dpin);
    float t = DHT.temperature;
    float h = DHT.humidity;
    if (isnan(t) || isnan(h)) {
        if (DEBUG)
            Serial.println("Failed to read from DHT");
    }
    else {
        if (DEBUG)
            Serial.println("Temp=" + String(t) + " *C");
        if (DEBUG)
            Serial.println("Humidity=" + String(h) + " %");

        data = "temperature=" + String(t) + "&humidity=" + String(h);

        httppost();
    }

    delay(1000);
}

This is my PHP code:
<?php
    global $Temp;
    global $Humidity;
    if(isset($_POST['temperature'])){
        $Temp=$_POST["temperature"];
    }
    if(isset($_POST['humidity'])){
        $Humidity=$_POST["humidity"];
    }

    $Write="
Temperature : " .$Temp . " Celcius
" . "
Humidity : " .       $Humidity . " %
";
    file_put_contents('sensor.html',$Write);
?>

the serial monitor says bad request   ... the code that you posted does not contain the text bad request ... the message does not come from the code that you posted

@jsotola That's probably the response from the server.

uri should start with /.

@gre_gor thanks brother. it resolved my issure

The URI path in the HTTP request must start with a /.
It should be:
String uri = "/esp.php";


text:
RGB Not displaying Red when using LCD
I was testing my RGB (common anode) on its own playing with colours and got the red, green to work as desired.
However, when I connected my LCD board to my Arduino Uno as well as the RGB (using the same code prior and same output pins so I know the code isn't the issue) the RGB no longer displays red.
I assume it has something to do with the fluctuating voltage/current after I've put in the LCD but I cant work out how to resolve it. When its meant to be red it's just nothing, doesn't light up, green however still works.
#include <LiquidCrystal.h>
#define COMMON_ANODE
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
int SelectCounter = 0;
int hours = 0; // start hours
int minutes = 0; //start min
int seconds = 5; //start seconds
int redPin = A1;
int greenPin = 2;
int bluePin = 3;
int digitposition = 0;
int readkey;
int speaker = A5;
int buttonPin = A4;
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;

void setup() {
pinMode(speaker, OUTPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}

void loop() {
noTone(speaker);
setColor(0, 0, 255); // red

....... }

void trigger() {
  lcd.clear(); // clears the screen and buffer
 lcd.setCursor(6,0);
 lcd.println("MUM:      ");
 lcd.setCursor(4, 1); // set timer position on lcd for end.
 lcd.println("WAKE UP!    ");
 tone(speaker, 10);
 setColor(0, 255, 0);  // green
 delay(500);
 digitalWrite(A1, HIGH);
 digitalWrite(2, HIGH);
 digitalWrite(3, HIGH);
 noTone(speaker);
 delay(500);
 lcd.display();
 }

void setColor(int red, int green, int blue)
{
  #ifdef COMMON_ANODE
   red = 255 - red;
   green = 255 - green;
   blue = 255 - blue;
 #endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

Without schematics and the code it's impossible to answer. However many libraries affects timers and all pwm channels on it. But I don't see why the LCD library should be using a timer.

Would what I've added suffice?

pin 1 is TX of Serial

You know that pins 0 and 1 are used for the Serial communication, right?

Yeah, of course, stupid mistake. So to make it work is all I need to do change red pin to A1 (only analog pins available) because that's not seeming to work, its now made it red, and turned the green one to a mix of yellow/red

I've changed the code accordingly to how it looks now

@AngusRyan and now it works or not? In any case, I suggest you to read the analogwrite arduino page. Particularly the part when they say "On most Arduino boards (those with the ATmega168 or ATmega328P), this function works on pins 3, 5, 6, 9, 10, and 11" and "You do not need to call pinMode() to set the pin as an output before calling analogWrite()"

The analogWrite works on PWM pins only.

Only the pins with a ~ next to it are PWM pins. The pin connected to the red led, pin A1, does not support PWM, so analogWrite will not have the desired effect.


text:
Esp8266 and HttpClient not working properly
I am working on a project to send data to an API. Here is my code
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>

#define USE_SERIAL Serial

ESP8266WiFiMulti WiFiMulti;

const char* key="***********";

void setup() {

    USE_SERIAL.begin(115200);
    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }

    WiFi.mode(WIFI_STA);
    WiFiMulti.addAP("******", "*********");

}
String data=" ";
void loop() {
    data+="{";
    data+="\"";
    data+="light";
    data+="\"";
    data+=":";
    data+=830;
    data+=",";
    data+="\"";
    data+="temperature";
    data+="\"";
    data+=":";
    data+=23;
    data+=",";
    data+="\"";
    data+="humidity";
    data+="\"";
    data+=":";
    data+=202;
    data+="} ";

    // wait for WiFi connection
    if((WiFiMulti.run() == WL_CONNECTED)) {

        HTTPClient http;

        USE_SERIAL.print("[HTTP] begin...\n");
        // configure traged server and url
        http.begin("https://us-central1-sensorapp-d2a64.cloudfunctions.net/getData",key);      //Specify request destination
        http.addHeader("Content-Type", "application/json");  //Specify content-type header
        int httpCode = http.POST(data);   //Send the request
        String payload = http.getString();                  //Get the response payload
        USE_SERIAL.println(httpCode);   //Print HTTP return code
        USE_SERIAL.println(payload);    //Print request response payload

        USE_SERIAL.print("[HTTP] GET...\n");
        if(httpCode > 0) {
            // HTTP header has been send and Server response header has been handled
            USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

            // file found at server
            if(httpCode == HTTP_CODE_OK) {
                //   String payload = http.getString();
                USE_SERIAL.println(payload);
            }
        } else {
            USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
        }

        http.end();
    }

    delay(30000);
}

After one successful request, it gives error 400 (Bad Request) until I reset the nodemcu. But then again it sends the data once successfully and continues with 400 (Bad Request).
Why are all the following requests bad? Is there something I haven't done?

You declare and initialize data as a String in the global space. Then, in loop, you use a bunch of concatenations to build your request string.
You never clear the contents of data, but back at the top of loop() on the next round, you concatenate all the string data again, which duplicates it.
Side note, the String type is terrible for low-memory devices, and especially bad when you use a lot of concatenations. Because of the way the String type works internally, when you concatenate strings, you end up leaving "holes" in the RAM that aren't likely to be able to be re-used.
Even if you do fix the code by clearing data after you submit your HTTP request, your program will still run out of RAM pretty quickly.
Better would be to build the constant parts of the string as constant globals and just concatenate the variable parts when needed and clear it after use.
Best would be to stop using String and use instead a char data[DATA_SIZE] type of string buffer and use the standard C string utilities like strncpy(), strnlen(), strncat(), etc.

Thank You For the reply. I will do it and will update things.

Just using the statement data=" "; in the loop solved my problem.


text:
How to measure the supply voltage of Arduino without using an analog pin
I'm using Arduino Nano to measure temperature with a 10 kohm thermistor and a voltage divider. My problem is I'm getting only 4.2V on the 5V pin. The power is supplied via a USB cable from a desktop PC.

I measured the output voltage of a USB port on the PC and it was around 4.5V. It doesn't look normal. So I suspect the power supply unit of the PC is not strong enough.
But it still makes sense to measure the voltage at the 5V pin since there is no guarantee it's exactly 5V. Its error will affect the calculated resistance of the thermistor. So I got it by connecting the pin directly to the A1 pin.
On the other hand, it seems to me Arduino internally and digitally knows the value of the supply voltage. So it would be faster and easier to get it rather than using the A1 pin. But I don't know how to do it.
After searching on the Internet, I could find only these things which didn't help me much.

voltage level - What are the 5V and VIN pins for? - Arduino Stack Exchange
voltage level - Getting 3.3v on 5v pin in Arduino Uno - Arduino Stack Exchange

I also considered using an external power supply, say 9V to the VIN pin but I don't feel like doing that much.
How can I measure the supply voltage of Arduino without using an analog pin?

The analog inputs measure a voltage ratio: input/reference. Thus the calculated resistance of the thermistor is not affected by variations in the supply voltage.

Okay, so the integer returned by analogRead() is input/reference(1.1V)/5V*1023?

analogRead() returns Vin÷Vref×1024, where Vin is the voltage at the input pin and Vref is usually (if youy did not mess with analogReference()) the supply voltage.

In the case of your voltage divider, analogRead() returns Rthermistor÷(Rthermistor+Rpullup)×1024, irrespective of the supply voltage.

This page says "voltages between 0 and 5 volts into integer values between 0 and 1023" so is it really 1024? If it were 0-5 volts into 0-5, it would be Vin÷Vref(5V)×5, though 0-5 have 6 integer values.

Yes, it's 1024. The ADC saturates at 1 step below Vref. C.f. the datasheet of the microcontroller, which is the only authoritative document for that matter.

Great! So the maximum measurable voltage is not exactly 5V, but 1023/1024*5V if Vref is 5V?

Actually it's 1022÷1024×Vref, because when you read 1023 you don't know whether the input voltage is 1023÷1024×Vref or anything higher. Actually, any voltage above 1022.5÷1024×Vref is expected to give a reading of 1023.

Yes, you can do it.
You can measure the voltage of the internal (approximately) 1.1V reference voltage using the ADC and use the results of that to calculate what the reference voltage you used (VCC) must have been to get the results you did.
This is a function I commonly use:
long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1125300L / result; // Back-calculate AVcc in mV
  return result;
}

Depending on how close to 1.1V your internal reference voltage is, you may need to adjust the value 1125300L in the code above.  Measure the actual VCC voltage and adjust that value until it results in the same voltage being returned (multiplied by 1000 since that function returns millivolts).
However, as Edgar Bonet mentions, you don't need to care about the supply voltage in your situation, since your thermistor readings are just a ratio that input voltage, whatever it is. Change the input voltage and you will get the same results, since the ADC returns a value between 0 and Vcc in 1024 steps. With different supply voltages you still get 1024 steps.

How did you get 1125300L? And why is it 1125300L / result? It seems to me ADCL | ADCH << 8 is a 10 bit ADC value so something like result = 1125300L * result / 1024 would make sense. But for this one result is the denominator.

1125300 is 1100 (1.1v as mv) times 1023 (ADC max value).

In this page, it is 1126400L = 1.110241000. I'm wondering which I should believe.

There are massive arguments around the net regarding if you should use 1023 or 1024. I say 1023. The max value of the ADC is not equal to VREF, but is VREF "minus one LSB" (as stated by the datasheet). 1024 would be VREF but you can't get 1024 out of the ADC.

IMHO it's 1024. Edgar Bonet's comments sound reasonable. For the denominator thing, I was wrong. the equation is Vin(1.1V) = ADC/1024AVcc(5V) since it reads "1.1V reference against AVcc". That's equivalent to AVcc = 1.11024/ADC = 1126.4/ADC.

Regarding the use of delay(2) to allow AREF to settle, how long you actually have to wait depends on the size of the capacitor from AREF to ground, as well as the drive capability of the new source. I've observed changing MUX from 1.1 to Vcc settles faster than from Vcc to 1.1.

Without doing per-board calibration, the value this yields is inaccurate to the point of being useless.

@Boann It's precise enough to detect whether the Arduino is powered by a USB port or a Li-ion battery, so it's certainly not useless. If you need accurate measurements, Arduino is certainly the wrong hardware.

Per https://www.gammon.com.au/forum/?id=11497&reply=2#reply2 I measured my bandgap voltage as 1.082 with an void setup (){analogReference (INTERNAL);analogRead (A0);}

The Nano has an ATMega328P MCU, which has an internal 1.1V reference voltage.
You use analogReference() to change the reference voltage that analogRead() compares the analog inputs against.
You will need to use a voltage divider to ensure that your maximum possible supplied voltage ends up being no higher than the 1.1V reference.
You'll still need to use an analogInput pin.

If you do this, you will make the resistance reading dependent on the supply voltage, which is what the OP wanted to avoid in the first place.

I see. You are correct; I was only solving the problem of how to compute the supply voltage, but with the supply voltage known, the resistance reading for the thermistor can be calibrated in software.

What Edgar was saying is that the thermistor measure is ratiometric, so using a ratiometric way of measuring the thermistor voltage the supply voltage perfectly cancel out. If you use the 1.1V reference you will have to make more calculations and will have a less precise measurement

Hi, my intention was to know the supply voltage without making the system complicated. I think the value of the voltage doesn't matter as @frarugi87 suggested the two voltages cancel out. If it were not so high it generates tremendous heat and break parts or so low it can't be measured, it's fine.


text:
Uploading sketch problem
I just plugged my arduino and click upload, it shows this error:
Arduino: 1.8.5 (Windows 7), Board: "Arduino/Genuino Uno"

Sketch uses 948 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified.

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

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Are you sure you board is appearing as COM1?

it was showing COM4

either you are already using the serial port or you just didn't select the port from the arduino "Tools>port"
you can always check your device's communication port using the device manager.

thanks for your precious time,,, the problem was selecting a right port. thanks alot

In the Arduino IDE check for the available ports. Be sure that the COM Port on Windows or ACMO port on Linux based OS is selected.
If the problem continues then check if the port is allowed in Windows and Linux.


text:
Problem with a seven segment display. The segments blink then turn off
I can't figure it out what is the problem with my circuit, the segments turning on for sec and then they are turning off for good.
I tried to connect to GND instead of the 5 V but then, nothing happened.

My code:
void setup() {
  for (int pin = 2 ; pin < 9 ; pin++){ // setup pins 2 – 8 to be output
    pinMode(pin, OUTPUT);
  }

  for (int pin = 2 ; pin < 9 ; pin++){ // turn on pins 2 - 8
    digitalWrite(pin, HIGH);
  }
}

void loop(){}

Working simulation demo

How do you expect a LED to light up if you put 5 V on anode and cathode?

You are also missing the current limiting resistors.

@gre_gor. Thanks. I updated my question. Can you take a look?

There are two types of 7 segment displays: common anode and common cathode. Which do you have? Depending on the type, you must connect the COM pin to 5V and all the segment pins via a resistor to GND to light them up (common anode type). Else reversed (COM to GND, segments to +5V over a resistor)

The first thing to understand is how to connect the 7 segment display to your Arduino. The common anode pin connects directly to 5VDC. Each "segment" connects to the Arduino through a current limiting resistor (1k ohm is a good value to start with).

To turn a segment on, you supply a ground to it (through the resistor of course). Change: digitalWrite(pin, HIGH) to: digitalWrite(pin, LOW) in your sketch to turn on the segments.
I'm sure there are plenty of tutorials on the internet showing one resistor on the common anode input, but that is not the correct way to drive the display. Think about what happens when you display the number 1 VS the number 8. Changing the number of segments drawing power from the single resistor will vary the intensity of the display. The number 1 will be far brighter than the number 8.

Make sence. You are right, all of the tutorials are using only 1 resistor. I will try it.. Thanks!

There are two reasons the tutorials might show a single resistor on the common cathode or anode:  (1) They just accept the fact that an 8 will be a little dimmer than a 1--that might be acceptable for a quick hack.  (2) They illuminate one segment at a time, essentially blinking the segments fast enough that they seem to be lit steadily, which you can do from the microcontroller if it's not too busy doing other work.  There are also peripheral drivers that can do this type of time multiplexing.

Thanks! It was a good explanation! Another thing I noticed that there are  2 types of 7 segment display based on Anode and Cathode. Depends on the type I need to connect it to 5v / GND. Right?

@MoshFeu - Yes, there are common anode and common cathode displays available. Here is a tutorial that does a good job of explaining the differences: https://www.electronics-tutorials.ws/blog/7-segment-display-tutorial.html

With foregood you mean broken probably.
I don't see any resistor in your circuit, probably the LEDs are broken.
I'm afraid you have to use a new segment LED, and follow:
Arduino Example
Especially read this fragment:
Current-limiting Resistors

Don't forget that the display uses LEDs, so you should use
  current-limiting resistors in series with the digit pins. 330 ohms is
  a safe value if you're unsure. If you use current-limiting resistors
  on the segment pins instead, then open up the SevSeg.h file and set
  RESISTORS_ON_SEGMENTS to 1 for optimal brightness.

Ok. I updated my circuit. Can you take a look? Thanks!

Did you also follow the arduino example first? Because if that doesn't work, your segment display is broken.


text:
How to measure CO2, Ammonia and Detect Smoke using MQ135?

Setup Info:
MQ135 + Arduino+16x2LCD+ESP8266+ThinkSpeak.
Hi All, I have just bought a MQ135 . I started arduino basics with LED blinking , interfacing and then started with my real project.
e
I have seen in the data sheet of MQ135 that it can measure Ammonia, Sulfide,CO2 and Benze steam. It can also be used to detect smoke and alert.
But in the Arduino uno Serial monitor, I can see only one value 408.
Now, I dont know how to differentiate it in all different values of required gases and trigger smoke alarm
Also, my friend suggested to calibrate this sensor for which I found really good material and started with 24 Hours on test after dumping a code to read data from it.
Now I read 1836 which was 1795 , about half an hour back.
Kindly reply and let me know what info or input is required from My side.
This is my first of my many uno projects to come.
Regards,
Sillicon
https://forum.arduino.cc/index.php?topic=535401.msg3649205#msg3649205

you already posted at forum.arduino.cc .... why are you posting again here?  ..... you have not asked a specific question.

Yup, I intend to notify the same and look for unique solution to solve this problem

Now, I dont know how to differentiate it in all different values of required gases and trigger smoke alarm

This sensor does not differentiate between the various gases that it is sensitive to.

I dont recollect but I have seen coders showing off different values of CO2 , Ammonia on a 16X2 screen using MQ135.

If you’ve seen it, show it.

https://www.youtube.com/watch?v=GT8dNNRWNOY   Visit this please

I watched the video. The fact that values are displayed for different gases does not mean the values displayed are accurate. There are values shown for "Smoke" and for CO when it's clear nothing is being burned/combusted.


text:
How can i get rid of the error "cannot convert 'String' to 'const char*'"
I want to get this code to recognise different commands and be able to parse the rest of the command, fore example I send "/sleep 5", and it will sleep for 5 seconds. However, I keep on getting this error "cannot convert 'String' to 'const char*'". here is my code:
#define maxCommandLength 64

String commands[] = {"/test", "/say", "/reset", "/sleep"};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Power on.");
}
char serial[maxCommandLength];
boolean valid;
void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Clearing command buffer(char 'serial'");
  for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
    serial[i] = ' ';
  }
  if (Serial.available()) {
    Serial.readBytesUntil(' ', serial, maxCommandLength);
  }
  if (serial[0] == '/') { //if it is a command
    Serial.print("Command recieved. \nCommand class:");
    Serial.println(serial);
    //test if command is valid
    for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
      valid = strcmp(serial,commands[i]);
      if(valid){
        break;
      }
    }
    //execution of command
    Serial.readBytesUntil(' ', serial, maxCommandLength);
    //.......
  }
}

there is no reason for command to be a String array. Instead make it a const char**:
const char** commands = {"/test", "/say", "/reset", "/sleep"};

I found that yours wouldn't compile, but this would:
const char* commands[] = {"/test", "/say", "/reset", "/sleep"};

@RowanRadosav-McRae  If this answers your question please accept the answer.

You can call the .c_str() method of String class returning (temporary) const char * representation of underlying string, in your case:
valid = strcmp(serial,commands[i].c_str());
//                               ^^^^^^^^

should work. Just make sure you don't keep the returned const char * around longer than necessary because by spec it is no guaranteed to remain valid.


text:
Parse long CSV file with esp8266
I'm trying to write a code for nodeMCU (esp8266 based board) to continuously calculate distance between GPS location and geographical coordinates written in a CSV file in SD. Originally I thought the best way to do it was to parse the file, save the longitudes and latitudes in two arrays at startup and, then, calculate continuously distances between arrays and coordinates taken from GPS. If distance is less than a value, an output warns me. There is only a "little" problem: the file contains 5500 coordinates and, so, it is impossible to allocate two arrays containing 5500 floats inside ram memory. Now I have thought two alternatives:
1) save the two arrays in flash memory that is, I know, a lot slower but also bigger
2) parse and calculate distance line by line continuously: in a loop I'll take the first line from SD, parse it, calculate distance between it and GPS location and, then do the same thing for second, third,... line. It requires the continuous access to SD and parsing but I don't have to use flash memory.
What is the best option in your opinion? Have you got alternatives or suggestions?
Thank you!!

I vote for 1). Is SD card faster then flash? Why not use file with SPIFFS?

I don't know if SD is faster than flash; probably it is. I have never used spiffs so I am a little bit scared on how to use it. Have you got suggestions?

Can I only save .txt files inside SPIFFS or also arrays? If I save, for example, a .txt file with coordinates, I need to reopen it and parse it again, will it be convenient? Maybe I can use option 2 with SPIFFS instead of with SD

I moved the comments to an answer

use an ESP32 instead: ~6X the usable RAM of the 8266

@dandavis at the end I decided to save file in SPIFFS, parse line by line and calculate distance line by line. It only takes 6 seconds at 160MHz; it's acceptable for what I want to do. Thank you anyway.

Instead od the SD card you can use the esp8266 file system SPIFFS. It uses the flash of the esp8266, which is connected at 40MHz as Quad I/O on newer systems.
To use SPIFFS you create a folder named data in your esp8266 sketch folder. You put the files in that folder and then you use the SPIFFS upload plugin.
In runtime use the SPIFFS library. It is similar to SD library.


text:
Motor shield leaves no pins accessible
I just bought a motor shield for my UNO, in the pic below:

Plugging it into the uno leaves no pins accessible on the board. I’d like to use it to build a robot car, but there’s nowhere to plug in the ultrasonic sensors. Do I need to solder some pins to the row at the top of the pic, or to the through-board holes on the right labelled A0-5?

According to tutorial, the shield uses almost all D pins. Free are pins 2 and 13. If servo is not used the pins 9 and 10 are free too. The pin 2 has the extra hole to solder a wire or a single pin header.
All analog pins are free and the shield enables to solder headers for them with additional header rows for 5V and ground for every A pin.
You can use analog pins as digital pins to connect the ultrasonic sensor.
Connection of I2C devices is possible on A4 and A5 pins.
The shield doesn't alow to stack a next shield, because it heats up.

yes. you can solder pin headers or contact wires directly to the shield. if use pinheaders it is easier to use the pins for other purposes.
In the case of using ultrasonic sensor you should have to use digital pins along with the 5v and ground pins of the shield.

Just avoid using already-used pins...

yes for sure @frarugi87

You can use a "Screw shield" between the motor shield and the Uno to make access to the unused pins easier.


text:
What is RSR 09TI chip?
There is a chip on Arduino UNO board which I can not find anything about. It is labeled RSR 09TI. It is placed near other power related components (see the image), but what is its purpose on the board?

Looks like the power regulator from +5V to +3.3V. See here component U2. Do you have a multimeter to measure the pins with regards to GND? There should be GND, +5V and +3.3V on there if I'm right.

@MaximilianGerhardt I don't have any UNO at hand right now, but I'd guess that the 5V -> 3V3 regulator is the guy at the lower right red corner on the image (looks like smaller brother of the 20V -> 5V guy)

I believe that is the dual op-amp that is used for both monitoring VIN to enable/disable the USB power, and as a buffer for the LED on pin 13.
In the schematic it's U1, and is an LM358.


text:
ESP8266 exception if sending TLS-POST-request for a couple of iterations
Problem
I send sensor measurements from an Arduino to -> AWS APIGateway -> Lambda -> CloudWatch, which works but only for a couple of minutes, then a stack-trace is shown and the program stops.
Request
I search for solutions, which ..

avoides the stack trace
recovers from the stack trace and starts over
speed up sending data (as close to once every second as possible!)
still collect data points during sending/receiving data (if I add the uncommented part during receiving the response nothing is happening) -> Parallel execution?

Tried so far
I so far observed that it may be a time issue, as with more "delay" it takes longer to receive the error. I really just want to write the data and therefore uncomment my code part which reads the APIGateway response, this way the error comes sooner. I already looked up the related issue on Github, but nothing solved my problem.
Specs

NodeMCU v2 including ESP8266
LM393 noise sensor
MacBook for development

The bare output:
...
Request: { "id": "S3", "noise": 41 , "ip": "192.168.178.20" }

Exception (29):
epc1=0x4020c612 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000004 depc=0x00000000

ctx: cont
sp: 3fff0010 end: 3fff0530 offset: 01a0

>>>stack>>>
3fff01b0:  00820000 00000082 3fff57cc 40219652
3fff01c0:  3ffef4b0 3fff5f44 3fff57cc 4021984c
3fff01d0:  3fffba7c 00000208 3fffba7c 40100670
3fff01e0:  00000104 0000b018 00001603 00000042
3fff01f0:  00000040 00000082 3fff7dd4 40219b65
3fff0200:  00800000 00000080 00000000 00000041
3fff0210:  00000040 0000003f 3fff6164 00000041
3fff0220:  3fffb664 3fff7dd4 3fff6164 3fff6f34
3fff0230:  3fffbb78 ffffffff 3fff5f44 40204c04
3fff0240:  00000040 3fff5f44 3fff7dd4 3fff5f44
3fff0250:  00000040 3fff5f44 3fff7dd4 4021a69f
3fff0260:  3fff67b4 0000003f a5c6bfaf 00000001
3fff0270:  3fff5f44 3fff6a04 3fff7dd4 00000001
3fff0280:  00000010 3fff5f44 0000000f 4021a8f4
3fff0290:  3fff6164 3fff9b1c 0000000f 00000001
3fff02a0:  00000001 3fff68bc 3fff3872 402196f8
3fff02b0:  00000100 3fff96fc 3fff3847 00000000
3fff02c0:  00000100 3fff96fc 3fff3847 4021ba7d
3fff02d0:  3fff0300 00000000 000000d0 00000030
3fff02e0:  b9a842ca 3fff68c8 3fff6170 00000004
3fff02f0:  3fff3841 3fffa794 3fff3841 40216778
3fff0300:  eb090303 4fed87e4 8f9aa767 9126663e
3fff0310:  ea791a25 f4e54d08 e2cb4f3b da7af472
3fff0320:  3d042744 7d12ab50 1cecee1e 42cab262
3fff0330:  3fff3841 00000004 3fffa794 40216c0d
3fff0340:  fa036a52 f16613d1 c13f331a 40213cd0
3fff0350:  f6658dd1 3fffc6fc 3ffef510 4020f835
3fff0360:  00000000 00000004 00000004 40203688
3fff0370:  00000012 00001192 00000064 40204bc4
3fff0380:  00000050 00000000 00000032 00000004
3fff0390:  3fff3841 00000004 3fffa794 00000004
3fff03a0:  3fff3841 00000004 3fffa794 40216580
3fff03b0:  d7c44818 00000131 00000131 0000002d
3fff03c0:  00000062 3fff3841 3fffa794 4021695c
3fff03d0:  00000016 3fff3874 3fffa794 401004d8
3fff03e0:  3fff0438 0000000e 00000010 3fff3044
3fff03f0:  4020343c 3fffa794 3fff0430 01000000
3fff0400:  3fff0438 00029c3d 3fffa794 402166e8
3fff0410:  3fffa794 3fff13ec 3fff14ec 3fff3044
3fff0420:  3fff241c 00029c3d 3fff14ec 40203e25
3fff0430:  3fffa794 3fff13ec 40204b4c 3ffef510
3fff0440:  00003a98 00003a98 00003a98 4020136f
3fff0450:  3ffef248 00000000 3fff241c 00000029
3fff0460:  000001bb 3ffe8a09 3ffef248 40204073
3fff0470:  000001bb 3ffef248 3ffe8a09 00000029
3fff0480:  000001bb 3ffef248 3ffe8a09 40204119
3fff0490:  40107158 ce653134 40107158 ce653134
3fff04a0:  3ffe8a09 3ffef248 3ffef240 402022d4
3fff04b0:  40244290 00000004 00000000 4023d5cd
3fff04c0:  4023d631 60000a00 00000000 3fffdad0
3fff04d0:  004b004b 004b004b 004b004b 004b004b
3fff04e0:  00000000 00000026 40238168 3ffef4f4
3fff04f0:  402013fa 0000001c 00000000 3ffef4fc
3fff0500:  3fffdad0 3ffef244 3ffef240 4020245c
3fff0510:  3fffdad0 00000000 3ffef4f4 40204b98
3fff0520:  feefeffe feefeffe 3ffef510 40100710
<<<stack<<<
⸮⸮؁⸮

The decoded stack trace:
Decoding 36 results
0x40219652: more_comps at crypto/bigint.c line 672
0x4021984c: alloc at crypto/bigint.c line 672
0x40100670: _umm_realloc at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/cores/esp8266/umm_malloc/umm_malloc.c line 1641
:  (inlined by) realloc at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/cores/esp8266/umm_malloc/umm_malloc.c line 1715
0x40219b65: regular_multiply at crypto/bigint.c line 672
0x40204c04: optimistic_yield at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/cores/esp8266/core_esp8266_main.cpp line 57
0x4021a69f: bi_barrett at crypto/bigint.c line 1289
0x4021a8f4: bi_mod_power at crypto/bigint.c line 1414
0x402196f8: trim at crypto/bigint.c line 672
0x4021ba7d: RSA_public at crypto/rsa.c line 254
:  (inlined by) RSA_encrypt at crypto/rsa.c line 288
0x40216778: send_client_key_xchg at ssl/tls1_clnt.c line 409
0x40216c0d: do_clnt_handshake at ssl/tls1_clnt.c line 123
0x40213cd0: mem_free at /local/users/gauchard/arduino/arduino_esp8266/origin/tools/sdk/lwip2/builder/lwip2-src/src/core/mem.c line 152
0x4020f835: pbuf_free_LWIP2 at /local/users/gauchard/arduino/arduino_esp8266/origin/tools/sdk/lwip2/builder/lwip2-src/src/core/pbuf.c line 1306
0x40203688: ClientContext::_consume(unsigned int) at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/libraries/ESP8266WiFi/src/WiFiClientSecure.cpp line 310 (discriminator 1)
:  (inlined by) ClientContext::read(char*, unsigned int) at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/libraries/ESP8266WiFi/src/include/ClientContext.h line 253 (discriminator 1)
0x40204bc4: __yield at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/cores/esp8266/core_esp8266_main.cpp line 57
0x40216580: do_handshake at ssl/tls1.c line 2007
:  (inlined by) basic_read at ssl/tls1.c line 1483
0x4021695c: do_client_connect at ssl/tls1_clnt.c line 168
0x401004d8: malloc at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/cores/esp8266/umm_malloc/umm_malloc.c line 1668
0x4020343c: SSLContext::_delete_shared_SSL(SSL_*) at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/libraries/ESP8266WiFi/src/WiFiClientSecure.cpp line 310 (discriminator 1)
0x402166e8: ssl_read at ssl/tls1.c line 2007
0x40203e25: SSLContext::connect(ClientContext*, char const*, unsigned int) at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/libraries/ESP8266WiFi/src/WiFiClientSecure.cpp line 310 (discriminator 1)
0x40204b4c: esp_yield at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/cores/esp8266/core_esp8266_main.cpp line 57
0x4020136f: delay at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/cores/esp8266/core_esp8266_wiring.c line 51
0x40204073: WiFiClientSecure::_connectSSL(char const*) at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/libraries/ESP8266WiFi/src/WiFiClientSecure.cpp line 310 (discriminator 1)
0x40204119: WiFiClientSecure::connect(char const*, unsigned short) at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/libraries/ESP8266WiFi/src/WiFiClientSecure.cpp line 310 (discriminator 1)
0x40107158: sntp_get_current_timestamp at ?? line ?
0x40107158: sntp_get_current_timestamp at ?? line ?
0x402022d4: loop_send_post(int) at /var/folders/ld/dws59xv93p15208nvrw7tt9w0000gn/T/arduino_modified_sketch_158237/HTTPSRequest.ino line 86
0x40244290: pm_wakeup_init at ?? line ?
0x4023d5cd: test_tout at ?? line ?
0x4023d631: test_tout at ?? line ?
0x40238168: system_adc_read at ?? line ?
0x402013fa: __analogRead at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/cores/esp8266/core_esp8266_wiring_analog.c line 33
0x4020245c: loop at /var/folders/ld/dws59xv93p15208nvrw7tt9w0000gn/T/arduino_modified_sketch_158237/HTTPSRequest.ino line 52
0x40204b98: loop_wrapper at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/cores/esp8266/core_esp8266_main.cpp line 57
0x40100710: cont_norm at /Users/lony/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/cores/esp8266/cont.S line 109

The sketch/code I use:
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>

static const String         SYSTEM_NAME = "S3";

static const char*          WIFI_SSID = "SSID...";
static const char*          WIFI_PASSWORD = "PW...";
static String               local_ip;

static const char*          TARGET_HOST = "host.com";
static const int            TARGET_PORT = 443;
static const String         TARGET_URL = "/v1/noise-data-receiver";
static const char*          TARGET_SSL_SHA1_FINGERPRINT = "8D ....2"; // To retrieve use web browser

static const int            BAUD_RATE = 9600;
static const int            PIN_SENSOR = A0;
static const int            PIN_LED = LED_BUILTIN;

static WiFiClientSecure     client;

static const int            THRESHOLD_NOISE = 100;
static int                  level = 0;

static const unsigned long  REFRESH_INTERVAL = 1000; // ms
static unsigned long        lastRefreshTime = 0;

void setup() {

  pinMode(PIN_LED, OUTPUT);
  Serial.begin(BAUD_RATE);
  setup_wifi();
}

void loop() {

  // Fetch noise level
  digitalWrite(PIN_LED, LOW);
  level = analogRead(PIN_SENSOR);
  digitalWrite(PIN_LED, HIGH);

  // Send HTTP POST request (every s)
  if(millis() - lastRefreshTime >= REFRESH_INTERVAL) {
    // Send request
    loop_send_post(level);

    lastRefreshTime += REFRESH_INTERVAL;
  }
}

/*
 * LIBS
 */

void setup_wifi() {

  Serial.println();
  Serial.println();
  Serial.print("Connecting system [" + SYSTEM_NAME + "] to WIFI ");
  Serial.print(WIFI_SSID);

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.print("Connected - ");

  local_ip = WiFi.localIP().toString();
  Serial.print("IP address: ");
  Serial.print(local_ip);
  Serial.println();
}

void loop_send_post(int level) {

  // Connect
  if (!client.connect(TARGET_HOST, TARGET_PORT)) {
    Serial.println("connection failed");
    return;
  }

  // Speed up sending
  client.setNoDelay(true);

  // Verify TLS
  if (!client.verify(TARGET_SSL_SHA1_FINGERPRINT, TARGET_HOST)) {
    Serial.println("certificate doesn't match");
    return;
  }

  // Send
  String body_json = "{ \"id\": \"" + SYSTEM_NAME + "\", \"noise\": " + String(level) + " , \"ip\": \"" + local_ip + "\" }";
  client.print("POST " + TARGET_URL + " HTTP/1.1\r\n" +
               "Host: " + TARGET_HOST + "\r\n" +
               "Connection: close\r\n" +
               "User-Agent: ESP8266\r\n" +
               "x-api-key: GEeGwazU1Ia2h6rZH6e0y4jwlxhjVurT9OWbOed4\r\n" +
               "Cache-Control: no-cache\r\n" +
               "Content-Type: application/json\r\n" +
               "Content-Length: " + body_json.length() + "\r\n" +
               "\r\n" +
               body_json);
  Serial.println();
  Serial.println();
  Serial.println("Request: " + body_json);

//  // Wait for response
//  unsigned long timeout = millis();
//  while (client.available() == 0) {
//
//    if (millis() - timeout > 5000) {
//      Serial.println(">>> Client Timeout !");
//      client.stop();
//      return;
//    }
//  }
//
//  Serial.println("Response: ");
//  while(client.available()){
//    String line = client.readStringUntil('\r');
//    Serial.print(line);
//  }
}

Can you please move the declarion of your WiFiClientSecure client in your loop_send_post function to force the destruction of that object at the end of the function? Sounds like your client leaks memory because the session is never closed properly.. Maybe try calling client.stop() after sending your request, too?

It is already running more stable thank you. Still there are delays in the execution. Do you know if there is a tool to analyse memory leaks more detailed?

1 second to do a TLS handshake with huge RSA certs is kinda hard on your ESP8266, so I would not expect new sessions to be established that fast. If you want less delay you should .connect() in your setup once and use Connection: keep-alive to POST as many times as possble before re-establishing the connection (and handshake). Regarding memleaks: You can print the amount of available heap memory anytime by using the ESP.getFreeHeap() function.

If you can fully solve this problem you should post an answer yourself afterwards to close the question

Will do but so far I only succeeded running the job consistently by moving the client into the function. Everything else needs another week.


text:
Using time function in arduino
how to get exact timestamp of a sensor reading and compare it with other sensor values in arduino?
Ex: Get the time of low reading of LDR and compare it

You see that word in the tag that you chose? That's the name of the function you want.

You should clarify 1) what do you mean by exact (you need to specify the resolution needed), 2) what kind of sensors you are using (particularly how long does it take them to make a measurement) and 3) if you have a target, the accuracy you need (accuracy != resolution)

Are you after a human readable timestamp (eg. 17:53:43) for logging etc. or are you after a machine timestamp (eg. 42750 ms after powerup)? If the machine timestamp is fine then use millis() as others have suggested.

@nuwankarunarathna Really more details are needed to answer this question.

i want to get two readings from two ldr sensors and need to have the exact time that ldrs are gone low.(low light condition). this has to be done over multiple times and i should have the capability to compare the values

As Majenko said you can use the millis() keyword.
Unless millis is not accurate enough. In that case you can use micros(), but this overflows every 70s if I'm correct, but you can offset it against millis().
If you need to compare two values, what you can do is:

get millis()
get micros()
read sensor data (optimize if needed)
get micros()

Average the difference of the micros, and add it to millis, and you have the average time for the sensor data readings.
Of course if it doesn't matter that all sensor data is read at approximately the same time, you can use millis() for each sensor data reading and work with those values.

Why should you take the aveage timestamp of the measure and not the beginning or the end? I think that the beginning is more consistent and more appropriate (usually you acquire and then elaborate, so the actual measurement is closer to the beginning rather than the end)

@frarugi87 I also would use the start, but if you need the one time stamp for multiple measurements, the 'average'  might be more applicable.

since arduino code is in a loop how can i exactly know the time

You first get the time with millis(). Than immediately afterwards you do the measurement. Assumign the measurement takes very little time, you can use the millis() value as 'timestamp'.


text:
How to re-solder the resistor in order to reprogram the Atmega8U2
As I see here I need to reprogram the ATMEGA8u2: https://www.arduino.cc/en/Hacking/DFUProgramming8U2 I need to solder a 10k resistor into a specific place.
In a previous attempt I did that and resulted the following marks:

So How I can resolder the resistor in order to reprogram the atmega8u2?

Ouch. Looks like your iron was too hot and you lifted one of the pads.  Recoverable if you are careful.

Have you tried without the resistor? The guide seems to suggest that that resistor is only needed on the rev.1 version of the UNO.

you have to carefully scrape away the solder mask before soldering components. ... the solder mask is the blue and white "paint". ... it is covering the pads. ... scrape a small area on the corner of the board as a test.

Looks like you ripped a pad off. To prevent that in the future, try using more flux and dropping the temp (Max around 320*C/610*F). The iron shouldn't be in contact with the board for more than about 3 seconds. No force should be necessary to remove components.
Not to worry though. Common beginner's mistake and not too hard to fix.
To prep this for repair:

Gently clean the area up with 91% isopropyl alcohol and cotton swabs.
Carefully scrape away the solder mask (blue paint) on what's left of the copper trace all the way back to the via (little hole). Try to remove all the solder mask from the via. Straighten and flatten the pulled up trace.
Clean, flux, and tin (apply as thin layer of solder) to the trace and remaining pad. Filling in the via is OK as it will give better surface area to attach the repair.
Flux and solder the resistor to the remaining pad to keep it in place and properly aligned for the repair.

To repair the damage:

We need to bridge the gap created by the damaged pad. A globby solder bridge may work, but wire is much better.
Find a piece of thin gauge solid core wire (30-22AWG. Some 24AWG from an ethernet cable would do fine).
Orient the wire so that it's directly over the remaining trace and also making contact with that end of the resistor.
You can trim it to size now or after soldering. It may be easier to keep in place if you trim it after soldering as long as you have some fine flush cut pliers. Either way, leave enough that it covers the entire cleaned and tinned portion of the trace.
Flux and solder the wire to both the resistor and trace. This will complete the circuit.
Clean again with alcohol. Let dry. Test the board.

Give this Adafruit article a read. I've got extensive professional soldering training and endorse it fully as the best beginners soldering guide I've found.

Does 70% Alcohol do the job?

@DimitriosDesyllas 70% Alcohol means 30% water. It will clean and remove flux, but if any gets under a component it will take much longer to dry and you'll have conductive corrosive flammable liquid risking your circuit. I definitely would not recommend it. 91% Isopropyl is readily available and cheap at any drug store right next to the 70%.

I woinder If I can use another arduino to program the AtMegaU8 without the need for much solder.

@DimitriosDesyllas You can use another Arduino to program the AtMegaU8. You will need to connect directly to the ICSP header closer to the USB port and "AREF" (if your board version has one). Not completely sure how critical that resistor is going to be though.

That pad connects to the same place as the circuit used for resetting the ATMega328P chip - that is, pin D7 on the ATMega8U2.
It just pulls the pin PD7 down to ground with more "force" than the internal pullup of the pin itself.
You can attach that resistor to anywhere along that line, and probably the most convenient place would be to the ATMega16U2 side of capacitor C5.
That capacitor has one end linked to the RESET pin on the main Arduino header, so you can connect a DMM in continuity test to that pin and "buzz out" each capacitor until you find the one point where it beeps (I think it's one that's right next to "Reset EN").
Carefully solder your resistor to the opposite side of the capacitor to the side that beeps (the side nearest the ATMega8U2 chip, probably), and connect the other end of the resistor to GND on one of the main headers.
By the way - get yourself a flux pen and apply flux to where you are soldering before you start soldering. It should help you avoid these kind of problems in the future. Also get a proper temperature controlled soldering iron (I use 350C for mine most of the time) and some solder wick to help recover from solder messes.  All part of the standard EE's toolkit.


text:
Arduino UNO reprogram the MEGA8u2 using external programmer
As they say in https://www.arduino.cc/en/Hacking/DFUProgramming8U2 you need to solder a 10k resistor in order to reprogram/reset the MEGA8u2 chip on Arduino UNO but sometimes you may lack the needed tools.
Is there a way to reprogram the MEGA8u2 using an external programmer or an another arduino as a programmer?
My idea behind this is to use the ISP LAYOUT for ATMEGA8U2 in order to load the correct bootloader:

How is that easier than soldering in a 10K resistor?

Actually in my case I do not know if I can solder one: https://arduino.stackexchange.com/questions/50807/how-to-re-solder-the-resistor-in-order-to-reprogram-the-mega8u2

Sure you can. Solder in a 6 pin header and you can program the ATMega8U2 using any Atmel hardware programmer. It's just a standard MCU, after all.  I'm not sure how the DFU side of things works - whether it's built into the chip in ROM or not1, but if it's just a bootloader in flash your programming may wipe it out stopping DFU from working in future. Not a problem if you can't get into DFU mode anyway.

1: The DFU is firmware stored in the "boot" region of the flash. As long as you don't erase or overwrite that region of the flash DFU will still function in future. Of course, you can also re-install the DFU firmware at any time you like.


text:
Arduino UNO(master read) + NANO(slave write) i2c buttons+stepper
First of all, I'm new to arduino. Check the EDIT line below the two codes.
I have connected motor shield to arduino uno. Connection between the two arduinos are A5 to A5, A4 to A4, 5V to 5V and GND to GND. I have a stepper connected to UNO, and a button connected to nano.
EDIT5: I deleted the messy previous codes, the question was answered.
However, I cant get the steppers to rotate(they only vibrate). Any advice is appreciated. The code right now is:
Master
#include <Wire.h>
#include <AFMotor.h>
//define steppers
AF_Stepper motor1(48, 1);
AF_Stepper motor2(48, 2);

//define variables
int x = 0;
int y = 0;

void setup()
{
  Wire.begin(5); //begin i2c communication
  Wire.onReceive(receiveEvent);
  motor1.setSpeed(10);  // 10 rpm
  motor2.setSpeed(10);  // 10 rpm

  motor1.release();
  motor2.release();
  delay(1000);
}

void loop()
{
  delay(500); // wait 0.5 second
}

void receiveEvent(int howMany)
{
    //read x,y from slave
    x = Wire.read();
    y = Wire.read();

    if (x == 1) //stepper1 rotate forward
    {
      motor1.step(100, FORWARD, SINGLE);
    }
    else if (x == 2) //stepper1 rotate backward
    {
      motor1.step(100, BACKWARD, SINGLE);
    }
     else if (y == 1) //stepper2 rotate forward
    {
      motor2.step(100, BACKWARD, SINGLE);
    }
     else if (y == 2) //stepper2 rotate backward
    {
      motor2.step(100, BACKWARD, SINGLE);
    }
}

Slave
#include <Wire.h>

//define buttons
const int button1 = 2;
const int button2 = 3;
const int button3 = 4;
const int button4 = 5;

//define state of buttons
int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;

//define variables
int x = 0;
int y = 0;

void setup()
{
   //start i2c communication
   Wire.begin();
}

void loop()
{
  //read state of buttons
  buttonState1 = digitalRead(button1);
  buttonState2 = digitalRead(button2);
  buttonState3 = digitalRead(button3);
  buttonState4 = digitalRead(button4);

    //if button1 is pressed,send x to master
    if(buttonState1 == HIGH){
      x = 1;
      Wire.beginTransmission(5);
      Wire.write(x);
      Wire.endTransmission();
    }
    //if button2 is pressed,send x to master
    else if(buttonState2 == HIGH)
    {
      x = 2;
      Wire.beginTransmission(5);
      Wire.write(x);
      Wire.endTransmission();
    }
    //if button3 is pressed,send y to master
    if(buttonState3 == HIGH){
      y = 1;
      Wire.beginTransmission(5);
      Wire.write(y);
      Wire.endTransmission();
    }
    //if button4 is pressed,send y to master
    else if(buttonState4 == HIGH)
    {
      y = 2;
      Wire.beginTransmission(5);
      Wire.write(y);
      Wire.endTransmission();
    }
}

slave uses onReceive. your "Slave" code is master code

@Juraj Yeah, I realised it. Don't you know how is it possible to make it work ?

@RóbertPollák What did you realise? If you realised, can't you fix it? In any case Arduino has a tutorial for when you want to transfer data from the slave to the master

@frarugi87 That tutorial is great, I followed the steps and worked. However, the problem was when I wanted to create what I wrote above. Button to control the stepper.

Well, instead of sending "hello" you have to send the button status. From the other part, instead of printing it you have to use it properly. Try modifying first the servo to send you '0' or '1' and the master prints it on the serial, then when it works modify the master to interprete it as a command. If you have problems (but I think you won't, since you already did it) you can ask showing what you did in the meantime

I see a lot of bugs everywhere, but I am totally confused which code that you are going to use. First decide which Arduino board should be the master and which one the slave. A master can send data to a slave or request data from a slave.

@Jot I was told not to delete the previous codes, so I just make an edit. My uno is the master reader, nano is the slave writer. I think I almost figured it out, I'm just stuck at a point, where if I write a char I predefined, the stepper turns on, but I can't make it run with the button.

About "edit 3", the slave at address 8 and the master polls the slave via i2c. That is okay. The master can request two bytes and read two bytes (for example as HIGH or LOW) and omit the Wire.available. The slave should always write two bytes, just write 'buttonState1' and 'buttonState2'. No if-statement needed.

I have an important question: are you using an extra Arduino board because there are not enough pins available for two buttons? Please don't do that. First of all, you should buy a better driver board. Second, all the analog pins of the Arduino board are digital pins as well. If you have no servo motor connected to the shield, pin 9 and 10 can be used as well. There is also pin 2 and 13 which are not used. That means with that shield you have still 10 pins for buttons! (or 8 when using  two servo motors).

@Jot is there a way we can send DMs instead of commenting? It would make this thing faster.
Anyways, yes I use another board because not only there are not enough pins for the buttons, but I want to add bluetooth module.

There is a chat (never used it), but so far this is all about Arduino and meaningful.

Could we somehow set up that chat?
I couldn't figure it out how to set up the buttons with analog pins. My code is there, I updated my code, could you help me with that, so I wouldn't need to use I2C so far.

To use an analog pin as a digital pin, use the name of the pin: pinMode(A0, INPUT), digitalRead(A0), and so on. Or in your sketch, for example: const int button4 = A0; You are receiving two bytes via i2c, so you must send two bytes. If that is not what you want, then you have to forgot about programming code and first define the data that will be transmitted via i2c. Describe the protocol of the data. I'm kind of lost, since you are trying many things without a direction to go to. Don't forget to use @Jot, or else I won't be notified.

By the way, how you know which motor shield do I have? I use two steppers so I might be able to do that without i2c, but I want to use bluetooth module to control the steppers wirelessly. @Jot

A little guessing and the "AFMotor.h" give it away. The newer Adafruit Motor Shield uses a different name, so this must be the old one. If you are planning to use SoftwareSerial together with i2c, then you get into new problems. The i2c needs interrupts to run smooth, and the SoftwareSerial takes over the Arduino to do its work.

Well, I've got this one. Could I use any newer library? I just want to connect a bluetooth module(dont know which one yet) to nano(slave) to control the steppers. By the way, the 9V battery wasn't new, I'm going to buy one right now, I'll be back soon and tell you if that was the problem. @Jot

@Jot The new battery still won't rotate just vibrate. I guess the problem would be somewhere else I can't locate.

The thing is, its rotating without i2c, but only vibrates with. @Jot

A 9V battery is for smoke detectors, you can not use it with an Arduino board and certainly not for motors. That old motor driver needs that old library, and the new motor driver module has its own library. The bluetooth works best with a hardware serial port. You are running so fast into every possible problem, is there someone who can help you at your place?

@Jot not really that's the problem. Why is this a thing that without i2c its working correctly, with i2c, its not. That's why I wanted to get into chat with you somehow if you have time for that.

You might request to delete this question and start a new one. Tell what your goal is and ask how to achieve that, and tell what hardware you already have. This website is for questions and answers, perhaps forum.arduino.cc is a better place.

That's what I'm going to do! @Jot thanks everything once again!

There are many ways to do this. The master could be the central unit which makes all the decisions, or the slave could preprocess the information.
It is best to start with a single byte to make it work. But I have made examples for two bytes anyway.
The next examples requests two buttons via i2c. You can change the HIGH and LOW into an integer value, but this is a start to make it work.
Master (without checking)
void loop()
{
  Wire.requestFrom(8,2);    // request 2 bytes from slave device #8
  int button1 = Wire.read();
  int button2 = Wire.read();

  Serial.print("button1=");
  Serial.println(button1 == HIGH ? "HIGH" : "LOW");

  Serial.print("button2=");
  Serial.println(button2 == HIGH ? "HIGH" : "LOW");

  // Some delay is needed, to prevent a 100% i2c bus load.
  // Perhaps 1 ms is enough, now 500 ms for testing.
  delay(500);
}

Master (with checking)
void loop()
{
  Wire.requestFrom(8,2);    // request 2 bytes from slave device #8
  if(Wire.available() == 2)   // are 2 bytes received ?
  {
    int button1 = Wire.read();
    int button2 = Wire.read();

    Serial.print("button1=");
    Serial.println(button1 == HIGH ? "HIGH" : "LOW");

    Serial.print("button2=");
    Serial.println(button2 == HIGH ? "HIGH" : "LOW");
  }
  else
  {
    Serial.println("The slave was not found");
  }

  // Some delay is needed, to prevent a 100% i2c bus load.
  // Perhaps 1 ms is enough, now 500 ms for testing.
  delay(500);
}

Slave (very simple)
void requestEvent()
{
  buttonState1 = digitalRead(button1);
  buttonState2 = digitalRead(button2);
  Wire.write( (byte) buttonState1);
  Wire.write( (byte) buttonState2);
}

Slave (advanced, update button state in the loop)
#include <Wire.h>

const int button1Pin = 2;
const int button2Pin = 3;

// Variables that are used in a interrupt and also outside
// that interrupt must be declared as volatile.
// Then the compiler knows that they can change at any moment.
volatile byte buttonState1;
volatile byte buttonState2;

void setup()
{
  pinMode(button1Pin,INPUT);
  pinMode(button2Pin,INPUT);
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
}

void loop()
{
  // keep the variables updated with the latest information.
  buttonState1 = (byte) digitalRead(button1Pin);
  buttonState2 = (byte) digitalRead(button2Pin);
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent()
{
  // send the two bytes.
  Wire.write(buttonState1);
  Wire.write(buttonState2);
}

Avoid comments like "+1" or "thanks", but still, thank you @Jot.
Anyways, I managed to write a code that's running, but the steppers are just vibrating, not rotating. Any solution for it?

That is an other problem. Try to make a small test sketch (without using the i2c bus and the other board) to test it. It means there not enough power or the wrong driver or electrical noise that backfires into the arduino board. You know that the motor shield that you are using is the worst, cheapest, weakest motor shield there is? It can drive only a very, very, very small toy motor. Maybe not even that.

When I used it without i2c bus, only with the shield and one button(because only pin D2 is free on that shield and analog pins) it was working okay, but now, with this setup, its not working.

You could add a check in the receiveEvent if the howMany == 1. Since a single byte is expected it should be 1. Calling the motor.step from an interrupt function might cause problems. If possible, you should do such things in the Arduino loop(). Don't fill the i2c bus with 100% load. Add a delay in the master Arduino. Start at least with 100 ms. Work cleaner! with the code and explanation. You have now called the master the slave and the other way around.


text:
analog read only once a time
I was working on a school project in where i need to analog read form A0 and test if my value is bigger than some boundary (500 for example) to return 0 or 1
well with a simple code in an infinity loop
this will keep returning 0000000 and 1111111 for infinity
but need 1 only once when my analog value passes from 900 to 300 for example and I dont need once when It stays at 300.
and the same problem for 0 : I need 0 only once when it passes from 300 to 900 and not 0 from staying at 900
thanks for help in advance

Store the current read value AND the previous value and check if a border has been crossed.
E.g.
if Previous value < 500 AND current value >= 500
   Going from 0 to 1 -> return/send 1
else if Previous value >= 500 AND current value < 500
   Going from 1 to 0 -> return/send 0

However, to make it more complicated, you might have debouncing effects, e.g. what if the value moves for some time around 500 to go to 200... It will still result in possibly many 0 and 1 boundary changes.
You can fix this easily by using two different value: by checking going lower < 490 and going higher > 510 (or any other appropriate value. Or use a debounce mechanism where it should be below or above the 500 value for a minimum (but short) amount of time.

What you are talking about is threshold with hysteresis.  It's basically how the digital inputs work using schmit triggers.
+------+ 1023
| HIGH |
+------+ 900
| DEAD |
+------+ 300
| LOW  |
+------+ 0

What you want to do needs to be done in two distinct sections:

Detect the incoming analog level, and
Control and record the status.

The first part is simple enough:
int val = analogRead(0);
if (val > 900) {
    // High
} else if (val < 300) {
    // Low
}

With that you have two blocks of code that are valid for the two bands you are interested in.  That is effectively like a button now - you have a "HIGH" and a "LOW" signal, just like digitalRead() gives you for a digital input.  Now you just need to couple that with some standard button toggling code.  That is - only change the status if the status actually should change.  And that's simple enough.  For example:
if (newStatus != oldStatus) {
    oldStatus = newStatus;
    // Do something just once
}

To expand that concept out, you get:
static bool enabled = false; // This is the saved status

int val = analogRead(0); // The incoming value

if (val > 900) { // A HIGH signal.
    if (!enabled) { // It's not already recorded as HIGH
        enabled = true; // Record it as a HIGH
        Serial.println("1");
    }
} else if (val < 300) { // A LOW signal
    if (enabled) { // It's currently HIGH, not LOW...
        enabled = false;
        Serial.println("0");
    }
}

And there you have it.  If it goes HIGH and it's not recorded as HIGH then it's a new HIGH.  If it goes low and it's not recorded as LOW then it's a new LOW.