text:
Programming custom Arduino Mega with Arduino Uno
I'm making a custom board with AtMega2560-16AU as MCU and CH340G as bootloader (schematic can be seen in the picture).  I have printed the custom PCB and soldered everything in place now I want to program the bootloader.

I connected my Arduino UNO with my custom board like shown in the fritzing schematic below. My custom pcb doesn't look like Arduino MEGA but the connections are the same.

I go to Arduino IDE and upload the ArduinoISP example (baudrate:115200) while choosing programmer as "Arduino as ISP".

And when I upload the example I get a response like this:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: reading input file "C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex"
avrdude: writing flash (4354 bytes):

Writing | ################################################## | 100% 0.68s

avrdude: 4354 bytes of flash written
avrdude: verifying flash memory against C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex:
avrdude: load data flash data from input file C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex:
avrdude: input file C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex contains 4354 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.53s

avrdude: verifying ...
avrdude: 4354 bytes of flash verified

avrdude done.  Thank you.

As far as I know so far there's no problem.
And now I move to step 2 which now requires me to switch the board to ArduinoMega from tools. And click burn bootloader.

When I click burn bootloader I get a response like this:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega2560
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
           flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0xffffff (probably .avr8x_mega) (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Now when I clicked burn the bootloader I got a response saying invalid signature.
So far I tried to:

Change baudrates and try the same steps.
Tried to change the avrdude.txt file. I tried to change the
signature that was searched for which I couldn't change it because
windows 10 wouldn't allow me even though I gave myself all the admin
permissions.

So as a solution to this signature problem people have put an electrolytic capacitor that has 10nF or 10uF value between GND and RST pins of the programmer Arduino.
Also when I tried this for the first time I got a value different than "Off" for oscillator in the 2nd step.
So what should I do? Do I need to change my oscillator and try again or do I need that polarized 10uF capacitor?
Sorry for poorly formatting this post. Thank you so much for reading. Any answers would be appreciated.

Please no capslock. Thats like shouting and its difficult to read

"10nF or 10uF".  10nF will not to the job.  If you've been testing with 10nF switch to 10uF an see what happens.

@timemage I haven't tried either of those. I'm asking if it would help at all.

Defeating the UNO's DTR reset mechanism is a necessity when using it as a programmer (arduinoisp.ino).  A 10uFcap between RESET and GND is a a way to do that.  In short, yes it will help.  It should have been mentioned in whatever tutorials and documentation you've been following.

A 10-100uF capacitor on the reset pin of the "master" Arduino prevents it from resetting when the Serial port is opened, which would interfere with the process of writing the bootloader to the Mega2560. There are other ways to prevent this, but this is one of the simplest.

@StarCat I tried both 10uF and 100uF capacitors (16V polarized electrolytic) they both didn't work. 10uF made it so that I couldn't upload sketches to UNO. 100uF didn't change anything but I could upload sketches.

Have you tried dedicated ISP programmer like USBasp or USBtinyISP? Have you tried Avrdudess to read out fuse settings and or just trying to detect the MCU to see if it still responses to ISP command?

@SimonVu14 No I haven't, thank you for your recommendation.

I finally found the problem with this board. I had a 22pF capacitor between RST and GND on the board I had ordered.
You should not have a capacitor there or it should be 100nF, values such as 22pF or 10nF will cause the board to malfunction and therefore you can't burn the bootloader.

I have not yet tried the 100nF cap but I soon will try and update the answer.


text:
How can I stop my servo looping when my sensor doesn't detect movement?
I have this project with my Arduino UNO where I want my servo motor SG90 to go full speed to 180 degrees when the PIR sensor sends HIGH value and go slowly back to zero when the value is LOW.
I have this code working where the servo goes full speed back to zero:
#include <Servo.h>

Servo myservo; //creates a servo object
int pos = 0; //variable to store servo position
//amount of time we give the sensor to calibrate(10-60 secs according to the datasheet)
int calibrationTime = 30;
//the time when the sensor outputs a low impulse
long unsigned int lowIn;
//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int pir = 12; //digital pin connected to the PIR's output
int pirPos = 13; //connects to the PIR's 5V pin

void setup() {
  myservo.attach(4); //attaches servo to pin 4
  Serial.begin(9600); //begins serial communication
  pinMode(pir, INPUT);
  pinMode(pirPos, OUTPUT);
  digitalWrite(pirPos, HIGH);
  //time for calibration

  Serial.println("calibrating sensor ");
  for (int i = 0; i < calibrationTime; i++) {
    Serial.print(calibrationTime - i);
    Serial.print("-");
    delay(1000);
  }
  Serial.println();
  Serial.println("done");

  //this waits until the PIR's output is low before ending setup
  while (digitalRead(pir) == HIGH) {
    delay(500);
  }

  Serial.print("SENSOR ACTIVE");
}

void loop() {
  if (digitalRead(pir) == HIGH)
    myservo.write(180);              // tell servo to go to position in variable 'pos'
  Serial.print("Motion detected!");

  if (digitalRead(pir) == LOW)
    myservo.write(0);              // tell servo to go to position in variable 'pos'
  Serial.print("Motion ended!");
}

I'd like the servo to go slowly back to zero, so I tried this :
#include <Servo.h>

Servo myservo; //creates a servo object
int pos = 0; //variable to store servo position
//amount of time we give the sensor to calibrate(10-60 secs according to the datasheet)
int calibrationTime = 30;
//the time when the sensor outputs a low impulse
long unsigned int lowIn;
//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int pir = 12; //digital pin connected to the PIR's output
int pirPos = 13; //connects to the PIR's 5V pin

void setup() {
  myservo.attach(4); //attaches servo to pin 4
  Serial.begin(9600); //begins serial communication
  pinMode(pir, INPUT);
  pinMode(pirPos, OUTPUT);
  digitalWrite(pirPos, HIGH);

  //time for calibration
  Serial.println("calibrating sensor ");
  for (int i = 0; i < calibrationTime; i++) {
    Serial.print(calibrationTime - i);
    Serial.print("-");
    delay(1000);
  }
  Serial.println();
  Serial.println("done");

  //this waits until the PIR's output is low before ending setup
  while (digitalRead(pir) == HIGH) {
    delay(500);
  }

  Serial.print("SENSOR ACTIVE");
}

void loop() {
  if (digitalRead(pir) == HIGH)
    myservo.write(180);              // tell servo to go to position in variable 'pos'

  Serial.print("Motion detected!");

  if (digitalRead(pir) == LOW)
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }

  Serial.print("Motion ended!");
}

The problem is with this code the servo does go slowly back to zero but then goes full speed back to 180 and again and again ....
Any idea? I'm a beginner in Arduino, so I assume it must not be that hard to figure out.
Thanks.

If (digitalRead(pir) == LOW) then you tell the servo to jump to 180 with this line: for (pos = 180; pos >= 0; pos -= 1)

I'd run your code through Tools/Auto Format in the IDE, which is something you should do before posting in the future, for the sanity of your readers, if not for your own.

Okay thanks for the tip guys !!

Don't set the pos to 180 in the (digitalRead(pir) == LOW) branch if you do not want it to repeatedly jump up to 180 for as long as the condition is true.
void loop() {
  if (digitalRead(pir) == HIGH)
     pos = 180;
  myservo.write(pos);              // tell servo to go to position in variable 'pos'

  Serial.print("Motion detected!");

  if (digitalRead(pir) == LOW)
    for (; pos > 0; pos -= 1) { // decay to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }

  Serial.print("Motion ended!");
}

Alternately, you could use pos as a state variable and simplify things:
void loop() {
  if (digitalRead(pir) == HIGH)
     pos = 180;
  elif (pos > 0 ){
     pos--;
     delay(15);
  }
  myservo.write(pos);
}

If pir is LOW, the OP's speed-controlled code will keep cycling between 180 and zero again and again.

"long as the condition is true" or maybe "as long as the input remains LOW".  I'm going to delete my previous comments above (and this one later), because with your good clarifications they're going to look more out of sync.

I pasted the code, works like a charm, thanks a lot to you two guys !!

It sounds like you should "accept" this answer.

source: Stack Exchange

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

sort: votes


text:
Issue with simple timer based on millis()
Sorry to bother but I am at my wits end. I'm experimenting with timers, and starting very simple. The following code is supposed to print the content of a variable each time an interval of time has passed, then update that variable. But for some reason I'm getting no output on the serial monitor.
I have used the serial monitor before on other projects without issue, so I'm not sure what the problem could be.
Is there any error in my code?
unsigned long previousMillis = 0;
unsigned long currentMillis = millis();
const long interval = 1000;

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

void loop() {
  if (currentMillis - previousMillis >= interval) {
    Serial.println(previousMillis);
    previousMillis = currentMillis;
  }
  else {
    ;
  }
}

//  previousMillis += interval;

Simple problem: You are not updating the currentMillis variable anywhere. Its value does not magically update, when you have once assigned the value of millis() to it. Insert currentMillis = millis() right at the start of the loop() function.

Thank you for your response. I thought it automatically updated with the latest value of millis() constantly. So it would only update at each iteration of the loop? If you would like to post this is an answer I can accept it if that makes any difference to you, because it is very helpful to me.

Since currentMillis is just a simple variable, it will not automatically update. In fact the initialization with millis() in global scope is unnecessary. Just initialize the value with 0. At the time, where the global variables are created, the time is 0ms anyways.
You need to update the currentMillis variable everytime, before using it. So just insert
currentMillis = millis();

right at the start of the loop() function.

Thanks again for your help.

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


text:
Arduino pull-up resistor not working
I made a circuit where when I press a button, a LED lights up using a pull-down resistor. But when I tried the same with a pull-up resistor instead, the LED remains off (whereas I expected it to be on by default and go off when I push the button). What is the problem?
Here is the circuit:

And here the code:
int BUTTON = 7;
int LED = 8;

void setup()
{
  pinMode(BUTTON, INPUT);
  pinMode(LED, OUTPUT);
}

void loop()
{
  digitalWrite(LED, digitalRead(BUTTON));
}

Is that LED the right way around? The cathode side or the more negative side is the one with the cut-off edge, and while it's really hard to see from those kinds of drawings, if looks like anode is drawn towards the ground there, so the wrong way around.

Try connecting the button to 5V, you have no signal transition. With a pull up the switch has to ground it. With a pull down the switch needs to drive it high.

@ilkkachu yes, I just displayed it incorrectly in the picture.

@Gil but the button is connected to 5V via the 10K resistor. As is shown in circuit diagrams online.

It is important where the other end of the resistor is connected.  If you want pull up connect it to Positive the switch to negative, if you want pulldown connect it to ground and the switch to positive.  Try this link it will help you understand: https://www.electronics-tutorials.ws/

@Gil but isn't that exactly what I did in the schematic? Resistor is connected to positive and the switch to negative. And the MCU between the resistor and the switch like in the circuit diagrams here.
Btw thanks for the link! Looks like a great resource.

The drawing looks good, except for the LED. The code looks also good. So, show us the picture of your real circuit on breadboard. There may be a chance that your breadboard's broken.


text:
How to make car turn 90 degrees?
I have an elegoo car model and am trying to make it turn 90 degrees whenever it gets to a 90 degree turn. This model has line tracing and it works fine on curved surfaces but doesn't work so on 90 degree turns.
    /Line Tracking IO define
#define LT_R !digitalRead(10)//connected to pin 10. Value is inverted
#define LT_M !digitalRead(4)
#define LT_L !digitalRead(2)

#define ENA 5//input to enable motor A. Controls speed
#define ENB 6//input to enable motor B
#define IN1 7//Control spinning direction of motor A. If one of them is high motor spin(an OR gate)
#define IN2 8//Same motor A
#define IN3 9//3 and 4 are for motor B
#define IN4 11

#define carSpeed 100

void forward(){ //car goes forward
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("go forward!");
}

void back(){ //car goes backwards
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("go back!");
}

void left(){ //goes left
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("go left!");
}

void right(){ //goes right
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("go right!");
}

void stop(){ //power is shut off
   digitalWrite(ENA, LOW);
   digitalWrite(ENB, LOW);
   Serial.println("Stop!");
}

void setup(){
  Serial.begin(9600);
  pinMode(LT_R,INPUT);//takes input from all the sensors
  pinMode(LT_M,INPUT);
  pinMode(LT_L,INPUT);
}

void loop() {

  if(LT_M){
    forward();
    while(LT_M);
  }
  else if(LT_R) {
    right();
    while(LT_R);
  }
  else if(LT_L) {
    left();
    while(LT_L);
  }

  else if (LT_M && LT_R && !LT_L) {
  delay(500);
  right();
  }

  else if (LT_L && LT_R && !LT_R) {
   delay(500);
   left();
    }

Your code is not complete. Sometime you use pins ENA and ENB with digitalWrite and sometimes with analogWrite. #define LT_R !digitalRead(10) is a macro definition: So, what is the meaning of pinMode(LT_R,INPUT); ;-)?  I wonder why parts of this program work.

PeterPaulKiefer is right with the pinMode statements. That will only configure either pin 0 or 1 as input. It cannot work as you wanted. Most likely you are profiting here from the fact, that at startup all the pins are already configured as inputs.

First: Your code as 2 problems:

As stated in the comments by PeterPaulKiefer, when you use
  pinMode(LT_R,INPUT);

That is not working as intended by you. LT_R is defined at the top as
  #define LT_R !digitalRead(10)

Thus the compiler will see
  pinMode(!digitalRead(10), INPUT);

digitalRead() will return zero or one, thus you are configuring pin 0 or pin 1 here (depending on the state of the sensor at startup). Instead you need to directly use the pin number (10) or use another define for the pin number itself. Your code only works, because all the pins are configured as INPUT (tristate) at startup of the microcontroller, so that they don't break something with a wrong signal. You got lucky there.

The last two else if statements are never executed:
  else if (LT_M && LT_R && !LT_L) {
      delay(500);
      right();
  }
  else if (LT_L && LT_R && !LT_R) {
      delay(500);
      left();
  }

The conditions here will first evaluate LT_M (in the first statement) and LT_L (in the second statement) respectively. Only if these are true, the rest of the expression will be evaluated. But you already checked for both of them being true above. When they are, the following else if statements don't get executed (thats the logic of if else statements). And if they are false, the code will also not be executed.
When you get to a 90° right corner, the middle and right sensor will trigger. Currently this will lead to the robot just keeping going forward.

So you need to change your code to actually check every every possible combination of the sensor states.
Also keep in mind, that a sharp corner needs way more turning, than a curve. Depending on the width of the line are the distance between your sensors, you might or might not be able to distinguish between those two cases. You should analyze, which sensor states you would have in which situations, write that down and then write code for every state. You could also put all sensor states into one single number, so that it is easier to check for it in the code. Something like this:
byte all_states = digitalRead(2) + 2*digitalRead(4) + 4*digitalRead(10);

Each combination will give you a unique number to work with. Effectively this stores the states of the sensors in one bit of the number each. Bit 0 is for pin 2, bit 1 is for pin 4 and bit 2 is for pin 10. You can also write this with bitwise operators:
byte all_states = digitalRead(2) | (digitalRead(4)<<1) | (digitalRead(10)<<2);

For example: If the right sensor is triggered, but not the others, you would get a binary number 0b00000100, which is decimal 4. If the left and the middle sensor are triggered, but not the right one, this results in 0b00000011, which is decimal 3. Then you could check with a switch statement:
switch(all_states){
    case 0: //No sensors triggered
        break;
    case 1: // Left sensor triggered
        break;
    case 2: // middle sensor triggerd
        break;
    case 3: // middle and left sensor triggered
        break;
    ...
}

You see how it works. The code for each case then goes inbetween of each case and break line.


text:
How to interrupt and direct my program where I want it to in the code by clicking a button?
I want to simulate christmas lights and the different modes of lighting it can produce by pressing a button. I tried to do this by having a button pressed which changes an int variable (1-3) which then corresponds to 1 of 3 of my if statements that each have their own code that lights the leds in a different manner. What I have noticed is that if I were to press the button while my program is in the middle of executing one of these light modes, the operation is NOT interrupted and I'd have to wait for the operation to finish before I could press the button and switch to a different mode. As you know, in actual Christmas lights, this is not the case. One can easily switch between modes with a push of a button with no delays. How can I achieve this through code? P.S. I am a newbie in Arduino. My code is written below

const int buttonPin =2;
int ledPin[5] = {3,5,6,9,10};
int counter = 1;
int brightness = 0;
void setup(){
    Serial.begin(9600);
    pinMode(buttonPin, INPUT);
    for(int i = 0; i<5; i++)
    {
       pinMode(ledPin[i], OUTPUT);
      Serial.println(ledPin[i]);
    }
}
void loop(){

  int reading = digitalRead(buttonPin);
  if (reading != 0){
    counter++;
    if(counter == 4)
    {
      counter = 1;
    }
  }

  if (counter == 1) // mode 1 of the christmas lights (default mode)
  {
    digitalWrite(3, HIGH);
    digitalWrite(6, HIGH);
    digitalWrite(10, HIGH);
    delay(300);
    digitalWrite(3, LOW);
    digitalWrite(6, LOW);
    digitalWrite(10, LOW);
    delay(300);
    digitalWrite(5, HIGH);
    digitalWrite(9, HIGH);
    delay(300);
    digitalWrite(5, LOW);
    digitalWrite(9, LOW);
    delay(300);
  }
  else if (counter == 2)// mode 2 of the christmas lights
  {
      for(brightness =0; brightness <= 255; brightness++)
      {
        analogWrite(3, brightness);
        analogWrite(5, brightness);
        analogWrite(6, brightness);
        analogWrite(9, brightness);
        analogWrite(10, brightness);
        delay(3);
      }
      for(brightness =255; brightness >= 0; brightness--)
      {
        analogWrite(3, brightness);
        analogWrite(5, brightness);
        analogWrite(6, brightness);
        analogWrite(9, brightness);
        analogWrite(10, brightness);
        delay(3);
      }
  }
  else if (counter == 3)// mode 3 of the christmas lights
  {

    for (int i = 0; i < 5; i++)
    {
        digitalWrite(ledPin[i], HIGH);
        delay(150);
        digitalWrite(ledPin[i], LOW);
        delay(150);
    }
    for (int i = 3; i > 0; i--)
    {
        digitalWrite(ledPin[i], HIGH);
        delay(150);
        digitalWrite(ledPin[i], LOW);
        delay(150);
    }
  }
}

Step1: Read Blinking without Delay to replace delay() in your code. This will achieve what you are asking for; Step 2 as a bonus: read Debouncing as you will encounter this once you fix the first problem. Step 3 as another bonus: try to understand statement like digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); to toggle the LED,  and see how to use it to shorten and simply your code. Enjoy your learning.


text:
100 hz Square Wave of 50% duty cycle in digital pin 3 and verifying with pin 4
I am stuck on this for a while, I am trying to generate a 100 hz square wave with 50% duty cycle in pin 3 and trying to verify it with wire at pin 4; I am getting 64000 but not 100 in serial monitor.

#define LEDPIN 3

uint16_t val2= pulseIn(4, HIGH);

ISR(TIMER1_COMPA_vect) { digitalWrite(LEDPIN, !digitalRead(LEDPIN)); }
void setup() {
Serial.begin(9600);
pinMode(LEDPIN, OUTPUT);
// initialize Timer1 (the 16-bit timer) using channel A output compare
noInterrupts(); // disable global interrupts
// TIMER 1 for interrupt frequency 100 Hz:
cli(); // stop interrupts
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // same for TCCR1B
TCNT1 = 0; // initialize counter value to 0
// set compare match register for 100 Hz increments
OCR1A = 19999; // = 16000000 / (8 * 100) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12, CS11 and CS10 bits for 8 prescaler
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei(); // allow interrupts
//TCCR1A = 0; // Timer/Counter Control Register 1A
//TCCR1B = 0; // (both control registers need to be configured)
//// set compare match register to desired timer count:
//OCR1A = 15624; // Output Compare Register 1A (i.e., for channel A)
//TCCR1B |= (1 << WGM12); // CTC (Clear Timer on Compare Match) mode
//TCCR1B |= (1 << CS10); // for 1,024 prescaler; UNO has a 16 MHz clock
//TCCR1B |= (1 << CS12);
//TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
interrupts(); // enable global interrupts:
}
void loop() {
uint16_t val = OCR1A/8;

ICR1 = val -1;
OCR1A = val/2 - 1 ; // 50% duty cycle for pin 3
//OCR1B = val/2 - 1 ; // 50% duty cycle for pin 4
//uint16_t val2= pulseIn(4, HIGH);
Serial.print(val2);
delay(1000);
Serial.print("\n");

}

You wrote:
uint16_t val2 = pulseIn(4, HIGH);

It makes no sense to call this here, as the timer has not been
initialized. You probably cannot expect anything but a timeout in this
context.
noInterrupts();
cli();

These two are synonyms. No need to repeat yourself. Actually, no need to
block interrupts at all.
sei();
interrupts();

Ditto.
OCR1A = 19999; // = 16000000 / (8 * 100) - 1

This is supposed to fire interrupts at 100 Hz. But if you want a
100 Hz output signal, you should fire the interrupts at 200 Hz
(two interrupts per cycle). Thus:
OCR1A = 9999; // = (16 MHz / 8) / (2 * 100 Hz) - 1

Then,
// Set CS12, CS11 and CS10 bits for 8 prescaler
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);

This is configuring Timer 1 for an external clock source. If you
want ÷8 prescaler, you should only set bit CS11. Check the datasheet.
uint16_t val = OCR1A/8;
ICR1 = val -1;
OCR1A = val/2 - 1 ; // 50% duty cycle for pin 3

This doesn't make any sense to me. Why are you setting ICR1? Why are
you changing OCR1A although it was already configured in setup()?
You can remove all this. Here is the loop() I used for testing:
void loop() {
    Serial.println(pulseIn(3, HIGH));
    delay(1000);
}

And it repeatedly printed 4955, which is quite close to the expected
value (namely 5000).

Thanks for your help.

TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10); is divide by 8.  It is shifting a couple zeros.  It is like TCCR1B |= (0b010 << CS10); but I like the 0b010<<CS10 format better if you are trying to document the three clock select bits.


text:
How do I set up communication between the "Seeeduino Xiao" and the "Adafruit Bluefruit LE UART Friend - Bluetooth Low Energy (BLE)"?
I've seen normal Arduino boards connecting to it no problem (Uno, Nano, etc.). I'm trying to connect it to my Seeeduino Xiao. It has UART compatible pins, so I'm fairly certain wiring isn't an issue. I think I'm having a hard time with the coding.

Nevermind, I figured it out. For anyone that has this problem to:
First, use the "blueart_cmdmode" example file. Then, follow these steps:
HOW TO GET THE SEEEDUINO XIAO TO WORK WITH THIS

Make sure the "Adafruit_BluefruitLE_UART ble(Serial1, BLUEFRUIT_UART_MODE_PIN);"
line of text above the "void error" line is UNCOMMENTED. Everything else in that
block is to still be commented.

Define the pins in "BluefruitConfig.h" as such:
#define BLUEFRUIT_SWUART_RXD_PIN       6    // Required for software serial!
#define BLUEFRUIT_SWUART_TXD_PIN       7    // Required for software serial!
#define BLUEFRUIT_UART_CTS_PIN         0    // Required for software serial!
#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused

Wire the pins as defined above.

Make sure the Bluefruit is switched to "CMD" mode.


text:
Where to define web server callback functions so they can access server object? (ESP8266WebServer library)
I want my ESP8266-based device to create an accesspoint that allows the user to input their home ssid and password. There is a device object that holds most of the data defined elsewhere.
I'm trying to use the ESP8266WebServer library. It requires me to define parameterless callback functions. Where should I declare and define these callback functions so that they can access the server object? In all the example code, the server object is global. I'd want to avoid that, and I'd also like to avoid having a server object as a permanent Device class member.
How should I go about this? It is not allowed to define the callback functions inside Device::getWifiCredentials, and if I declare them outside then server isn't in scope.
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

// Function to create AccessPoint to get ssid and password
int Device::getWifiCredentials() {

    ESP8266WebServer server(80);
    server.begin();

    // define callbacks
    server.on("/", handleRoot); // initial page

    server.on("/ssid", handleCredentials); // catch response from initial page

    // wait for credentials to be delivered
    server.handleClient();

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

    return ACTION_SUCCESSFUL;

}

// **Where can these functions be defined to allow them to access the server object?**

void handleRoot() {
};

void handleCredentials() {

    String ssid;
    String pw;

    if( server.hasArg() ){
        ssid = server.arg("ssid");
        pw = server.arg("pw");
    }
};

"It is not allowed to define the callback functions inside Device::getWifiCredentials", it can be done with an anonymous function like server.on("/ssid", []() { }.

i would move ESP8266WebServer server(80); to the 4th line; outside any function. I think you might need to call on() before begin() as well, just once, like in setup(), at least that's how mine works.

put your server declaraition outside the constructor and call a class callback :
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

// Function to create AccessPoint to get ssid and password
int Device::getWifiCredentials() {
server.begin();

    // define callbacks
    server.on("/", std::bind(&Device::handleRoot, this); // initial page

    server.on("/ssid", std::bind(&Device::handleCredentials, this); // catch response from initial page

    // wait for credentials to be delivered
    server.handleClient();

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

    return ACTION_SUCCESSFUL;
}


text:
Controlling lights by XBee S1+ ESP32 without bridge
I need some help with my ideas please, I have a smart home system and I am trying to control the Philips hue light but without the bridge.
I want to do that by XBee S1 + FURTHER ESP 32.
so, who did that or have any ideas about how that can possible.
Any links, Videos, tutorials will be greater.
thanks all.

do Phillips Hue lights use XBee modules for communication?

For Now, I am using the bridge but I want to control them XBee to turn it off/on. the system is not in my home I am working on it.  so what I want to do turn off the bridge and control the lights from the XBee ,    as I saw from the internet I can do that with the transport key of the light + XCTU software +xbee S1. but I am lost I don't know how to start.


text:
Problem uploading my sketch onto my arduino. Arduino 1.8.13, Linux Ubuntu 20.4
This is my log, honestly no idea what the problem is here, tried updating java, didnt work.

Sketch uses 11216 bytes (4%) of program storage space. Maximum is 262144 bytes.
Global variables use 2384 bytes (7%) of dynamic memory, leaving 30384 bytes for local variables. Maximum is 32768 bytes.
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77)
    at processing.app.SketchController.upload(SketchController.java:732)
    at processing.app.SketchController.exportApplet(SketchController.java:703)
    at processing.app.Editor$UploadHandler.run(Editor.java:2055)
    at java.lang.Thread.run(Thread.java:748)
Caused by: processing.app.SerialException: Error touching serial port '/dev/ttyACM0'.
    at processing.app.Serial.touchForCDCReset(Serial.java:107)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - /dev/ttyACM0; Method name - openPort(); Exception type - Permission denied.
    at jssc.SerialPort.openPort(SerialPort.java:170)
    at processing.app.Serial.touchForCDCReset(Serial.java:101)
    ... 6 more

look at the second caused by line

https://www.arduino.cc/en/Guide/Linux#please-read

Is your user in the dailout group? That is required for you to use the serial devices. And after you added the group to your user, you need to relogon to get thar change active

How do i find out if i am in the dailout group

I added my user using  [ $ sudo adduser "user" dialout  ] and it worked thank you


text:
Trying to improve speed of downloading files from server and writing to SPIFFS
update I have updated the code(second code segment) so that the null character is inserted into the array which solves the problem of writing past the end of the array. in order to stop the program from crashing i can only put the null character at the end of the array. this means that i need to increase the size of the array to accommodate for it. infuriatingly as soon as i do anything with the size variable, ie. size = size+1 the program takes a great deal longer to execute. i have no idea whats going on here so any help would be much appreciated. i have simplified the code further and the actual text file i am using on the server is included if anyone wanted to try it out. many thanks.
original post
i have written a sketch which uses the HTTPClient library to download 3 files from a server and write them to 3 SPIFFS files on an ESP32 using arduino IDE. It works fine but I am trying to improve the speed. The following code is the code which works:
#include <Arduino.h>

#include <WiFi.h>
#include <WiFiMulti.h>

#include <HTTPClient.h>

#define Serial Serial

WiFiMulti wifiMulti;

#include <SPIFFS.h>

#include "SPIFFS.h"

#define FORMAT_SPIFFS_IF_FAILED true

String url = "http://server.com";
String fileName[] = {"/file1", "/file2", "/file3"};
String fileSuf = ".dat";
String imageSuf = ".gif";
int fileIndex = 0;
int numFiles = sizeof(fileName) / sizeof(fileName[0]);

String filePath = url + fileName[fileIndex] + fileSuf;
String imagePath = fileName[fileIndex] + imageSuf;

void setup() {

  Serial.begin(115200);

  if (!SPIFFS.begin(FORMAT_SPIFFS_IF_FAILED)) {
    Serial.println("SPIFFS Mount Failed");
    return;
  }

  SPIFFS.format();

  ///connect to the internet
 wifiMulti.addAP("xxx", "xxx"); //work network

//    download files
    while(fileIndex < numFiles){
      getFiles(); //retreive gif image
      fileIndex++;
    }
    fileIndex = 0;

}

void loop() {

}

long timer;
int speed;

void getFiles() {

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

    //generate paths
    filePath = url + fileName[fileIndex] + fileSuf;
    imagePath = fileName[fileIndex] + imageSuf;

    Serial.println(filePath);
    Serial.println(imagePath);

    HTTPClient http;

    Serial.print("[HTTP] begin...\n");

    // configure server and url
    http.begin(filePath);
    timer = millis(); //set timer

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

      // file found at server
      if (httpCode == HTTP_CODE_OK) {

        // get lenght of document (is -1 when Server sends no Content-Length header)
        int len = http.getSize();

        // create buffer for read
        byte buff[2048] = { 0 };

        // get tcp stream
        WiFiClient * stream = http.getStreamPtr();

        // read all data from server
        while (http.connected() && (len > 0 || len == -1)) {

          // get available data size
          size_t size = stream->available();

          if (size) { ///
            // read up to 128 byte
            int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size)); //calculate size of buffer(is it full?)

            appendFile(SPIFFS, imagePath, buff, c); //addi buffer to file in flash

            if (len > 0) {
              len -= c;
            }
          }
        }

        Serial.println();
        Serial.print("[HTTP] connection closed or file end.\n");

      }
    } else {
      Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
    }

    speed = millis() - timer;
    Serial.println(speed); //print time taken in millis;
    http.end();

  }

}

void appendFile(fs::FS &fs, String _path, byte message[], int arr_size) {

  File file = fs.open(_path, FILE_APPEND);

   file.write(message,arr_size);

}

So thats all well and good but i experimented with how to speed it up.The following code finishes the task of downloading and writing to flash in a third of the time but because i pass the array to the print method without telling it where the buffer ends it prints 'junk' bytes on the end making the file corrupted.
My question is, why is my working method so much slower than the other method. is there any way i can get the same speed as method 2 but without printing the unwanted bytes each time? it seems like i should be able to specify this without sacrificing so much speed.
as an example of the speed file1 took 9102 ms to complete in the first approach and 3303 ms in the second. a big difference! any advice would be much appreciated, thanks!
Heres the second approach' code:
(The only changes are changing the buffer array from byte to char and using file.print(message) in the appendFile function instead of file.write(message,array_size);
#include <Arduino.h>

#include <WiFi.h>
#include <WiFiMulti.h>

#include <HTTPClient.h>

#define Serial Serial

WiFiMulti wifiMulti;

#include <SPIFFS.h>

#include "SPIFFS.h"

#define FORMAT_SPIFFS_IF_FAILED true

String path = "/test.txt";
String filePath = "http://gonadgranny.atwebpages.com/text.txt";

void setup() {

  Serial.begin(115200);

  if (!SPIFFS.begin(FORMAT_SPIFFS_IF_FAILED)) {
    Serial.println("SPIFFS Mount Failed");
    return;
  }

  SPIFFS.format();

  ///connect to the internet
 wifiMulti.addAP("xxx", "xxx"); //work network

      getFiles(); //retreive gif image

}

void loop() {
  readFile(SPIFFS, path);
  delay(5000);

}

long timer;
int speed;

void getFiles() {

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

    //generate paths

    Serial.println(filePath);
    Serial.println(path);

    HTTPClient http;

    Serial.print("[HTTP] begin...\n");

    // configure server and url
    http.begin(filePath);
    timer = millis(); //set timer

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

      // file found at server
      if (httpCode == HTTP_CODE_OK) {

        // get lenght of document (is -1 when Server sends no Content-Length header)
        int len = http.getSize();

        // create buffer for read
        char buff[2048] = { 0 };

        // get tcp stream
        WiFiClient * stream = http.getStreamPtr();

        // read all data from server
        while (http.connected() && (len > 0 || len == -1)) {

          // get available data size
          size_t size = (stream->available()) ; //make one bigger

          if (size) { ///
            // read up to 128 byte
            int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size)); //calculate size of buffer(is it full?)

            appendFile(SPIFFS, path, buff, c); //addi buffer to file in flash

            if (len > 0) {
              len -= c;
            }
          }
        }

        Serial.println();
        Serial.print("[HTTP] connection closed or file end.\n");

      }
    } else {
      Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
    }

    speed = millis() - timer;
    Serial.println(speed); //print time taken in millis;
    http.end();

  }

}

void appendFile(fs::FS &fs, String _path, char message[], int arr_size) {

  message[(arr_size-1)] = '\0'; //put in end of array

  File file = fs.open(_path, FILE_APPEND);

   file.print(message);

}

void readFile(fs::FS &fs, String path) {
  Serial.printf("Reading file: %s\r\n", path);

  File file = SPIFFS.open(path);
  if (!file || file.isDirectory()) {
//    Serial.println("- failed to open file for reading");
    return;
  }

//  Serial.println("- read from file:");
  while (file.available()) {
    Serial.write(file.read());
  }
}

add buff[size+1] = '\0' between int c... and appendFile(..., which should crop off the extra right-hand malarky when print()ed.

hi thanks for this, i used it as the basis to rewrite my code and the speed just slowed right down again. its so strange that this seemingly very simple process of checking for the end of line character is causing such an enormous increase in processing time...


text:
Forcing bootloader startup through program
I am trying to find out if it is possible to trigger programmatically the double-tap on reset button function, implemented in modified version of Atmel's SAM-BA bootloader. The board of interest is Arduino Zero.
In case this is not possible using the stock board setup, if this can be achieved by hardware or bootloader modifications.

Theoretically it is quiet easy to fake that double-tap with software, but there might be some obstacles in practice.
The bootloader uses an unsigned long value in RAM memory to indicate if the double tap happend. The actual bootloader for the zero uses the following definitions.
// zero specific; but other boards use the same values AFAIK
// (in board_definitions_arduino_zero.h)
#define BOOT_DOUBLE_TAP_ADDRESS  (0x20007FFCul)
#define BOOT_DOUBLE_TAP_DATA  (*((volatile uint32_t *) BOOT_DOUBLE_TAP_ADDRESS))

// for all bootloader (in main.c)
#define DOUBLE_TAP_MAGIC 0x07738135

When the bootloader is started after a reset, it checks, if that was a power on reset (POR) or not. If it has been a POR, it sets the indicator value to 0 BOOT_DOUBLE_TAP_DATA = 0;.
If it does not detect a POR, the bootloader continues with checking the indicator value whether it is set to the tap magic.
If the magic can be found  the indicator value is set back to 0 and the bootloader is started. Otherwise the value is set to the "double tap magic": BOOT_DOUBLE_TAP_DATA = DOUBLE_TAP_MAGIC. The bootloader waits for 500 ms to let the user reset the zero a second time (double tap) and resets the indicator value after that time interval.

How to:
To simulate a double tap, you just need to set the indicator variable with the magic value from within you program. Use the definitions above. Then perform a software reset.

The caveats:

If the bootloader was changed, that could make you code useless.
I have not the time to test my ideas, so this is just an unverified method. It might fail for some reasons, I do not see actually.
You have to find a method to reset the zero with the program. Iknow some methods but I've not tried any of them so far.

Reset Methods: (as a starting point for your search)
I've read somewhere that the zero supports the CMSIS method NVIC_SystemReset.
This is a method often used for M0 ARM controllers (like SAMD11).
SCB_AIRCR = SCB_AIRCR_VECTKEY(0x5FA) | SCB_AIRCR_SYSRESETREQ_MASK;

Here is my code "idea" (untested):
#define BOOT_DOUBLE_TAP_ADDRESS  (0x20007FFCul)
#define BOOT_DOUBLE_TAP_DATA  (*((volatile uint32_t *) BOOT_DOUBLE_TAP_ADDRESS))
#define DOUBLE_TAP_MAGIC 0x07738135

// lots of code ....

void resetWithDoubleTap()
{
   BOOT_DOUBLE_TAP_DATA = DOUBLE_TAP_MAGIC;
   NVIC_SystemReset();
}

I would be lucky, if you succeed with this. Please let us know your outcomes, either write your own answer or tell me what you've done and I will correct my answer if necessary. Good luck.

Thank you very much. I will have a board available for testing in a week or so. Anyway  I will definitely post the results here. For now this is the accepted answer.


text:
ESP32 captive portal not working with private IP address for android
For the initial settings of WiFi cerdentials and configuration on a standalone device (ESP32), I try to implement a captive portal using the CaptivePortal example for ESP32 DNSServer (see original source). I'm using Arduino IDE 1.8.13 and ESP32 core 1.0.4.
Different from the cited source, the example reads (as often seen in posts for that):
IPAddress apIP(192, 168, 1, 1);

This works well when connecting my laptop and opening firefox, which the tells me I'ld have to sign in by opening a signin-page.
This does not work with my android phone. It always tells me "no connection to internet".
In the latest version of the ESP core as cited above, the IP address is modified to
IPAddress apIP(8,8,4,4); // The default android DNS

This in fact works, even with android device.
I now tried different IP addresses (192.168.4.1, 8.8.8.8, 142.250.186.131, which is connectivitycheck.gstatic.com in real life, and some more). What did happen:

Using an address out of the private pool (192.168.x.y) did lead to "No connection to the internet"
Using any of the public addresses did open the portal page.

I updated the DNSServer library to version 1.0.5 of the core, as that allowed for debugging the dns server. Additionally, I added some Serial prints for debugging. Using 192.168.1.1, the output reads:
dhcps: send_offer>>udp_sendto result 0
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 18 - AP_PROBEREQRECVED
DNS responds: 192.168.1.1 for epdg.epc.mnc002.mcc262.pub.3gppnetwork.org
DNS responds: 192.168.1.1 for north-america.pool.ntp.org
DNS responds: 192.168.1.1 for mtalk.google.com
DNS responds: 192.168.1.1 for connectivitycheck.gstatic.com
DNS responds: 192.168.1.1 for connectivitycheck.gstatic.com
DNS responds: 192.168.1.1 for alt4-mtalk.google.com
DNS responds: 192.168.1.1 for gstatic.com
DNS responds: 192.168.1.1 for android.googleapis.com
DNS responds: 192.168.1.1 for google.com

 --- Begin http request ---
GET / HTTP/1.1
User-Agent: Dalvik/2.1.0 (Linux; U; Android 7.0; SM-A310F Build/NRD90M)
Host: 192.168.1.1
Connection: Keep-Alive
Accept-Encoding: gzip

 --- End http request ---

DNS responds: 192.168.1.1 for connectivitycheck.gstatic.com
DNS responds: 192.168.1.1 for connectivitycheck.gstatic.com
DNS responds: 192.168.1.1 for android.clients.google.com
DNS responds: 192.168.1.1 for google.com
DNS responds: 192.168.1.1 for service.game-mode.net
DNS responds: 192.168.1.1 for play-lh.googleusercontent.com
DNS responds: 192.168.1.1 for play.googleapis.com
DNS responds: 192.168.1.1 for connectivitycheck.gstatic.com
DNS responds: 192.168.1.1 for gld.push.samsungosp.com
DNS responds: 192.168.1.1 for googleapis.com
DNS responds: 192.168.1.1 for ssl.google-analytics.com
DNS responds: 192.168.1.1 for beacons.gvt2.com
DNS responds: 192.168.1.1 for connectivitycheck.gstatic.com
DNS responds: 192.168.1.1 for connectivitycheck.gstatic.com
DNS responds: 192.168.1.1 for google.com
DNS responds: 192.168.1.1 for yahoo.com

 --- Begin http request ---
GET / HTTP/1.1
Connection: close
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en;q=0.8,en-US;q=0.6,en;q=0.4
User-Agent: Dalvik/2.1.0 (Linux; U; Android 7.0; SM-A310F Build/NRD90M)
Host: www.yahoo.com

 --- End http request ---

and some more of these.
Using e.g. 142.250.186.131, this reads different:
dhcps: send_offer>>udp_sendto result 0
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 18 - AP_PROBEREQRECVED
DNS responds: 142.250.186.131 for epdg.epc.mnc002.mcc262.pub.3gppnetwork.org
DNS responds: 142.250.186.131 for connectivitycheck.gstatic.com
DNS responds: 142.250.186.131 for connectivitycheck.gstatic.com
DNS responds: 142.250.186.131 for north-america.pool.ntp.org
DNS responds: 142.250.186.131 for capi.samsungcloud.com
DNS responds: 142.250.186.131 for mtalk.google.com
DNS responds: 142.250.186.131 for alt2-mtalk.google.com

 --- Begin http request ---
GET /generate_204 HTTP/1.1
Host: connectivitycheck.gstatic.com
Connection: close
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Dalvik/2.1.0 (Linux; U; Android 7.0; SM-A310F Build/NRD90M
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en;q=0.8,en-US;q=0.6,en;q=0.4

 --- End http request ---

DNS responds: 142.250.186.131 for connectivitycheck.gstatic.com
DNS responds: 142.250.186.131 for android.googleapis.com

 --- Begin http request ---
GET / HTTP/1.1
User-Agent: Dalvik/2.1.0 (Linux; U; Android 7.0; SM-A310F Build/NRD90M)
Host: 142.250.186.131
Connection: Keep-Alive
Accept-Encoding: gzip

 --- End http request ---

DNS responds: 142.250.186.131 for service.game-mode.net
DNS responds: 142.250.186.131 for android.clients.google.com

 --- Begin http request ---
GET /generate_204 HTTP/1.1
Host: connectivitycheck.gstatic.com
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Linux; Android 7.0; SM-A310F Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/87.0.4280.101 Mobile Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
X-Requested-With: com.android.captiveportallogin
Accept-Encoding: gzip, deflate
Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7

 --- End http request ---

So, the HTTP requests are
GET / HTTP/1.1
Host: 192.168.1.1

(and some other hosts) if using private network address, and
GET /generate_204 HTTP/1.1
Host: connectivitycheck.gstatic.com

if using public network address.
My question:
Is there any reason that android systems act different on addresses from the private address space than from the public one? And if so, is it safe to use e.g. 8.8.4.4 for all kinds of client systems (android, ios, linux, windows, ...)?
Edit:
I tried 10.0.0.1 and 172.16.0.1 (the other two private network spaces), but android does not like them as well; @dandavis seems to be right. Now I use 192.9.200.1 which works well.
Why that address?
Some history: When in the late 1980s and early 1990s companies began to use IP networks in combination with SUN computers, many "network administrators" followed a documentation by SUN how to configure those networks. In that documentation, the address range 192.9.200.0/24 was used as an example; it was part of SUNs own network range. So many (if not all) of those people used this address range, not knowing that they should use other (private) addresses.
The address range 192.9.0.0/16 nowadays is owned by Oracle, but they seem not to use 192.9.200.0/24. If you search for "192.9.200.0", you may still find lots of documentation containing exactly those example addresses.

#2 is a yes. #1 might be that 192.168... looks like a "regular ass wifi" that should be providing internet, whereas 8.8... isn't typical, so this could be a stupid user optimization for the 99.9% of times that 192... provides internet.

Thank you for your comment. I really don't like using addresses from internet routed networks for private purpose. But here this might be the only solution - will try 172.16.0.0/12 and 10.0.0.0/8 as well and report on success.

I would suggest doing a bit of reading on rouotable and non routable IP addresses.  It appears your Android is not on the same network and it is being rejected as it should.

@Gil: Every IPV4 Address is "routable" - there are no "non routable" IP addresses. Addreses out of the "private" address space are not routed in public networks, but that is a different thing (see RFC1918 or https://en.wikipedia.org/wiki/Private_network). "My Android" gets its Address via DHCP from the Soft-AP, and thus is "in the same network" as the AP, which is also DNS server and default router, as I can see from the Android information.


text:
Firmata.SendString doesn't work with specific `char` variables
I have a Firmata sketch, that accepts string messages, partitions them and sends its' parts back to a Firmata client program. My problem is certainly at the sketch's side. The problem is that Firmata.sendString(argument1) and Firmata.sendString(argument2) methods don't send anything. More information is found in the sketch's code. How can I get the sendString methods to work?
/*
 * This sketch accepts strings in the following form:
 * CMDn(arg1,arg2)
 * CMDn — command name,
 * arg1 и arg2 — unnecessary arguments.
 * Each argument's length can be from 1 to 4 characters,
 * They're saved to separate variables.
 *
 * This sketch sends back the parsed commands partially:
 * the command name, argument #1 (if present), argument #2 (if present)
 */

#include <Firmata.h>

void stringCallback(char *received) {
  //CMDn(arg1,arg2)
  //CMDn(arg1)
  //CMDn(1)
  //CMDn()
  //012345678901234
  //          11111

  //This scheme up there is just for
  //understanding the indexes of the chars in the string
  //in its various possible variations

  //Let's declare all the necessary variables
  char methodName[5];
  char argument1[5];
  char argument2[5];
  byte commaLocation = 0;

  //If the received string doesn't match the strings' syntax,
  //send an error message
  if (!(received[4] == '(' && strlen(received) <= 15)) {
    Firmata.sendString("ERR;");
    return;
  }

  //Let's take the 0-3 chars in the string and send it back.
  //It's probably the command name
  for (int i = 0; i < 4; i++) {
    methodName[i] = received[i];
  }
  methodName[4] = '\0'; //does or doesn't the compiler add the terminator automatically?
  Firmata.sendString(methodName); //send it
  //This string is being sent without problems.

  //If there is some arguments in the string,
  //it is detectable if the string char 5 is not ')'/
  if (received[5] != ')') {
    //Lent's find out if the input string has a `comma`
    //inside the parentheses. If it does, it means that
    //there are two arguments in the string.

    Firmata.sendString("46 passed");
    for (int i = 6; i < (strlen(received) - 1); i++) {
      //If there is a comma, save its' index and break the loop
      if (received[i] == ',') {
        commaLocation = i;
        break;
      }
    }

    //If a comma is not present, its location variable equals 0,
    //sincerely we just collect all the chars between the parentheses
    //to the 'argument1' variable and send it.
    if (commaLocation == 0) {
      Firmata.sendString("61 passed");
      for (int i = 5; i < ; i++) {
        argument1[(i - 5)] = received[i];
      }

      argument1[strlen(argument1)] = '\0'; //Either this is executed or not, the outcome doesn't change

      Firmata.sendString(argument1); //This very command doesn't work. It just does not send anything.
                                     //Looks like 'argument1' is empty, but I'm awfully sure that it must
                                     //not be empty. Anyway, the 'argument1' does not show up in the client
    }

    //If there is a comma present, then write chars before the comma
    //to 'argument1', and after the comma - to 'argument2'
    if (commaLocation != 0) {
      Firmata.sendString("77 passed");
      //let's write what is before the comma:
      for (int i = 5; i < commaLocation; i++) {
        argument1[i - 5] = received[i];
        Firmata.sendString("81 iterator");
      }

      //let's write what's after the comma;
      char argument2[5];
      for (int i = (commaLocation + 1); i < (strlen(received)); i++) {
        argument2[(i - (commaLocation + 1))] = received[i];
        Firmata.sendString("87 iterator");
      }

      argument1[strlen(argument1)] = '\0'; //Either this is executed or not, the outcome doesn't change
      argument2[strlen(argument2)] = '\0';

      Firmata.sendString(argument1); //Not working
      Firmata.sendString(argument2); //Not working
    }
  }
}

void sysexCallback(byte command, byte argc, byte *argv) {
  Firmata.sendSysex(command, argc, argv);
}

void setup() {
  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
  Firmata.attach(STRING_DATA, stringCallback);
  Firmata.attach(START_SYSEX, sysexCallback);
  Firmata.begin(57600);
}

void loop() {
  while (Firmata.available()) {
    Firmata.processInput();
  }
}

Expected output:

What I send
What I receive (excluding the debug messages, ; stands for newline)

DHTt()
DHTt

DHTt(1)
DHTt; 1

DHTt(1,2)
DHTt; 1; 2

Real output:

What I send
What I receive (excluding the debug messages)

DHTt()
DHTt as long as there are no arguments, there are no problems. But the arguments are necessary for my task

DHTt(1)
DHTt the argument are not sent

DHTt(1,2)
DHTt two arguments are not sent neither

strlen(argument1) tells you the index of the first '\0' char, so that line doesn't make sense. This would be a lot simpler if you used pointers to the char array so that you can easily set/change a start point (for example with recPtr = strchr(received, ',')) instead of skipping over offsets. Look for helpful tools in http://www.cplusplus.com/reference/cstring/

@DanDavis, isn't the cstring equivalent to the Arduino String struct, neither the character array?

Also, please pinpoint which concrete line of the code?

They're probably referring to any of the lines that take the form x[strlen(x)] ='\0';  At best x contains a valid string and this line is unless since it just puts a null terminator where one already exists.  If x is not a valid c-string, useless is the best outcome you can hope for, but not the only one.  You are going this with argument1 in two places.  argument2 in one place.  It seems like it would be good to just spend some time learning about strings outside of the context of your project.  You can play in a desktop environment and transfer over what you learn.

What does your client (the PC) do with the string? Do you use a library there or did you write the client yourself?

@pmf, everything my client program does is to accept a string provided by the user and then send it to the Arduino. More information can be found on this question.

@dandavis, strchr is making the 81 line loop lose mind. Is a pointer which strchr returns saveable to a byte variable?

Firmata.sendString does not send anything to the client in two cases:

If the message is empty;
If the message does not contain the \0 terminator in it.

In this case, while you're sending methodName, you're manually assigning the terminator to the string; and the sender works:
methodName[4] = '\0';

The only thing necessary to do to solve this argument problem is making each char variable end with a null terminator. Here you can see the solved code:
#include <Firmata.h>

//setup() and loop() won't be here, there are no changes in them

unsigned long charIndex(const char * findIn, unsigned int symbol) {
  //Find 'symbol' in char array 'findIn'. Unlike
  //strchr(), returns unsigned long or 0 if 'symbol' not found

  char * pointer = strchr(findIn, symbol);
  if (pointer != NULL) return (pointer - findIn);
  if (pointer == NULL) return 0;
}

void stringCallback(char *received) {
  //Let's declare all the necessary variables
  char methodName[5];
  char argument1[5];
  char argument2[5];
  int commaLocation = 0;
  int lasti;

  byte nullTerminatorIndex = strlen(received); //For understanding

  //If the received string doesn't match the strings' syntax,
  //send an error message
  if (!(received[4] == '(' && strlen(received) <= 15)) {
    Firmata.sendString("ERR;");
    return;
  }

  //Let's take the 0-3 chars in the string and send it back.
  //It's probably the command name
  for (int i = 0; i < 4; i++) {
    methodName[i] = received[i];
  }
  methodName[4] = '\0'; //**The compiler doesn't add terminators automatically**.
  Firmata.sendString(methodName); //send it
  //This string is being sent without problems.

  //If there is some arguments in the string,
  //it is detectable if the string char 5 is not ')'/
  if (received[5] != ')') {
    //Lent's find out if the input string has a `comma`
    //inside the parentheses. If it does, it means that
    //there are two arguments in the string.

    Firmata.sendString("46 passed");
    if (charIndex(received, ',') != 0) commaLocation = charIndex(received, ',');

    //If a comma is not present, its location variable equals 0,
    //sincerely we just collect all the chars between the parentheses
    //to the 'argument1' variable and send it.
    if (commaLocation == 0) {
      Firmata.sendString("61 passed");
      for (int i = 5; i < (nullTerminatorIndex - 1); i++) {
        argument1[(i - 5)] = received[i];
        lasti = (i - 5);
      }

      argument1[(lasti + 1)] = '\0';
      lasti = 0;

      Firmata.sendString(argument1);
    }

    //If there is a comma present, then write chars before the comma
    //to 'argument1', and after the comma - to 'argument2'
    if (commaLocation != 0) {
      Firmata.sendString("77 passed");
      //let's write what is before the comma:
      for (int i = 5; i < commaLocation; i++) {
        argument1[i - 5] = received[i];
        lasti = (i - 5);
      }

      argument1[(lasti + 1)] = '\0';
      lasti = 0;

      //let's write what's after the comma;
      char argument2[5];
      for (int i = (commaLocation + 1); i < (nullTerminatorIndex - 1); i++) {
        argument2[(i - (commaLocation + 1))] = received[i];
        lasti = (i - (commaLocation + 1));
      }

      argument2[(lasti + 1)] = '\0';
      lasti = 0;

      Firmata.sendString(argument1);
      Firmata.sendString(argument2);
    }
  }
}

Here's a simplified version of your command parser using cstrings and pointers:
void parseArgs(char * rec){
  char cmd[32];
  char arg1[32]= {0};
  char arg2[32]= {0};
  char * ptr; // this is a re-usable workhorse pointer
  char * ptrDelim; // another workhorse to split arguments

  // first copy all of it to cmd
  strcpy(cmd, rec);
  // find end of command
  ptr = cmd;
  while( isalpha(ptr[0]) ) ptr++;
  ptr[0] = '\0'; // mark end of command string

  // find first arg
  ptr = strchr(rec, '(')+1; // set ptr to char to right of open paren
  strcpy(arg1, ptr); // copy stuff after open paren to arg1:
  ptr = strchr(arg1, ')');// find max extent of arg1
  if(ptrDelim=strchr(arg1, ',')){
    ptrDelim[0]='\0'; // end arg1's string at delim
    ptrDelim++; // move right one char
    strcpy(arg2, ptrDelim); // copy stuff after comma
    arg2[strlen(arg2)-1] = '\0'; // chop off ")"
  }else{
    ptr[0]='\0';
  }//end if comma?

 Serial.println("\nGiven:" + String(rec)+";");
 Serial.println("Command:" + String( cmd )+";");
 Serial.println("Arg1:" + String( arg1 )+";");
 Serial.println("Arg2:" + String( arg2 )+";");

}

Examples:
parseArgs("CMDn()");
parseArgs("CMDn(arg1)");
parseArgs("CMDn(arg1,arg2)");

Remove the String()-having lines after you get done debugging.

In if(ptrDelim=strchr(arg1, ',')){ statement, did you mean == instead of =?

Also, what does your code do if there is no arguments in the incoming string?

@Starter: i should have wrapped the expression in parens as the compiler suggested, but it's an intentional two-fer: if the char is not present in the string it returns a falsy null-pointer, and if it finds it, it returns a truthy evaluation whilst assiging the pointer to that char's posistion.

@Starter: then they will be blank, which you can detect by if(strlen(arg1)) or if(arg1[0]) as needed.

this is not working correctly. When I input "CMDn(arg1,arg2)", I get this; if no args are present, then there is a ) in arg1; if there is only one arg, it is being recorded to arg1 along with the comma.


text:
Vernier to Arduino not working
I want to connect this analog Vernier temperature probe to my Arduino with this British Telecom Connector (BTA).
According to datasheet, when sensor is in the connector, the PIN 6 of the connector should give us the value from 0-5V. I think it should work with this connector because it is supposed to work with this adapter, which is approved by Vernier. It's hard to get any real details about this official Vernier adapter, but I think it doesn't do anything different than just the BTA (linked above).
Of course, I also connected 5V and GND to connector, but when I want to read that 0-5V from Arduino, it says 0. Every single time. The sensor is not broken, because it works with Vernier sensor interface shield which I put on the Arduino (yes, I could use it, but I want to make my project smaller).
That's how the PINS work:

Sensor Pin
Arduino Pin

1 (+/-10 V output line)
A1

2 (Ground)
Ground

3 (Vres/resistance reference)
A4 (also for I2C autoID)

4 (AutoID)
A5 (also for I2C autoID)

5 (+5 Volt power)
5V

6 (0-5 V output line)
A0

I don't know if that's important, but the sensor is based on a thermistor. Also, if I connect A0 to PIN number 1 (+/- 10V output line), it gives me a value.  But, I really can't find anywhere how is that value connected with temperature. I hope I presented my problem well enough so you will understand it.
Thanks :)

This is probably going to sound mean, but I'm sincere in this. Break that up into coherent paragraphs and make sure you're focusing on one thing.

data is a number that's not 0 ... very normal

Sorry, i just didn't know what kind of information do you need :/. That's the link to the probe: https://www.vernier.com/product/stainless-steel-temperature-probe/ . I though it would work with Arduino like this because it works if you use this protoboard adapter approved by Vernier: https://www.vernier.com/product/analog-protoboard-adapter/ .

Take some time to edit your question.  You can put those links into it while you're in there.

Well, I've made an edit to get you started.  I'm trying to be conservative with it.  You should refine it.


text:
Extracting .hex from Arduino Due
I have an Arduino Due that was programmed by the Arduino IDE, to cut things short I lost access to the original sketch (.ino) file, there is no way of recovering it no matter what.
I know that in the 8-bit MCUs I can read the .hex file from the flash memory, I already did that with PIC and AVR MCUs with their software programmer utilities.
My question is: Can I use a software programmer utility on Windows PC to extract the hex file to reprogram other Arduino Due with it? If yes, please help me.
I've read about the Bossac utility, it looks promising, but I have no experience in the ARM MCUs field at all.
again: I am NOT interested in C or Assembly code, I just want the .hex file.

you can simply read the hex with avrdude with the -U flash:r:filename option

No you can not, avrdude is for 8-bit Atmel MCUs, this is a 32-bit ARM MCU, the USBASB will not work.

You're right, my bad!

No worries at all, I will try now some methods and report back if anything succedded.

I'm sure you can do it through the JTAG interface. No idea how though.

You can use JTAG and probably should.  But, it can also be done with bossac if you are very careful.  If you're not, you'll end up erasing your flash on your source board.
Using bossac
This would maybe not be preferred over JTAG because it is probably easier to screw up (see warnings below), but it can be done.  I may add some on JTAG programming later, and if I do it may be above this section for that reason.  The main advantage here is just that you don't need a JTAG programmer.  The one caveat is that your existing sketch, or rather the image of the sketch that has been burned onto what I'm calling the "source board" has to be functioning well enough that it can cooperate in being placed back into the ROM bootloader.  I fully expect this is not a problem for you, or for pretty much any normal Arduino sketch that has been burned to a board.
WARNINGS

Under NO circumstances do you want to connect to the PROGRAMMING port of your source board at 1200 baud.
Doing so will erase your board, and then that's the end of it.

In the below you will be connecting to the Native USB port at 1200, NOT the programming port.
Connect only one port at a time to your computer so there is no possibility of selecting the wrong one.

Practice this whole procedure with a board you don't care about first.

Locate your BOSSAC command.
On my Windows machine, it was in:
C:\Users\username\AppData\Local\Arduino15\packages\arduino\tools\bossac\1.6.1-ardunio\bossac.exe

It may be under a different version number.  It's possible that it will be in a completely different location.
cd %USERPROFILE%
dir bossac.exe /s/b/p/a

Should locate it it, eventually, in any case.
On Linux it will be under ~/.arduino15 somewhere:
find ~/.arduino15 -name bossac

On a Mac it will probably be under a /Library/ directory under the user account somewhere.  You get the idea, locate it, make sure you can run it.
NOTE: There's a bossa program that is the GUI version where bossac is a command-line program.  Unfortunately the IDE board support files don't ship the GUI program.  If you're having trouble with the command-line and want to try that instead, go for it.  But test it on a board you don't care about beforehand.  I have not tried it.
Connect to the Native Header
Connect your native USB port on the source board and only to that port.

Enable boot to ROM
Open a terminal emulator of your choice at a rate of 1200 baud to the native USB port, wait a couple seconds and then close the port.  You can use the Serial Monitor from the IDE to do this if you want:

Select the correct port from Tools/Port.

Open the Serial Monitor

Switch the baud rate to 1200 baud.

You're not going to type anything and you're not going to see anything once you're connected at 1200 baud.

Close the Serial Monitor

You probably should:

See if the port has changed COM#, if so select the new one.

Re-open the serial monitor

Change the baud rate again to anything-but-1200-baud

Close the serial monitor again.
This is not strictly necessary but the IDE remember the last chosen baud rate, and for what we're doing this is a slightly dangerous thing.

Close the IDE as well.

What connecting at 1200 baud does is activate the code inside the core part of the programmed sketch that changes the board to boot from the internal ROM bootloader.  It doesn't need traffic.  It just needs to see a request for 1200 baud.  More specifically, it needs to see the DTR "signal" go inactive, which happens when the port is closed, when the effective rate was 1200 baud.
NOTE: if you screw up here and connect to the programming port at 1200 baud instead, you'll wind up causing the ATMega16U2 to erase your source board.  The IDE remembers your last chosen baud rate, which makes this easy to screw up as well.  Hence the weird little dance in the above instructions regarding reopening the serial monitor and changing to something other than 1200 baud.  It's just putting an extra barrier up to accidentally doing this.
Once you've connected to the native USB port at 1200 baud and closed the port, your board will not run your sketch any more.  It's still there, it's just not running it.  The board has been told to sit in the ROM based bootloader, waiting for bootloader commands.
Saving your existing sketch's image
What we're going to do is run the bossac command you found earlier like so:
bossac --read saved-sketch-image.bin --boot --reset

I'm assuming you either changed directory to where bossac.exe is, or alternately you're going to specify the necessary path to it found earlier.  I've found this command locates the correct COM port automatically.
This command:

Downloads all of flash, 512 kbyte, and takes while, 128 seconds in one test.  Weirdly the same version under Linux takes closer to 10 seconds;  I haven't looked into why the difference, but I'm also unconcerned.
So you now should have a 512 kbyte raw binary file containing your sketch image.

It re-enables the boot-from-FLASH so that on the next reset it will go back to running your sketch

It resets your board, so it will begin running your old sketch.  If you don't want it to do that until you power cycle it, you could just as easily leave off the --reset part.

As said, this is a raw binary file.  But you mentioned a HEX.  I'm assuming you didn't mean that literally, so I'm not going to detail how to convert the .bin file to a HEX format.  Though, if you want to do that, you should know that it needs to be offset to 0x80000, because that's where flash starts on the Due.
Disconnect your source board from USB.
Making your clone (target) board
Connect to your target board via the programming port.

Hold the erase button for a few seconds to make sure the target board is erased.  Usually this would be done by the IDE connecting to the port for a while at 1200 baud.  But since we're using bossac at the command line, we need to do that step manually; it's just easier to use the button this time.

Reset the board with the reset button.  Your target board is now sitting in its ROM bootloader awaiting commands.

Put your image on the new board with:

bossac --write saved-sketch-image.bin --boot --reset

Again, it's programming the whole 512 kbytes.  In one test on Windows it took about 100 seconds; no difference between Windows and Linux.  We're using the USART (programming port) which is slower than USB and we're flashing rather than reading which is slower; I haven't bothered to figure out which thing is the bottleneck.

Like before --boot sets the board to boot from flash (your sketch) on next reset.

And again --reset just resets the board.

Your target board should now be be behaving identically to the original source board.

There's an Arduino auto-erase feature in bossac that may simplify parts of this procedure, but I haven't tested it out yet.  I'm leaving as is until I can play with that command-line option.

I have now successfully cloned a Due's flash to another via 10-pin JTAG header using OpenOCD as well, though it may be a while before I update this.  I have not yet done it on Windows nor via SWD header, which seems to be one that more reliably comes pre-soldered.  For now: In any case, yes you can do it.  If you want flash via JTAG, which is less important than reading, just know that you need to issue  OpenOCD flash bank commands before the program command will work, and that if you don't the error you'll get out of the program command doesn't make this clear.

Thank you very much, it worked 100%.
And yes I meant .bin not .hex it is my mistake.
You are a life saver :)

When you say Doing so will erase your board, and then that's the end of it, you mean the .bin right?, not that the board will be somehow screwed for further work with other source codes?

That phrase refers specifically to what will happen if you connect to your programming port at 1200 baud.  The firmware that is on the atmeag16u2 that behaves as a serial transceiver has been coded such that a connection at 1200 baud  will effectively hit the erase button for you.  So, no I don't mean it will erase a file, it will erase the content of flash on the board itself.  Given that the goal here is to preserve firmware on the board, it seemed appropriate to warn against doing this thing that will completely destroy the firmware currently on the board.

Connecting to the programming port at 1200 baud wouldn't wouldn't ruin your hardware; it would ruin any chance of success at recovering the current contents of flash.


text:
Receiver sleep mode RDA5807M
Good afternoon guys!
I have a radio receiver connected to an arduino and I want it not to work all the time, but to turn on by the arduino timer for a certain time, and the rest of the time the receiver must be turned off by software.
I have a working sketch that allows you to tune this receiver, and it also allows you to re-tune the receiver (set the volume and frequency) by calling a function.
#include <Wire.h>

#define RDA5807M_RANDOM_ACCESS_ADDRESS 0x11
// registers
#define RDA5807M_REG_CONFIG 0x02
#define RDA5807M_REG_TUNING 0x03
#define RDA5807M_REG_VOLUME 0x05
// flags
#define RDA5807M_FLG_DHIZ 0x8000
#define RDA5807M_FLG_DMUTE 0x4000
#define RDA5807M_FLG_BASS 0x1000
#define RDA5807M_FLG_ENABLE word(0x0001)
#define RDA5807M_FLG_TUNE word(0x0010)
//masks
#define RDA5807M_CHAN_MASK 0xFFC0
#define RDA5807M_CHAN_SHIFT 6
#define RDA5807M_VOLUME_MASK word(0x000F)
#define RDA5807M_VOLUME_SHIFT 0
#define RDA5807M_RSSI_MASK 0xFE00
#define RDA5807M_RSSI_SHIFT 9

//uint8_t volume; // 0..15
//uint16_t freq = 1077; // 107.3FM
uint16_t reg02h, reg03h, reg05h, reg0Bh;

void setup() {
  Serial.begin(9600);
  Nastroika(1, 4, 1077); // Receiver setting: incl. or off (on, off), volume (0 ... 15), frequency MHz * 10 (107.7 = 1077)
}

void loop() {
  Nastroika(1, 4, 1077);
  delay(5000);
  Nastroika(0, 4, 1077); // Nastroika(0)
  delay(5000);
}

void setRegister(uint8_t reg, const uint16_t value) {
  Wire.beginTransmission(0x11);
  Wire.write(reg);
  Wire.write(highByte(value));
  Wire.write(lowByte(value));
  Wire.endTransmission(true);
}

uint16_t getRegister(uint8_t reg) {
  uint16_t result;
  Wire.beginTransmission(RDA5807M_RANDOM_ACCESS_ADDRESS);
  Wire.write(reg);
  Wire.endTransmission(false);
  Wire.requestFrom(0x11, 2, true);
  result = (uint16_t)Wire.read() << 8;
  result |= Wire.read();
  return result;
}

void Nastroika(byte Key, uint8_t volume, uint16_t freq) // Receiver configuration after power failure
{
  Wire.begin();
  // Регистр 02h - inclusion, settings
  if (Key == 1)
  {
    reg02h = reg02h | RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
  }
  else if (Key == 0)
  {
    reg02h = reg02h & ~RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;

  }
  setRegister(RDA5807M_REG_CONFIG, reg02h);
  // Регистр 03h - radio station selection
  // After reset in register 03h, the default value is 0
  // Thus BAND = 00 (87..108MHz), STEP = 00 (100kHz). Let's leave them as they are
  reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT; // chan = (freq - band) / space
  setRegister(RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);

  //Register 05h. Set the volume, do not change the rest of the beats
  reg05h = getRegister(RDA5807M_REG_VOLUME); // Reading the current value
  reg05h &= ~RDA5807M_VOLUME_MASK; // Resetting the bits VOLUME
  reg05h |= volume << RDA5807M_VOLUME_SHIFT; // Setting a new volume
  setRegister(RDA5807M_REG_VOLUME, reg05h);
}

I need to modify this sketch and add the ability to wake up the receiver and put it into sleep mode. There is "RDA5807M_FLG_ENABLE" here. As I understand it, you need to change it?
Added later:
The method of turning off the receiver for a while, suggested in the comments, works.
However, for everything to be correct, when calling the function when the receiver is disconnected, we will send Nastroika(0, 4, 1077); that is, when turning off, we still specify the volume and frequency, although these parameters are superfluous here. It would be correct to write simply Nastroika(0); , But this cannot be done just like that, because there should be exactly three input arguments for the function, and not one.

Switch off:
reg02h = reg02h & ~RDA5807M_FLG_ENABLE;
setRegister(RDA5807M_REG_CONFIG, reg02h);

Switch on:
reg02h = reg02h | RDA5807M_FLG_ENABLE;
setRegister(RDA5807M_REG_CONFIG, reg02h);

EDIT: (to answer a comment of Антон)
Nastroika (настройка) means "tuning". Is that right? Then I would use this method only for tuning. Create two methods one for switching off and one for switching on.
void switchOff()
{
   reg02h = reg02h & ~RDA5807M_FLG_ENABLE;
   setRegister(RDA5807M_REG_CONFIG, reg02h);
}

void switchOn()
{
   reg02h = reg02h | RDA5807M_FLG_ENABLE;
   setRegister(RDA5807M_REG_CONFIG, reg02h);
}

In the Nastroika Method you should only perform the tuning and let the module of. If you insist to switch on at the same time you could use your old version.
Example:
void Nastroika(uint8_t volume, uint16_t freq)
{
   // !!!!! This is the wrong place for Wire begin
   // move it to the setup method.
   // Wire.begin();
   reg02h = reg02h | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
   // or if you insist / you want to keep the module be started here
   // reg02h = reg02h | RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
   setRegister(RDA5807M_REG_CONFIG, reg02h);
   reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT;
   setRegister(RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);

   reg05h = getRegister(RDA5807M_REG_VOLUME);
   reg05h &= ~RDA5807M_VOLUME_MASK;
   reg05h |= volume << RDA5807M_VOLUME_SHIFT;
   setRegister(RDA5807M_REG_VOLUME, reg05h);
}

Usage:
void setup()
{
   Serial.begin(9600);
   Wire.begin();
   Nastroika(4, 1077);
}

void loop()
{
  switchOff();
  delay(5000);
  switchOn();
  delay(5000);
}

Thanks, I corrected the code according to your suggestion. If you can help me get rid of two unnecessary arguments, I will be even more grateful to you

Thank you, I did everything as you said, everything works, I'm happy. We've also fixed some bugs, thank you!


text:
Cannot program ATMEGA328PU after burning bootloader with internal clock
I have build a couple of boards that have an ATMEGA328P-AU (the 32 pin MLF, as used on the Arduino Pro Mini). If I burn a bootloader via SPI to use an external 8MHz clock, I can then use the Arduino IDE to write a program via the serial port. If I burn a bootloader to use an internal 8MHz clock, burning the bootloader is still successful but programming with the Arduino IDE does not work.
The current boards do have crystals, but I want to build the rest of the boards without a crystal, so I need to get internal clock working.
The internal (non-working) script looks like this:
avrdude -Cavrdude.conf -v -patmega328p -B4 -cusbasp -Pusb -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xE2:m
avrdude -Cavrdude.conf -c usbasp -p atmega328p -e -Uflash:w:ATmegaBOOT_168_atmega328_pro_8MHz.hex

The external (working) script looks like this:
avrdude -Cavrdude.conf -v -patmega328p -B4 -cusbasp -Pusb -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xFF:m
avrdude -Cavrdude.conf -c usbasp -p atmega328p -e -Uflash:w:ATmegaBOOT_168_atmega328_pro_8MHz.hex

By my reckoning, lfuse=0xE2 should be CKDIV8=1, CKOUT=1, SUT=10 and CKSEL=0010.
Any suggestions how to make the internal clock work?

Except for the clock division bit I never set any fuses and it works for me. For a test you could try without setting any fuses, the atmegas are set to run with the internal clock by default from my experience.

Use ISP programmer, file menu >> Sketch >> Upload using programmer, to upload the sketch instead of via UART (arduino bootloader) and completely ignore the bootloader thing. You have to choose correct programmer, file menu >> Tools >> Programmer. I suppose you spin your own pcb then pop out an ISP port is no problem. Just be aware that timing stuffs, like delay and all, would not work correctly. also you would run into trouble with UART as well. But I think add a small resonator like CSTNE16M0V51Z000R0 on PCB wouldn't be a problem since it's quite darn small and not that expensive.

Are you trying to program over serial? Serial requires a somewhat accurate clock. Maybe the RC-oscilator is to far of 8Mhz for serial to work. Can you upload a blink sketch over ISP, and have it blink with those fuse settings?


text:
Memory for inputs?
When a button is pressed, the Arduino might be busy with something (like drawing the screen). When the Arduino has finally time to check the button input, the uses might have release it already.
Is there a way that can store the input until the Arduino has time to check it?
It would be awesome if there was ic that could take care of this.
Thanks for the help!

It's called an interrupt.

I most cases, this isn't an issue. Humans are kind of slow, compared to an Arduino running at 16Mhz. Pressing a button takes tens to hundreds of milliseconds. An eternity for a CPU. Alternatively, you could add an RC circuit to the button. This has the added benefit of also debouncing the button signal.

Just a SWAG but it sounds like you are using the delay(); function, that is blocking the arduino not allowing it to do anything else until finished. Work with the millis(); function, you code will be non blocking.

The answer to your direct question, is there an IC to store an input, is yes. It's called a Set-Reset (or SR) Flip-Flop. I don't know if they're packaged standalone in an IC but they're really simple to make with a pair of cross-connected NAND gates.
But that's not really the right solution to your problem. Your code should not be so "busy" that it misses a slow input like a push-button. I quoted "busy" because it is usually delay() calls, not computations, that occupy the processor for any large amounts of time, and delay()s are to be avoided if your code has any more than 1 thing to do.
Look up the Blink Without Delay example-sketch in the Arduino IDE for the unvarnished, basic approach to doing this. Then there are libraries that can help with the low-level details of doing it - SimpleTimer, is one such. Or, if your code is stuck waiting for slow external events, don't wait for them but check for them frequently and move on immediately to something else, if they haven't taken place yet.

The basic guidance when writing Arduino applications is to do a small amount of work on every pass through the loop function, then do a little bit more on the next pass. Check all your inputs, execute logic in response to those inputs, set up unsigned long variables with future millis() values, check those values to see if a future time has arrived, and repeat.
Do not use delay(). It is the death of a cooperative system like an Arduino. When your Arduino executes a call to delay(), everything stops until the delay time has passed.

Is there a way that can store the input until the Arduino has time to check it?

No, there is no way to remember/buffer input changes within the Arduino (You could use a flipfop IC like JRobert wrote. That can give you that functionality). But there are interrupts, that you can use with pins. A triggered interrupt will really interrupt the main code from running and execute its corresponding ISR (Interrupt Service Routine), to handle the interrupt cause, and then returning to execute the main code. A microcontoller has many different interrupts, each one connected to its special hardware. There are interrupts for the Serial interface, for SPI, I2C, and also some connected to the External Interrupt pins or the PinChange Interrupt (these last two could be used with your button). So this would not "store" the input change, but it will interrupt the main code to immediately act upon the input change. So that's a different principle.
If you want to bind your button to an interrupt, you could just stay in the Arduino Framework and use the attachInterrupt() function. There are many tutorials online for that. Keep in mind, that you should never do long things inside an ISR, and functions like delay() won't work there.

That said, most likely it is not really needed to use interrupts with buttons. Humans are rather slow, thus each button press will last in the ballpark of 100ms or longer.
You could now say, that your code is doing things longer than 100ms. But here the rabbit is buried (literal translation of a german saying, meaning "there is the problem"). When starting with Arduino, one is doing many blocking things, like delay() or blocking while loops. These are often very easy to implement, but nothing else will be running during these things.
Instead you should divide up your actions into small parts. When it is time to do something, you are doing that small part and exit fast. This enables other code to run in between. A good example is the BlinkWithoutDelay example. The normal blink example uses delay(), which blocks everything else. Instead you can use the millis() function as a clock and only take action, when it is time to do so, otherwise to further fast. Much like you would bake a pizza in your oven. You won't sit in front of the oven, waiting for the pizza to be ready. You would do something else and regularly look at your clock, if it is time to take the pizza out.
You didn't show your code, so we cannot advice you more in that direction. But you can find many tutorials about it, if you search for terms like Arduino blink without delay or Arduino millis tutorial.


text:
How to stop my 16*2 lcd blink?
Here I wrote code for my weighting scale measurement. In which I added an on/off switch for my LCD display. But in defined delay time my LCD is a blink and I do not want it. I want my LCD switch on/off work on 1000 delay time effectively.
How I can do this. please guide and edit my code.
#include "HX711.h"
#include <LiquidCrystal_I2C.h>

HX711 scale(4, 5);//(DT, SCK)
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int buttonPin = 2;
int buttonState = 0;

float calibration_factor = -55;
float units;
float ounces;
float in_kg;

void setup()
{
  //  Serial.begin(9600);
  lcd.init();
  lcd.noDisplay();
  lcd.noBacklight();

  lcd.setCursor(0, 0);
  lcd.print("Calculate Weight");
  lcd.setCursor(0, 1);
  lcd.print("Loading...      ");
  delay(3000);

  scale.set_scale(calibration_factor);
  scale.tare();

}

void loop()
{
  units = scale.get_units(), 10;
  if (units < 0)
  {
    units = 0.00;
  }
  ounces = units * 0.035274;
  in_kg = units / 1000;

  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH)
  {
    lcd.setCursor(0, 1);
    lcd.print("Reading: ");
    lcd.print(in_kg);
    lcd.print("kg");

    lcd.backlight();

    // Display the text on the LCD.
    lcd.display();

    delay(3000);
    lcd.noDisplay();
    lcd.noBacklight();

  }

}

If this is the same question / project as your earlier arduino.stackexchange post you should delete this post and edit / change your earlier post.

@st2000 I deleted the previous question. please help me with this.

I am not sure what you are asking.  It appears the code will display the weight  value for 3 seconds and then turn off the back-light and blank the LCD.  And it sounds like you would like to change that from 3 seconds to 1 second.  Then all you have to do is change delay(3000) to delay(1000).

Don't use lcd.backlight() and lcd.noBacklight(), don't use lcd.noDisplay() every time your program runs the main loop() function. Set those things on once and leave them set.

@Dougie but I want to implement an on/off display and backlight through the switch on running device. SO how I do this?

You may need to clarify whether you're talking about an on/off that holds position or a momentary push button.  The latter meaning: push to turn on, push to turn off.