text:
How to edit code from Node-Red to Cayenne
I am working on a project to run some (relays or LED's) on an inputs (Pins) Arduino by esp8266-01s . now while searching on internet I found a video divided it two step that talks about the issue using a ESP8266-01. The important thing in the topic is that the person uses two codes for project :
1) The first code for esp8266.
2) The second code for arduino uno.
The most important part of the topic I want to modify the code for esp8266 . but the owner of the video uses node red website and I want to use the cayenne website . I want to specify basic commands to modify in order to work on cayenne website .
I play with esp and arduino in order to project offline.
First video , Second video
// Code to upload onto ESP8266
 #include <PubSubClient.h>
 #include <ESP8266WiFi.h>

 //EDIT THESE LINES TO MATCH YOUR SETUP
 #define MQTT_SERVER "192.168.1.117"  ///YourMQTTBroker'sIP
 const char* ssid = "Weems_2GHz";
 const char* password = "1029384756";

 char* Topic = "inTopic"; //subscribe to topic to be notified about

 WiFiClient wifiClient;

 void setup() {
 //initialize the light as an output and set to LOW (off)

 //start the serial line for debugging
 Serial.begin(9600);
 delay(100);

//start wifi subsystem
WiFi.begin(ssid, password);
//attempt to connect to the WIFI network and then connect to the MQTT server
reconnect();

//wait a bit before starting the main loop
  delay(2000);
}

PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

void loop(){

//reconnect if connection is lost
if (!client.connected() && WiFi.status() == 3) {reconnect();}

//maintain MQTT connection
client.loop();

//MUST delay to allow ESP8266 WIFI functions to run
delay(20);

}

void callback(char* topic, byte* payload, unsigned int length) {

//convert topic to string to make it easier to work with
String topicStr = topic;

//Print out some debugging info
////Serial.println("Callback update.");
//Serial.print("Topic: ");
//Serial.println(topicStr);

//turn the light off if the payload is '0' and publish to the MQTT server a confirmation message
if (payload[0] == '0'){
Serial.print("0");
respond();}
if(payload[0] == '1'){
Serial.print("1");
respond();}
if (payload[0] == '2'){
Serial.print("2");
respond();}
if(payload[0] == '3'){
Serial.print("3");
respond();}
if (payload[0] == '4'){
Serial.print("4");
respond();}
if(payload[0] == '5'){
Serial.print("5");
respond();}
if (payload[0] == '6'){
Serial.print("6");
respond();}
if(payload[0] == '7'){
Serial.print("7");
respond();
}

}
void respond(){
delay(5);
if (Serial.available()) {
//read serial as a character
char ser = Serial.read();
switch (ser) {
  case 'a':
client.publish("outTopic", "Relay 1 is ON");
break;
  case 'b':
client.publish("outTopic", "Relay 1 is OFF");
break;
  case 'c':
client.publish("outTopic", "Relay 2 is ON");
break;
  case 'd':
client.publish("outTopic", "Relay 2 is OFF");
break;
  case 'e':
client.publish("outTopic", "Relay 3 is ON");
break;
  case 'f':
client.publish("outTopic", "Relay 3 is OFF");
break;
  case 'g':
client.publish("outTopic", "Relay 4 is ON");
break;
  case 'h':
client.publish("outTopic", "Relay 4 is OFF");
break;
}//switch
}//if
}//void
void reconnect() {

//attempt to connect to the wifi if connection is lost
if(WiFi.status() != WL_CONNECTED){

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

//make sure we are connected to WIFI before attemping to reconnect to MQTT
if(WiFi.status() == WL_CONNECTED){
// Loop until we're reconnected to the MQTT server
while (!client.connected()) {
  //Serial.print("Attempting MQTT connection...");

  // Generate client name based on MAC address and last 8 bits of microsecond counter
  String clientName;
  clientName += "esp8266-";
  uint8_t mac[6];
  WiFi.macAddress(mac);
  clientName += macToStr(mac);

  //if connected, subscribe to the topic(s) we want to be notified about
  if (client.connect((char*) clientName.c_str())) {
    Serial.print("\tMTQQ Connected");
    client.subscribe(Topic);
  }

  //otherwise print failed for debugging
  else{Serial.println("\tFailed."); abort();}
  }
  }
  }

  //generate unique name from MAC addr
  String macToStr(const uint8_t* mac){

  String result;

  for (int i = 0; i < 6; ++i) {
  result += String(mac[i], 16);

  if (i < 5){
  result += ':';
  }
  }

  return result;
  }

/* control Relays via serial with numbers*/
/// Upload to Arduino uno
 void setup(){
 Serial.begin(9600);
 //Set all the pins we need to output pins
 pinMode(12, OUTPUT);
 pinMode(11, OUTPUT);
 pinMode(10, OUTPUT);
 pinMode(9, OUTPUT);
 digitalWrite(12, HIGH);
 digitalWrite(11, HIGH);
 digitalWrite(10, HIGH);
 digitalWrite(9, HIGH);
 }

 void loop (){
 if (Serial.available()) {
 //read serial as a character
 char ser = Serial.read();

 //NOTE because the serial is read as "char" and not "int", the read value must be compared to character numbers
 //hence the quotes around the numbers in the case statement
 switch (ser) {
  case '0':
    digitalWrite(12, LOW);
    Serial.print("a");
    break;
  case '1':
    digitalWrite(12, HIGH);
    Serial.print("b");
    break;
  case '2':
    digitalWrite(11, LOW);
    Serial.print("c");
    break;
  case '3':
    digitalWrite(11, HIGH);
    Serial.print("d");
    break;
  case '4':
    digitalWrite(10, LOW);
    Serial.print("e");
    break;
  case '5':
    digitalWrite(10, HIGH);
    Serial.print("f");
    break;
  case '6':
    digitalWrite(9, LOW);
    Serial.print("g");
    break;
  case '7':
    digitalWrite(9, HIGH);
    Serial.print("h");
    break;

   }
  }
 }

sadly, neither "backend" has anything to do with arduino code, so this is off-topic. that said, there's not really much in your code that needs changing to use either one. I do wonder what the nano is for if your running code on the ESP; is it needed?

@dandavis I did not understand anything from what you say. What do you mean by the backend. And what do you mean by being outside the topic?

Just change the MQTT details to those you need for the cayenne website.

@Majenko the edit will do on code for esp yes . And i want specify line important in order to work change this code . Plese edit code or specify line change for code

I suggest you look at some of the example code that should exist for working with cayenne, then compare that with your existing code. And yes, on the esp.

@KhalidAbu-Khadija, I'm not sure, but I think you are missing an MQTT broker (like Mosquito for instance).  I don't think Node-RED is an MQTT broker.  Node-RED can subscribe to MQTT topics, manipulate MQTT payloads and emit MQTT messages.  But I think you still need an MQTT broker.

@st2000, there is an MQTT broker available for Node-RED

...can you point me to the web page where I can learn more @jsotola.  As I thought Node-RED will work with most any MQTT broker.  But, that Node-RED was not an MQTT broker.

...to put it another way.  You don't need Node-RED to send messages from one MQTT client to another MQTT client.  You just need an MQTT broker.  Node-RED can be complex to use and complex to install where as an MQTT broker can be simple to use and to install.

@st2000 Can you help me, brother, in this project, is there any way to contact you?

@st2000,  i say the car is available in red ... you say i thought that i could get any color .... please read my comment again .... here is the link https://flows.nodered.org/node/node-red-contrib-mqtt-broker

Sorry, I don't know anything about Cayenne.  But it sounded like you did not understand the entire workings of MQTT hence my comments above. But if this Node-RED contrib node can emulate an MQTT borker - then maybe you can get by with out using Mosquito.


text:
Faster TimerOne with Teensy 4.0 (600MHz)
I have a teensy 4.0 which runs at 600MHz, and is double superscaler (i.e. can execute two instructions per clock cycle, sometimes). I need an interrupt to happen faster than every microsecond. I've calculated that it's possible for the processor to run the my code at that speed with some reasonable overhead. Can TimerOne (or similar) be set to produce an interrupt more than once per microsecond?
Thanks in advance.

Are you talking about the library TimerOne or about the timer itself?

@chrisl well I've been using the TimerOne library but if the only way to get a faster interrupt is to not use that library then that's OK with me.

https://forum.pjrc.com/

You can use the TeensyTimerTool for this. It provides a generic interface to the hardware timers (TMR, GPT, PIT) and 20 software timers. Since the coupling of the timer peripherals to the ARM core is rather inefficient, the software timers might be a better fit for sub micro second interrupts.
If you prefer the hardware timers I suggest to use a GPT timer (also supported by the lib). You can configure it to use a 150MHz clock instead of the standard 24MHz clock. So something like 2MHz interrupt rate should be feasible.
Documentation can be found here: https://github.com/luni64/TeensyTimerTool/wiki

I had a similar problem with the Teensy 3.5.
I found that using the "Periodic Interrupt Timer (PIT)" let me generate interrupt every 300 ns.
I imagine that with a Teensy 4.0, it must be possible to generate an interrupt every 100 ns.
Here is the code which works for me on my Teensy 3.5,
with comments in french and some references in the comments.
I test the signal on an oscilloscope.
// ex00305_Timer_pit0_isr_rapide.ino
/*

FONCTIONNE TRES BIEN

Le signal n'est pas très stable, mais acceptable.
J'imagine que d'autres routines d'interruption perturbe la précision, comme la routine millis()

L'instruction suivante améliore la stabilité. visiblement.
NVIC_SET_PRIORITY(IRQ_PIT_CH0, 0);

Le but est de tester l'utilisation du Timer1 .c.f
/home/bg/Arduino/Teensy/Teensy_3_5_manual_K64P144M120SF5RM.pdf
Page 1083, Chapter 41 : "Periodic Interrupt Timer (PIT)"

Pour la gestion des timers PIT, c.f.
====================================
https://github.com/loglow/PITimer/blob/master/PITimer.cpp

********************************************************************************** */

#define PINOUT1 34
#define LEDRED  24
#define LEDYELLOW  25
#define LEDGREEN  26

volatile byte bEtat = 0;

void setup() {
    //============
    pinMode(PINOUT1, OUTPUT);
    digitalWriteFast(PINOUT1, HIGH);

    pinMode(33, OUTPUT);
    pinMode(34, OUTPUT);
    pinMode(LEDRED, OUTPUT);  digitalWriteFast(LEDRED, LOW);
    pinMode(LEDYELLOW, OUTPUT);  digitalWriteFast(LEDYELLOW, LOW);
    pinMode(LEDGREEN, OUTPUT);  digitalWriteFast(LEDGREEN, LOW);

    //if (SIM_SCGC6_PIT == 0b100000000000000000000000) digitalWriteFast(LEDYELLOW, HIGH);
    SIM_SCGC6 |= SIM_SCGC6_PIT; // C.f. page 317.  PIT Clock Gate Control   SIM_SCGC6_PIT == 0b100000000000000000000000

    // C.f. : /home/bg/.arduino15/packages/teensy/hardware/avr/1.58.1/cores/teensy3/kinetis.h
    // #define NVIC_ENABLE_IRQ(n) (*((volatile uint32_t *)0xE000E100 + ((n) >> 5)) = (1 << ((n) & 31)))
    // enable IRQ Interrupt
    NVIC_SET_PRIORITY(IRQ_PIT_CH0, 0); // Haute priorité, pour ne pas être perturbé par d'autres interrupt. Amélioration visible !
    NVIC_ENABLE_IRQ(IRQ_PIT_CH0);
    PIT_TCTRL0 = 3; // 0b011;  // enable Timer 0 interrupts ; start Timer 0   IRQ_PIT_CH0 == 48  Dans #elif defined(__MK64FX512__)
    //if (IRQ_PIT_CH0 == 48) digitalWriteFast(LEDGREEN,  HIGH);

    // Efface le flag du timer, pour permettre d'autres interruptions, nécessaire au départ
    PIT_TFLG0 = 1;

    // L'ordre des instruction a de l'importance !
    //""""""""""""""""""""""""""""""""""""""""""""
    PIT_MCR = 0;  // turn on PIT
    //PIT_LDVAL0 = 600-1;  // == 10 micro secondes setup timer 0 for xxx cycles Fréqu = 60 MHz  dt = 16.666 ns
    //PIT_LDVAL0 = 120-1;  // == 2 micros second
    //PIT_LDVAL0 = 60-1;   // == 1 micros second
    //PIT_LDVAL0 = 30-1;   // == 500 ns
    //PIT_LDVAL0 = 24-1;   // == 400 ns
    //PIT_LDVAL0 = 21-1;   // == 350 ns
    //PIT_LDVAL0 = 20-1;   // == 333 ns
    //PIT_LDVAL0 = 18-1;   // == 300 ns
    PIT_LDVAL0 = 120-1;
} // setup

void loop() {
    //===========
} // loop

void pit0_isr() {  // C.f. mk20dx128.c
    //===============
    // J'espère pouvoir gérer un temps

    // Efface le flag du timer, pour permettre d'autres interruptions
    // Doit être mis en début de routine !!!
    PIT_TFLG0 = 1;

    if (bEtat) {
        digitalWriteFast(PINOUT1, HIGH);
        //digitalWriteFast(LEDRED,  HIGH);
        bEtat = 0;
    }
    else {
        bEtat = 1;
        digitalWriteFast(PINOUT1, LOW);
        //digitalWriteFast(LEDRED,  LOW);
    }

} // pit0_isr

source: Stack Exchange

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

sort: votes


text:
What is the equivilent of PORTx for Teensy (4.0)?
I've seen people use code like PORTB |= 0x1 << 6 to set the sixth bit of PORTB in arduino. I understand that this is significantly faster than using digitalWrite. How can this be done using a modern Teensy (i.e. 3.6 or 4.0) if at all?

Step one: Read the datasheet for the chip on the board. Step two: implement what you have learned from step 1. Step three: profit.

@Majenko one slight problem with that: how do I know which pins correspond to which ports? Also, I find the datasheets like that very confusing so there's no guarantee that I'd be able to figure out exactly what's going on.

You need to relate the information in the datasheet to the source code for the core and board definition.

For the Teensy 3.6 you need to get to grips with section 63.3 of https://www.nxp.com/docs/en/reference-manual/K66P144M180SF5RMV2.pdf

DDRA is equivalent to GPIOA_PDDR. PORTA is GPIOA_PDOR, PINA is GPIOA_PDIR

@Majenko alright thanks very much I'll read up about that.

For those chips there are particular memory addresses that correspond to particular bits and the setting or clearing operations. Rather than a read, or, write three-instruction cycle, you can set or clear the bit with a single write instruction at a special bit-specific address. There's some mention of it in "5.2.1 Aliased bit-band regions" in the manual @Majenko listed.  Also, look into Teensy's digitalWriteFast(pin,val) instruction which optimizes into the equivalent code per the 63.3 section @Majenko referenced.

All Teensies support digitalWriteFast out of the box. digitalWriteFast compiles to just setting the bit in the right port register. You can not do that faster by direct register manipulation.
However, if for some reason you do want to manipulate the registers directly here the pin/gpio relation for the T4. (Generated by the sketch described here: https://github.com/luni64/TeensyTimerTool/wiki/Avoid-PWM-timer-clashes")
Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
00  |  GPIO6_03  |  FLEX_PWM1
01  |  GPIO6_02  |  FLEX_PWM1
02  |  GPIO9_04  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
04  |  GPIO9_06  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
06  |  GPIO7_10  |  FLEX_PWM2
07  |  GPIO7_17  |  FLEX_PWM1
08  |  GPIO7_16  |  FLEX_PWM1
09  |  GPIO7_11  |  FLEX_PWM2
10  |  GPIO7_00  |  QUAD1
11  |  GPIO7_02  |  QUAD1
12  |  GPIO7_01  |  QUAD1
13  |  GPIO7_03  |  QUAD2
14  |  GPIO6_18  |  QUAD3
15  |  GPIO6_19  |  QUAD3
16  |  GPIO6_23  |  no pwm
17  |  GPIO6_22  |  no pwm
18  |  GPIO6_17  |  QUAD3
19  |  GPIO6_16  |  QUAD3
20  |  GPIO6_26  |  no pwm
21  |  GPIO6_27  |  no pwm
22  |  GPIO6_24  |  FLEX_PWM4
23  |  GPIO6_25  |  FLEX_PWM4
24  |  GPIO6_12  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
26  |  GPIO6_30  |  no pwm
27  |  GPIO6_31  |  no pwm
28  |  GPIO8_18  |  FLEX_PWM3
29  |  GPIO9_31  |  FLEX_PWM3
30  |  GPIO8_23  |  no pwm
31  |  GPIO8_22  |  no pwm
32  |  GPIO7_12  |  no pwm
33  |  GPIO9_07  |  FLEX_PWM2
34  |  GPIO8_15  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1

#### Sorted by PWM timer
Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
12  |  GPIO7_01  |  QUAD1
11  |  GPIO7_02  |  QUAD1
10  |  GPIO7_00  |  QUAD1
13  |  GPIO7_03  |  QUAD2
18  |  GPIO6_17  |  QUAD3
15  |  GPIO6_19  |  QUAD3
14  |  GPIO6_18  |  QUAD3
19  |  GPIO6_16  |  QUAD3
24  |  GPIO6_12  |  FLEX_PWM1
01  |  GPIO6_02  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
34  |  GPIO8_15  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1
00  |  GPIO6_03  |  FLEX_PWM1
08  |  GPIO7_16  |  FLEX_PWM1
07  |  GPIO7_17  |  FLEX_PWM1
09  |  GPIO7_11  |  FLEX_PWM2
04  |  GPIO9_06  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
06  |  GPIO7_10  |  FLEX_PWM2
33  |  GPIO9_07  |  FLEX_PWM2
28  |  GPIO8_18  |  FLEX_PWM3
29  |  GPIO9_31  |  FLEX_PWM3
23  |  GPIO6_25  |  FLEX_PWM4
22  |  GPIO6_24  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
02  |  GPIO9_04  |  FLEX_PWM4
27  |  GPIO6_31  |  no pwm
17  |  GPIO6_22  |  no pwm
26  |  GPIO6_30  |  no pwm
30  |  GPIO8_23  |  no pwm
31  |  GPIO8_22  |  no pwm
32  |  GPIO7_12  |  no pwm
21  |  GPIO6_27  |  no pwm
20  |  GPIO6_26  |  no pwm
16  |  GPIO6_23  |  no pwm

#### Sorted by GPIO register:
Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
01  |  GPIO6_02  |  FLEX_PWM1
00  |  GPIO6_03  |  FLEX_PWM1
24  |  GPIO6_12  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
19  |  GPIO6_16  |  QUAD3
18  |  GPIO6_17  |  QUAD3
14  |  GPIO6_18  |  QUAD3
15  |  GPIO6_19  |  QUAD3
17  |  GPIO6_22  |  no pwm
16  |  GPIO6_23  |  no pwm
22  |  GPIO6_24  |  FLEX_PWM4
23  |  GPIO6_25  |  FLEX_PWM4
20  |  GPIO6_26  |  no pwm
21  |  GPIO6_27  |  no pwm
26  |  GPIO6_30  |  no pwm
27  |  GPIO6_31  |  no pwm
10  |  GPIO7_00  |  QUAD1
12  |  GPIO7_01  |  QUAD1
11  |  GPIO7_02  |  QUAD1
13  |  GPIO7_03  |  QUAD2
06  |  GPIO7_10  |  FLEX_PWM2
09  |  GPIO7_11  |  FLEX_PWM2
32  |  GPIO7_12  |  no pwm
08  |  GPIO7_16  |  FLEX_PWM1
07  |  GPIO7_17  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
34  |  GPIO8_15  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
28  |  GPIO8_18  |  FLEX_PWM3
31  |  GPIO8_22  |  no pwm
30  |  GPIO8_23  |  no pwm
02  |  GPIO9_04  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
04  |  GPIO9_06  |  FLEX_PWM2
33  |  GPIO9_07  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
29  |  GPIO9_31  |  FLEX_PWM3

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


text:
HTTP parsing with authentication in Arduino + ethernet shield
i am trying to parse a page from the route by using Arduino + Ethernet shield. before Arduino testing. I tested my code via python as it shows below. from this code i can get the data as i wish where we need authenticate user name and pass word to access to the router, as you see, here ( admin , admin) in the same time i have to used output variable to get only the data required. Python code is does it.
Python code:
My_url = "http://192.168.8.1/update.cgi"
r = requests.post (My_url, auth=('admin', 'admin'),data = 'output=netdev' )
print(r.status_code)
print(r.headers['content-type'])
print(r.encoding)
print(r.text)

The output is:
200
text/javascript
ISO-8859-1
netdev = {
 'WIRED':{rx:0x84154,tx:0x5a0cba}
,'BRIDGE':{rx:0x7e680,tx:0x59d98a}
,'WIRELESS0':{rx:0x0,tx:0x0}
,'WIRELESS1':{rx:0x0,tx:0x0}
}

Now i am trying to do that by using Arduino + Ethernet shield and i would like print the output on the serial port as it is showing below. Here the router is server and the Arduino is client.
My problem is the POST request with the authentication, How I can do it ( POST with authentication + 'output=netdev' like in python code ). Please any idea .. Many thanks in advanced
Arduino code :
#include <Ethernet.h>
#include <SPI.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
IPAddress server(192,168,8,1);  // numeric IP for Google (no DNS)
//char server[] = "jsonplaceholder.typicode.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 8, 100);
IPAddress myDns(   8, 8, 8, 8);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true) {
        delay(1); // do nothing, no point running without Ethernet hardware
      }
    }
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip, myDns);
  } else {
    Serial.print("  DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }
  delay(1000);
  Serial.println("connecting...");

  if (client.connect(server, 80)) {
    Serial.print("connected to ");
    Serial.println(client.remoteIP());
    // Make a HTTP request:

    client.println("POST /update.cgi HTTP/1.0");
    client.println("Host: 192.168.8.1");
    client.println("Connection: close");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  //if (client.available()) {
  while (client.available()) {
    char c = client.read();
    Serial.print(c);

  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }

}

Arduino output
Initialize Ethernet with DHCP:
  DHCP assigned IP 192.168.8.107
connecting...
connected to 192.168.8.1
HTTP/1.0 401 Unauthorized
Server: httpd
Date: Sat, 01 Jan 2011 00:27:00 GMT
WWW-Authenticate: Basic realm="DR3800"
Content-Type: text/html
Connection: close

<TITLE>401 Unauthorized</TITLE>

401 Unauthorized

Authorization required.

disconnecting.

Thank you Dougie for your anser. I used it , please you can see it in my code below where i used this library it gives no error for GET request , but when i use it ti POST request it gives same authentication problem as you see . where the POST request is important to get the data from .cgi page . Maybe i use that in wrong way .. any advice ? thanks
void loop() {
  Serial.println("making GET request with HTTP basic authentication");
  String contentType = "update.cgi";
  String postData = "output=netdev";

  client.beginRequest();
  client.get("/"+contentType);
  client.sendBasicAuth("admin", "admin"); // send the username and password for authentication
  client.endRequest();

   // read the status code and body of the response
  int statusCode = client.responseStatusCode();
  String response = client.responseBody();

  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);

  Serial.println("Wait five seconds");
  delay(5000);
}

The output is ok
making GET request with HTTP basic authentication
Status code: 200
Response:
Wait five seconds

But for POST as follows :
void loop() {
  Serial.println("making GET request with HTTP basic authentication");
  String contentType = "update.cgi";
  String postData = "output=netdev";

  client.beginRequest();
  client.post("/",contentType , postData);
  client.sendBasicAuth("admin", "admin"); // send the username and password for authentication
  client.endRequest();

   // read the status code and body of the response
  int statusCode = client.responseStatusCode();
  String response = client.responseBody();

  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);

  Serial.println("Wait five seconds");
  delay(5000);
}

the output is :
making GET request with HTTP basic authentication
Status code: 401
Response: <TITLE>401 Unauthorized</TITLE>

401 Unauthorized

Authorization required.

Wait five seconds

Rather than trying to send your own GET/POST request by hand coding it, use https://github.com/arduino-libraries/ArduinoHttpClient which does it all for you.

Use the sendBasicAuth method to send auth. data.

Thank you for your answer. I used it , please you can see it in my code [    String contentType = "update.cgi";
String postData = "output=netdev";
client.beginRequest();
client.post("/",contentType , postData);
client.sendBasicAuth("admin", "admin"); // send the username and password for authentication
client.endRequest(); ] and stil i have problem with POST methode. any idea

Please vote up my answer and mark it as accepted.


text:
ESP8266 reseted due to relay / AC plugged
My Wemos card is reseting for unknown reason. For example, the pump plugged on the relay works fine till 1am and then the pump stop. After a few research I figured out the ESP should reset because all internal parameters are reseted.

My hardware is simple Wemos card + relay + sensors (not here because not connected yet).

My program is quite complex. I can command/configure the wemos via webservice (ex relay on pin 5 with on 5min/off 10min).
https://github.com/TittyPanda/ESP-commander/blob/master/ESP-COMMANDER

OK if no AC device is connected on relay (no reset)
OK if a light is connected on relay
The issue occurs only when the water pump is connected

Maybe it's an electrical/electromagnetical thing because the pump has motor. What do you think ?
Thanks,
EDIT
Power part are done with common wires from power extension cord
AC-DC converter 5 V 1A 1.5A 500mA

Pump 40W 3000L/H 220V 50Hz

What is your pump current consumption? this sound like that you have a power supply that can't deliver sufficient power to the overall circuitry.

It could well be EMI induced by the pump. You need to specify more details about exactly what hardware you're using - what pump, what power supplies, what wiring, etc.

Thanks I added pump & converter info in the post

@hcheung I'm not sure because the whole system works fine when nothing is plugged on relays (I'm testing a light again but during 24h)

try a shorter and thicker extension cord, and a large capacitor (1000uf+) on the 5v rail.

I installed the L-C Power Filter between the breadboard and ESP as advised by @gdb.
24 h - no reset -> it was the solution.
Thanks all of you for your help and your time.
The topic is closed for me.

Try add some power filter like this:

Between the breadboard and ESP board.

Thanks @gbg It remains me my electronic/physic courses :) - found with  L-C Power Filter and google image ! https://fr.aliexpress.com/item/32842662140.html

it was the solution


text:
Newbie interfacing MLX90614 with arduino Due (Atmel3X8E)
I am a newbie trying to interface the infrared temperature sensor MLX90614 with the arduino Due. But it keeps sending out junk values in the serial monitor. I've tried it out on the Arduino Mega and it works perfectly. What might be the problem and how do I rectify it?
Thanks in advance.
#include <Wire.h>
#include <Adafruit_MLX90614.h>

Adafruit_MLX90614 mlx = Adafruit_MLX90614();

void setup() {
  Serial.begin(9600);
  Serial.println("Adafruit MLX90614 test");
  mlx.begin();
}
void loop() {
  Serial.print("Ambient = "); Serial.print(mlx.readAmbientTempC());
  Serial.print("*C\tObject = "); Serial.print(mlx.readObjectTempC()); Serial.println("*C");
  Serial.print("Ambient = "); Serial.print(mlx.readAmbientTempF());
  Serial.print("*F\tObject = "); Serial.print(mlx.readObjectTempF()); Serial.println("*F");
  Serial.println();
  delay(500);
}

Please include your code into your question

How do you wire the MLX90614 with the board? What MLX90614 interface/shield you are using? One thing that I could think of is that Arduino Mega is a 5V development board, while Arduino Due is a 3.3v development board.

@chrisl the code is the same example in the library to check the working of the sensor.

hcheung .. no, i am not using any shield for this..


text:
POST request using WiFiEsp.h library
I'm using an arduino uno and ESP8266 (esp01) with the WiFiEsp library to connect to WiFi and POST data, connecting to WiFi works just fine.
I need to send a POST request, but I can't get it to work as I want.
 #include "WiFiEsp.h"
 // Emulate Serial1 on pins 7/8 if not present
 #ifndef HAVE_HWSERIAL1
 #include "SoftwareSerial.h"
 SoftwareSerial Serial1(6, 7); // RX, TX
 #endif
 char ssid[] = "Innovating-Guest"; // your network SSID (name)
 char pass[] = "wireless"; // your network password
 int status = WL_IDLE_STATUS; // the Wifi radio's status

 char server[] = "10.66.240.66";//http://10.66.240.66:8000/loadimage
 WiFiEspClient client; // Initialize the Ethernet client object

 void setup()
 {
 // initialize serial for debugging
 Serial.begin(9600);
 // initialize serial for ESP module
 Serial1.begin(9600);
 // initialize ESP module
 WiFi.init(&Serial1);
 // check for the presence of the shield
 if (WiFi.status() == WL_NO_SHIELD)
 {
 Serial.println("WiFi shield not present");
 // don't continue
 while (true);
 }

 // attempt to connect to WiFi network
 while ( status != WL_CONNECTED) {
 Serial.print("Attempting to connect to WPA SSID: ");
 Serial.println(ssid);
 // Connect to WPA/WPA2 network
 status = WiFi.begin(ssid, pass);
 }
 // you're connected now, so print out the data
 Serial.println("You're connected to the network");
 printWifiStatus();
 Serial.println();
 Serial.println("Starting connection to server...");
 // if you get a connection, report back via serial
 if (client.connect(server, 8000)) {
 Serial.println("Connected to server");
 String temp= "12.22";
 String humd= "23.33";
 String batt= "100";

 String content ="{\"temperature\": + temp +,\"humidity\":+ humd +,\"batteryPer\": + batt + }";
 client.println("POST /loadimage HTTP/1.1");
 client.println("Host: 10.66.240.66:8000");
 client.println("Accept: */*");
 client.print("Content-Length: ");
 client.println(content.length());
 client.println("Content-Type: application/json");
 client.println();
 client.println(content);
 }
 }
 void loop()
 {

 while (client.available()) {
 char c = client.read();
 Serial.write(c);
 }
 // if the server's disconnected, stop the client
 if (!client.connected()) {
 Serial.println();
 Serial.println("Disconnecting from server...");
 client.stop();
 // do nothing forevermore
 while (true);
  }
 }

 void printWifiStatus()
 {
 // print the SSID of the network you're attached to
 Serial.print("SSID: ");
 Serial.println(WiFi.SSID());

 // print your WiFi shield's IP address
 IPAddress ip = WiFi.localIP();
 Serial.print("IP Address: ");
 Serial.println(ip);

 // print the received signal strength
 long rssi = WiFi.RSSI();
 Serial.print("Signal strength (RSSI):");
 Serial.print(rssi);
 Serial.println(" dBm");
 }

Can anyone help me to know that why this error is coming.
Thanks in advance.

POST /loadimage HTTP/1.1, with a space between POST and the uri.

@hcheung there is no change when use a space between POST and uri

Nevertheless, POST /uri HTTP/1.1 is the correct syntax for http POST command.

@hcheung I update with correction but POST is not happens by that. Is there any chnage in my server uri?? can you please help me

it looks like the server disconnects. if you can update the AT firmware to AT 1.7 (SDK 3), I recommend my WiFiEspAT library. in debug mode it shows all communication  with the AT firmware so it would be simpler to troubleshoot

Also change client.println("Content-Length: "); to client.print("Content-Length: ");

@Juraj `AT version:1.3.0.0(Jul 14 2016 18:54:01)
SDK version:2.0.0(5a875ba)

@hcheung I also try changing to client.print("Content-Length: "); It s not working now also.

I suspect, the problem is on the server side. So, you may use Wireshark or server logs to see, what exact query you are sending.

@gbg thanks for the reply. But the server side is done by another one and only duty i have is to post data obtained in arduino to the server. And when i try to send with nodemcu board it is working. So i think there is no problem with server side.

Okay, anyway, you can use the Wireshark to see, what exact bytes sends ESP to the server. To do this, your PC must be in the same WiFi network with the ESP

@gbg thanks for the help. Sorry but i can't post data now also.

Host should contain the port. So Host: 10.66.240.66:8000 should be Host: 10.66.240.66. Secondly; I think the JSON string isn't generated properly. I think it should be:  String content ="{\"temperature\":"+ temp +",\"humidity\":"+ humd + ",\"batteryPer\":" + batt + "}";

@Gerben thanks for the reply but by changing the host also there is no chnage. It shows as disconnecting from server now also. I don't have any idea what the problem is.

Is there even a problem? You'd expect the server to close the connection once it has received your request and send back a response. The only thing is that you'd expect to get back some response. Try temporarily removing the while (true); at the end of the loop and replace it with a delay(100);. Then see what happens

@Gerben, this is based on the Arduino WebClient example and the loop() works as it is to receive the HTTP response. but the client doesn't connect here at all

@Gerben I try by removing while(true); but same result cames.

@Juraj your are absolutely correct. Can you make any solutions other  than changing the esp version and library?

do you have an USB to TTL Serial adapter? wire the RX pin of the adapter to TX pin of the esp8266 additionally to the wire to Arduino. this way you can see everything the AT firmware sends to Arduino.

@Juraj I dont have an USB to TTL converter with me.


text:
ESP8266 and WPA2 PSK network
I'm having some issues with esp8266 connecting to a wifi network. I'm testing with a hotspot from a mobile phone.  If I set the network to open (no security) my code below works without any issue. If I enable security, WPA2 PSK (I'm assuming that means the personal version) and add the password to the code it fails to connect. Any suggestions as to what the issue might be?
//load softserial library
#include <SoftwareSerial.h>

//set a boolean constant variable to true
//#define DEBUG true
const boolean DEBUG = true;

//RX (pin 2) goes to TX on esp8266, TX (pin 3) goes to RX on esp8266
SoftwareSerial esp8266(2, 3);

//LED pin anode (long leg) is 13 and cathode (short leg) GND
int LED = 13;

//LED status array - led 0 is OFF (0) at startup.
int ledarray[] = {0};

void setup()
{
  //set the LED pin as output
  pinMode(LED, OUTPUT);

  //open the serial port
  Serial.begin(9600);

  //start esp8266 module (note: your esp's baud rate might be different)
  esp8266.begin(115200);

  //reset esp8266 module
  senddata("AT+RST\r\n", 2000, DEBUG);

  //set esp8266 as access point mode
  //senddata("AT+CWMODE=1\r\n", 1000, DEBUG);

  //set esp8266 as wireless station mode (web server)
  senddata("AT+CWMODE=1\r\n", 1000, DEBUG);

  //set network SSID and password if esp8266 is activate as station mode else comment out
  senddata("AT+CWJAP=\"test\", \"\"\r\n", 6000, DEBUG);

  //get ip address for esp8266
  senddata("AT+CIFSR\r\n", 2000, DEBUG);

  //configure esp8266 for multiple connections
  senddata("AT+CIPMUX=1\r\n", 1000, DEBUG);

  //turn on esp8266 server on port 80
  senddata("AT+CIPSERVER=1,80\r\n", 1000, DEBUG);
}

void loop()
{
  //is the esp8266 sending a message
  if(esp8266.available())
  {
    //if received data from esp8266
    if (esp8266.find("+IPD,"))
    {
      //subtract 48 because the read() function returns the ASCII decimal
      //value and 0 (the first decimal number) starts at 48
      int connectionid = esp8266.read() - 48;

      //read the url sent by the client, look for the variable (?)
      String msg;
      esp8266.find("?");
      delay(100);
      msg = esp8266.readStringUntil(' ');
      String command = msg.substring(0);

      //HTML served to browser
      String webpage = "<title>LED WEB SWITCH</title>";
      webpage += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">";
      webpage += "
LED WEB SWITCH
";

      //if command is T (variable passed in button link on webpage)
      if (command == "T")
      {
        //if position 0 of ledarray is 1
        if (ledarray[0] == 1)
        {
          //turn LED off
          digitalWrite(LED, LOW);

          //set position 0 of ledarray to 0
          ledarray[0] = 0;

          //add text to webpage
          webpage += "
LED STATUS OFF
";
        }
        else
        {
          //turn the LED on
          digitalWrite(LED, HIGH);

          //set position 0 of ledarray to 1
          ledarray[0] = 1;

          //add text to webpage
          webpage += "
LED STATUS ON
";
        }
      }
      else
      {
        //add text to webpage
        webpage += "
LED STATUS OFF
";
      }

      //add the button (notice the href has a '?T')
      webpage += "TAP";

      //create a senddata string to send the wenbpage to the esp8266
      String cipsend = "AT+CIPSEND=";
      cipsend += connectionid;
      cipsend += ",";
      cipsend += webpage.length();
      cipsend += "\r\n";
      senddata(cipsend, 500, DEBUG);
      senddata(webpage, 500, DEBUG);

      //create a string closecommand, append the connection id, a return and newline
      String closecommand = "AT+CIPCLOSE=";
      closecommand += connectionid;
      closecommand += "\r\n";

      //send the closecommane
      senddata(closecommand, 500, DEBUG);
    }
  }
}

void senddata(String command, const int timeout, boolean debug)
{
  //send the received command to the esp8266
  esp8266.print(command);

  //set int variable to the number of millisends since Arduino began
  long int time = millis();

  //while the time and the timeout is less than the number of millisends since Arduino began
  while((time + timeout) > millis())
  {
    //while the esp8266 is sending messages
    while(esp8266.available())
    {
      //display output in the serial window
      Serial.write(esp8266.read());
    }
  }
}

fwiw, it a lot easier to debug if you program the esp instead of the uno.

SoftwareSerial doesn't work reliable at 115200 baud. change the baud rate in AT firmware and in sketch to 9600 baud

I've tried following the advice here: https://arduino.stackexchange.com/questions/24156/how-to-change-baudrate-of-esp8266-12e-permanently
//start at 115200
esp8266.begin(115200);
//set to 9600 and start again
senddata("AT+UART_DEF=9600,8,1,0,0\r\n", 2000, DEBUG);
esp8266.begin(9600);
This does not seem to work, at 9600 it refuses to connect to the network and doesn't give any errors.

The solution to this was nothing to do with WPA2 PSK security or the baud rate being used. In my code I had a space between the WIFI server name and password (me correctly formatting). Apparently the ESP8266 does not like this one bit and the space needs to be removed - like so:
//set network SSID and password if esp8266 is activate as station mode else comment out
senddata("AT+CWJAP=\"test\",\"\"\r\n", 6000, DEBUG);


text:
Why my 4WD Bluetooth car run so slow

Code
/*Arduino Bluetooth Controlled Car
 *  * Created by Glen Tech
 * https://www.youtube.com/glentech
  */

#include <AFMotor.h>

//initial motors pin
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor3(3);
AF_DCMotor motor4(4);

char command;

void setup()
{
  Serial.begin(9600);  //Set the baud rate to your Bluetooth module.
}

void loop(){
  if(Serial.available() > 0){
    command = Serial.read();
    Stop(); //initialize with motors stoped
    //Change pin mode only if new command is different from previous.
    //Serial.println(command);
    switch(command){
    case 'F':
      forward();
      break;
    case 'B':
       back();
      break;
    case 'L':
      left();
      break;
    case 'R':
      right();
      break;
    }
  }
}

void forward()
{
  motor1.setSpeed(1000); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwise
  motor2.setSpeed(1000); //Define maximum velocity
  motor2.run(FORWARD); //rotate the motor clockwise
  motor3.setSpeed(1000);//Define maximum velocity
  motor3.run(FORWARD); //rotate the motor clockwise
  motor4.setSpeed(1000);//Define maximum velocity
  motor4.run(FORWARD); //rotate the motor clockwise
}

void back()
{
  motor1.setSpeed(1000); //Define maximum velocity
  motor1.run(BACKWARD); //rotate the motor anti-clockwise
  motor2.setSpeed(1000); //Define maximum velocity
  motor2.run(BACKWARD); //rotate the motor anti-clockwise
  motor3.setSpeed(1000); //Define maximum velocity
  motor3.run(BACKWARD); //rotate the motor anti-clockwise
  motor4.setSpeed(1000); //Define maximum velocity
  motor4.run(BACKWARD); //rotate the motor anti-clockwise
}

void left()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(BACKWARD); //rotate the motor anti-clockwise
  motor2.setSpeed(255); //Define maximum velocity
  motor2.run(BACKWARD); //rotate the motor anti-clockwise
  motor3.setSpeed(255); //Define maximum velocity
  motor3.run(FORWARD);  //rotate the motor clockwise
  motor4.setSpeed(255); //Define maximum velocity
  motor4.run(FORWARD);  //rotate the motor clockwise
}

void right()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwise
  motor2.setSpeed(255); //Define maximum velocity
  motor2.run(FORWARD); //rotate the motor clockwise
  motor3.setSpeed(255); //Define maximum velocity
  motor3.run(BACKWARD); //rotate the motor anti-clockwise
  motor4.setSpeed(255); //Define maximum velocity
  motor4.run(BACKWARD); //rotate the motor anti-clockwise
}

void Stop()
{
  motor1.setSpeed(0); //Define minimum velocity
  motor1.run(RELEASE); //stop the motor when release the button
  motor2.setSpeed(0); //Define minimum velocity
  motor2.run(RELEASE); //rotate the motor clockwise
  motor3.setSpeed(0); //Define minimum velocity
  motor3.run(RELEASE); //stop the motor when release the button
  motor4.setSpeed(0); //Define minimum velocity
  motor4.run(RELEASE); //stop the motor when release the button
}

Welcome! Please put your code in a code block (by adding 4 spaces before each line of code) to make it more readable. Also, add a clear description in your post about your hardware, the problem you are trying to solve and what you already tried. A link to youtube is not sufficient. What battery are you using for your project?

Can you measure the battery voltage when motors is ON?

What battery are you using? A 9V block batteries (like pictured) can't supply enough current to properly run a motor.

A photo of your actual hardware would also be helpful.

Move the stop() to setup(), and add some delay() in your loop(). Your loop is too busy and constantly stop and setting the direction again and again. Also introduce a status that holds the current direction status, if the command is the same as current direction status, skip the switch setup section, it only need when the command is changed.

I can't find issue in your code that I'm convinced is your problem. Without seeing your datasheet for the motor, I would bet your issue is one of two things:
1) A 9V battery is low-current relative to most batteries I've used for powering any decent DC motors. Do you have access to a better current source you could try?
2) Every motor has a trade-off in torque vs max-speed, dictated by the internal gear-ratio. Depending on the motor type, it may not have the torque to accelerate the vehicle to a significant speed.


text:
Detect the end of playback of a MP3 file with DFPlayerMini / DFRobotDFPlayerMini.h library
For a project I'm doing I've used an ESP8266/12e, a RTC Module DS3231 and a DFplayerMini
Basically it's a caller for birds and it has to play a 12-minute long MP3. The MP3 file should be played for 2 hours at the sunrise and 2 hours before the sunset, so each time it should be played 10 times (10 × 12 = 120 minutes (2 hours))
The code I wrote so far (some parts are omitted for brevity):
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"
#include <Wire.h>
#include <RtcDS3231.h>

#define DELAY_ONPLAY 1000
#define DELAY_ONPAUSE 20000

// RTC Library (I2C)
RtcDS3231<TwoWire> rtcObject(Wire);

// MP3 Serial communication
SoftwareSerial mySoftwareSerial(14, 12);
DFRobotDFPlayerMini myDFPlayer;

// Variables
int volume, mth, day, h, m;

// State of the playback
int playbackCount = 0;
bool isPlaying = false;

RtcDateTime currentTime;

void setup() {

    mySoftwareSerial.begin(9600);
    // Start serial connection
    Serial.begin(115200);
    // Start I2C
    rtcObject.Begin();

    if (!myDFPlayer.begin(mySoftwareSerial)) {
      while(true){
        delay(10);
      }
    }

    /* Get the value of potentiometer in the range of [3..30] and
     * set the volume
     */
    setVolume();

}

void loop() {

    setVolume();
    currentTime = rtcObject.GetDateTime();    //get the time from the RTC

    mth  = currentTime.Month();
    day  = currentTime.Day();
    h    = currentTime.Hour();
    m    = currentTime.Minute();

    /* The caller is not playing: check if date and time should
     * start the playback
     */
    if (isPlaying == false) {

        if (startSunrise() || startSunset()) {
            isPlaying = true;
        }

        else {
            // Nothing to do for the next 20 seconds
            delay(DELAY_ONPAUSE);
        }
    }

    else {

      // Currently playing
      if (playbackCount < 10) {

          if (/* MP3mini_is_idle */) {

            myDFPlayer.play(1);
            playbackCount = playbackCount + 1;

          }
      }

      else {
        playbackCount = 0;
        isPlaying = false;
        Serial.print("End of playback");
      }

      delay(DELAY_ONPLAY);

    }
}

void setVolume() {

    // Get the value of potentiometer in the range of [3..30]
    volume = map(analogRead(A0), 0, 1023, 2, 30);
    volume = constrain(volume, 3, 30);
    // Set the player volume
    myDFPlayer.volume(volume);
    Serial.println(String(volume));

}

bool startSunrise() {

    /* at the sunrise the call has to be played for 2 hours */

    if (mth == 2) {
        if ((day == 20 && h == 7 && m == 8) ||
            (day == 21 && h == 7 && m == 6) ||
            ...
            (day == 28 && h == 6 && m == 54) ||
            (day == 29 && h == 6 && m == 52)) { return true; }
    }

    if (mth == 3) {
        if ((day == 1  && h == 6 && m >= 49) ||
            (day == 2  && h == 6 && m >= 47) ||
            (day == 3  && h == 6 && m >= 45 ) ||
            (day == 4  && h == 6 && m >= 43) ||
            ...
            (day == 27 && h == 6 && m >= 0) ||
            (day == 28 && h == 5 && m >= 58)) { return true; }
    }

    return false;
}

bool startSunset() {

    /* 2 hours before sunset the call has to be played for 2 hours */

    if (mth == 2) {
        if ((day == 20 && h == 15 && m >= 41) ||
            (day == 21 && h == 15 && m >= 42) ||
            ...
            (day == 28 && h == 15 && m >= 52) ||
            (day == 29 && h == 15 && m >= 54)) { return true; }
    }

    if (mth == 3) {
        if ((day == 1  && h == 15 && m >= 56) ||
            (day == 2  && h == 15 && m >= 58) ||
            (day == 3  && h == 15 && m >= 59) ||
            (day == 4  && h == 16 && m >= 1) ||
            ...
            (day == 27 && h == 16 && m >= 31) ||
            (day == 28 && h == 16 && m >= 33)) { return true; }
    }

    return false;
}

The part I'm stuck on is
  if (playbackCount < 10) {

      if (/* MP3mini_is_idle */) {

        myDFPlayer.play(1);
        playbackCount = playbackCount + 1;

      }

  }

How do I detect in the if condition if the MP3 is actually playing before play it again?
I think a 12-minute delay() is not the right approach.
In the image below the DFPlayerMini pinout: I noticed It has a BUSY pin  but I haven't found examples so far that uses this pin to detect the playback state.

Thanks for any suggestion.

Have you googled for this? I directly found this site. The table under the image, that you have in your question, states, that the BUSY pin is LOW, when the DFPlayer is playing something. Isn't that exactly, what you want?

Thank you. I'll try as soon as possibile and I'll give you a feedback in a few hours

Alternatively you could create a new audio file that has the bird song, repeated 10 times, in it. PS if you go with the repeated playback code, I'd have the song repeat till it reaches 120minutes (using millis()), instead of repeating it 10 times. That way if you ever change the sound file, and that file has a different length, you wouldn't have to update the code.

@chrisl, I've solved checking the busy pin. If you like to put the comment as the answer I would be happy to accept it

As @chrisl alread said, you could use the busy pin. Or a simple serial query
myDFPlayer.readState();

If the result is something like DFPlayerPlayFinishe the actual track is complete.

I've solved checking the busy pin, thank you

The busy pin, means that the flash memory is being accessed. So its not the same as "track being played".


text:
Substitute multiple potentiometers for push buttons and single potentiometers
this is my first post here.
For some time I have been struggling with a problem and would like to know if anyone has a solution to share.
I am building a 4 tone sequencer, where I use 4 potentiometers to change the pitch of each tone beat. I want to add more beats to the sequencer so I would like to have an elegant solution instead of keep adding potentiometers.
 My idea was to use 1 potentiometer to control the pitch and use multiple push buttons with the single potentiometer for this process.
 All in all it goes like this:
 - When switch1=HIGH, pitch1=analogRead(A0);
 - When switch2=HIGH, pitch2=analogRead(A0);
 The problem is that when I change pitch1 and pitch2 the end up getting the same values as soon as I press their switch. My code looks like this:
   if(switch1state==HIGH)
  {
    Tone1Pot=analogRead(A0); // 0 – 1023
    pitch1=Tone1Pot/13;
  }

tone(speakerPin, notes[pitch1], 200);

Serial.print(pitch1);
Serial.print("     ");
delay(tempo);

if(switch2state==HIGH)
  {
    Tone2Pot=analogRead(A0); // 0 – 1023
    pitch2=Tone2Pot/13;
  }

tone(speakerPin, notes[pitch2], 200);

Serial.print(pitch2);
Serial.print("     ");
delay(tempo);

I would really like to store that analog reading value when I press switch1 and keep it until switch1 goes HIGH again.
EDIT:
Let me try to explain the issue better:
I have 2 push buttons and 1 potentiometer, all of them are inputs. The code I am aiming for is to do the following: 1 - While pressing push button1 I want to read the value of potentiometer and store it to a variable1. When the button1 is not pressed I want to keep that variable stored. 2 - While pressing push button2 I want to read the value of potentiometer and store it to a variable2. When the button2 is not pressed I want to keep that variable stored.
I have successfully achieved this, however the problem comes when I press button1 again to adjust variable1, variable2 is also getting adjusted in the process, even when I am not pressing button2
Chris - The push buttons are correct since I can change the states of the digital pins when I press them ( and I measure the 5V when pressed). I do not need the buttons to be pressed at the same time. What I need is the buttons to trigger the event of storing potentiometer data only when either one of them is pressed accordingly.
jsotola - Sorry for the bad explanation. I hope this one is better.
Code:
#include "pitches.h"

int notes[]={

NOTE_B1,
NOTE_C2,
NOTE_CS2,
NOTE_D2,
NOTE_DS2,
NOTE_E2,
NOTE_F2,
NOTE_FS2,
NOTE_G2,
NOTE_GS2,
NOTE_A2,
NOTE_AS2,
NOTE_B2,
NOTE_C3,
NOTE_CS3,
NOTE_D3,
NOTE_DS3,
NOTE_E3,
NOTE_F3,
NOTE_FS3,
NOTE_G3,
NOTE_GS3,
NOTE_A3,
NOTE_AS3,
NOTE_B3,
NOTE_C4,
NOTE_CS4,
NOTE_D4,
NOTE_DS4,
NOTE_E4,
NOTE_F4,
NOTE_FS4,
NOTE_G4,
NOTE_GS4,
NOTE_A4,
NOTE_AS4,
NOTE_B4,
NOTE_C5,
NOTE_CS5,
NOTE_D5,
NOTE_DS5,
NOTE_E5,
NOTE_F5,
NOTE_FS5,
NOTE_G5,
NOTE_GS5,
NOTE_A5,
NOTE_AS5,
NOTE_B5,
NOTE_C6,
NOTE_CS6,
NOTE_D6,
NOTE_DS6,
NOTE_E6,
NOTE_F6,
NOTE_FS6,
NOTE_G6,
NOTE_GS6,
NOTE_A6,
NOTE_AS6,
NOTE_B6,
NOTE_C7,
NOTE_CS7,
NOTE_D7,
NOTE_DS7,
NOTE_E7,
NOTE_F7,
NOTE_FS7,
NOTE_G7,
NOTE_GS7,
NOTE_A7,
NOTE_AS7,
NOTE_B7,
NOTE_C8,
NOTE_CS8,
NOTE_D8,
NOTE_DS8
};

int Tone = 0;
int speakerPin = 3;

int switch1=6;
int switch2=7;
int switch3=8;
int switch4=9;
int switch5=10;
int switch6=11;
int switch7=12;
int switch8=13;

void setup() {

Serial.begin(9600);

pinMode(switch1, INPUT);
pinMode(switch2, INPUT);
pinMode(switch3, INPUT);
pinMode(switch4, INPUT);
pinMode(switch5, INPUT);
pinMode(switch6, INPUT);
pinMode(switch7, INPUT);
pinMode(switch8, INPUT);

}

void loop() {

 // get potentiometers inputs
//int TonePot = analogRead(A0); // 0 – 1023
//int DurationPot = analogRead(A1); // 0 – 1023
int TempoPot = analogRead(A2); // 0 – 1023

int Tone1Pot;
int Tone2Pot;
int Tone3Pot;
int Tone4Pot;
int Tone5Pot;
int Tone6Pot;
int Tone7Pot;
int Tone8Pot;

int Duration1Pot;
int Duration2Pot;
int Duration3Pot;
int Duration4Pot;
int Duration5Pot;
int Duration6Pot;
int Duration7Pot;
int Duration8Pot;

// calculate corresponding, divide by 13 as we have 77 pitches. 1023/77 ~ 13
int pitch1;
int pitch2;
int pitch3;
int pitch4;
int pitch5;
int pitch6;
int pitch7;
int pitch8;

int pitch1stored;
int pitch2stored;

int noteduration1 = Duration1Pot/8;
int noteduration2 = Duration2Pot/8;
int noteduration3 = Duration3Pot/8;
int noteduration4 = Duration4Pot/8;
int noteduration5 = Duration5Pot/8;
int noteduration6 = Duration6Pot/8;
int noteduration7 = Duration7Pot/8;
int noteduration8 = Duration8Pot/8;

int tempo = TempoPot;

//Get state of switches if HIGH or LOW
int switch1state=digitalRead(switch1);
int switch2state=digitalRead(switch2);
int switch3state=digitalRead(switch3);
int switch4state=digitalRead(switch4);
int switch5state=digitalRead(switch5);
int switch6state=digitalRead(switch6);
int switch7state=digitalRead(switch7);
int switch8state=digitalRead(switch8);

////////////////////////////////////////Sound generation code /////////////////////////////////

if(switch1state==HIGH)
  {
    Tone1Pot=analogRead(A0); // 0 – 1023
    pitch1=Tone1Pot/13;
  }

tone(speakerPin, notes[pitch1], 200);

//tone(speakerPin, 0, 200);}// make the tone mute

Serial.print("pitch1= ");
Serial.print(pitch1);
Serial.print("     ");
delay(tempo);

if(switch2state==HIGH)
  {
    Tone2Pot=analogRead(A0); // 0 – 1023
    pitch2=Tone2Pot/13;
  }

tone(speakerPin, notes[pitch2], 200);

Serial.print("pitch2= ");
Serial.print(pitch2);
Serial.print("     ");
delay(tempo);

if(switch3state==HIGH)
  {
    Tone3Pot=analogRead(A0); // 0 – 1023
    pitch3=Tone3Pot/13;
  }

tone(speakerPin, notes[pitch3], 200);

Serial.print("pitch3= ");
Serial.print(pitch3);
Serial.print("     ");
delay(tempo);
}

what causes this state?  switch1=HIGH

The description of your problem is unclear to me, please elaborate more. Also please provide the full code, not just a small part of it.

store that analog reading value when I press switch1 and keep it until switch1 goes HIGH again  ... what does that mean? ... what does switch1 goes HIGH again actually mean? ... i think that your main problem is that you do not actually know how you want the device to work

I cannot see, how your code would show the described behavior (assuming that, you have connected the buttons correctly with a pulldown resistor). But your code can be greatly simplified, which would make it less error prone.
You have 8 buttons, which screams for the usage of arrays (IMO you should always use arrays, if you have more than 2 or 3 equal buttons). First put the button pins into an array:
#define N_BUTTONS 8
int button_pins[N_BUTTONS] = {6, 7, 8, 9, 10, 11, 12, 13};

Then define an array to hold the measured pitches (here initialized with 0):
int pitches[N_BUTTONS] = {0};

In your setup() function you can loop over the button_pins array to set them as input:
for(int pin : button_pins) pinMode(pin, INPUT);

In the loop() function you again loop over the button pins, but this time you check, if the current button is pressed. If yes, you measure the analog voltage, calculate the pitch and save it into the corresponding element of the pitches array:
for(int button=0;button < N_BUTTONS;button++){
    if(digitalRead(button_pins[button])){
        pitches[button] = analogRead(A0)/13;
    }
}

This always works for multiple pressed buttons at once.
Also you should avoid calls to delay() in your loop() function. That is just time, that the Arduino cannot do anything, including checking your buttons. If you want to do something timed, you should use a non-blocking coding style, like in the BlinkWithoutDelay example, that comes with the Arduino IDE. Basically it uses the millis() function as a clock, checking regularily, if the needed time has passed and only doing something if it had passed; letting other code execute, if not. There are tons of tutorials about this on the web.
As you have seen above, I didn't include the tone() function in my answer. That is because you should decouple your input and output code. The code above is the input code. It saves the wanted pitches into the corresponding array. Then, after that code, you can write all the code you need for outputting the pitches as tones (however you actually want to output them). The only real logical connection between these 2 parts of code is the pitches array. That makes it easier to have more and different inputs (for example if you wanted to have a reset button, which sets all the pitches at onece to a predefined value). Also the function of the input code (which needs to very regularily check the buttons, to be responsive) is not disturbed by the output code.

Thank you so much for the support. I will change my code accordingly and will get back to you to show the results.

I am trying to compile your code but encountered a problem which I cannot resolve
for(int button=0;button < N_BUTTONS;button++){     if(digitalRead(button_pins[button])){         pitches[button] = analogRead(A0)/13;     } }
The above code gives me the following error:
"exit status 1
expected primary-expression before ';' token"
Any thoughts?

The bit of code, that you are showing, is ok. The error must lay in the rest of the code, most probably above

I cant seem to find where the error is. I have looked for the whole code, maybe I am missing something. Error code:
**Arduino: 1.8.10 (Windows 10), Board: "Arduino/Genuino Uno"
C:\Users\teclast\Documents\Arduino\Sequencer_Project_Version0.1\Sequencer_Project_Version0.1.ino: In function 'void loop()':
Sequencer_Project_Version0.1:105:36: error: expected primary-expression before ';' token
for (int button=0; button<N_BUTTONS; button++){
                                ^

exit status 1
expected primary-expression before ';' token**

I have been trying to get that bit of code to work and it doesn't let me use the code:
'for(int button=0;button < N_BUTTONS;button++){'
If I change N_BUTTONS to 8  the code gets accepted.
With this I can change the value of pitches[0] with the analog read and button[0], however I cannot change the value of pitches[1]  afterwards and so on.

Oh, f***, I forgot to set the define to 8, you are totally right. Of course it must be defined as 8. I changed the code in my answer, now it should work

Thank you. That fixed it. It is working now as expected.
Really glad I asked for help since I don't think I was getting there by myself.

So based on the information you provided I understand that the issue is that both the if(switch1state==HIGH) and the `if(switch2state==HIGH)' statements evaluate to true if either switch is flipped. That means one of the following things is happening:
1) Somewhere in your code you're mixing their values and assigning ones value to the other
2) Your configuration of the digitalRead pins is wrong (either wrong pins or wrong pupdr config as I've seen incorrect pull-up and pull-down resistors propagate unexpected behavior across the ground)
3) your wires are crossed. If you're using a breadboard make sure you know how it's connected internally. Some swap between horizontal and vertical rows.


text:
Arduino Nano clone doesn't upload Linux
I've been trying to upload sketch to Arduino Nano clone (CH340G RS232 to USB converter). I have ArchLinux. My port is detected as /dev/ttyUSB0 (Official Arduino Uno is /dev/ttyACM0). After trying to upload a sketch avrdude responds with
avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x44

or
avrdude: stk500_getsync(): can't communicate with device: resp=0x88

After using verbose output it seems like it does not read from the arduino back to PC. I have all my permissions correct and everything was working to this date. I also used many arduinos which I also burned bootloader on using my Arduino Uno. Everything also works on seconds PC with Windows. Any ideas?
Linux log:
/usr/share/arduino/arduino-builder -dump-prefs -logger=machine -hardware /usr/share/arduino/hardware -hardware /home/jakub/.arduino15/packages -tools /usr/share/arduino/tools-builder -tools /home/jakub/.arduino15/packages -libraries /home/jakub/Arduino/libraries -fqbn=arduino:avr:nano:cpu=atmega328 -vid-pid=1A86_7523 -ide-version=10809 -build-path /tmp/arduino_build_539099 -warnings=all -build-cache /tmp/arduino_cache_182117 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.arduinoOTA.path=/home/jakub/.arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=/home/jakub/.arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.avrdude.path=/home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -verbose /usr/share/arduino/examples/01.Basics/Blink/Blink.ino
/usr/share/arduino/arduino-builder -compile -logger=machine -hardware /usr/share/arduino/hardware -hardware /home/jakub/.arduino15/packages -tools /usr/share/arduino/tools-builder -tools /home/jakub/.arduino15/packages -libraries /home/jakub/Arduino/libraries -fqbn=arduino:avr:nano:cpu=atmega328 -vid-pid=1A86_7523 -ide-version=10809 -build-path /tmp/arduino_build_539099 -warnings=all -build-cache /tmp/arduino_cache_182117 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.arduinoOTA.path=/home/jakub/.arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=/home/jakub/.arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.avrdude.path=/home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -verbose /usr/share/arduino/examples/01.Basics/Blink/Blink.ino
Using board 'nano' from platform in folder: /home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2
Using core 'arduino' from platform in folder: /home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2
Detecting libraries used...
/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2/cores/arduino -I/home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2/variants/eightanaloginputs /tmp/arduino_build_539099/sketch/Blink.ino.cpp -o /dev/null
Generating function prototypes...
/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2/cores/arduino -I/home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2/variants/eightanaloginputs /tmp/arduino_build_539099/sketch/Blink.ino.cpp -o /tmp/arduino_build_539099/preproc/ctags_target_for_gcc_minus_e.cpp
/usr/bin/arduino-ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /tmp/arduino_build_539099/preproc/ctags_target_for_gcc_minus_e.cpp
Kompilujem projekt...
/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -Wall -Wextra -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2/cores/arduino -I/home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2/variants/eightanaloginputs /tmp/arduino_build_539099/sketch/Blink.ino.cpp -o /tmp/arduino_build_539099/sketch/Blink.ino.cpp.o
Compiling libraries...
Compiling core...
Using precompiled core: /tmp/arduino_cache_182117/core/core_arduino_avr_nano_cpu_atmega328_6ffe6e1951fbeab8145453327f70df2d.a
Linking everything together...
/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-gcc -Wall -Wextra -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o /tmp/arduino_build_539099/Blink.ino.elf /tmp/arduino_build_539099/sketch/Blink.ino.cpp.o /tmp/arduino_build_539099/../arduino_cache_182117/core/core_arduino_avr_nano_cpu_atmega328_6ffe6e1951fbeab8145453327f70df2d.a -L/tmp/arduino_build_539099 -lm
/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /tmp/arduino_build_539099/Blink.ino.elf /tmp/arduino_build_539099/Blink.ino.eep
/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-objcopy -O ihex -R .eeprom /tmp/arduino_build_539099/Blink.ino.elf /tmp/arduino_build_539099/Blink.ino.hex
/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-size -A /tmp/arduino_build_539099/Blink.ino.elf
Projekt zaberá 924 bytov (3%) pamäte pre program. Maximum je 30720 bytov.
Globálne premenné zaberajú 9 bytov (0%)  dynamickej pamäti, 2039 bytov zostáva pre lokálne premenné. Maximum je 2048 bytov.
/home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/bin/avrdude -C/home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyUSB0 -b115200 -D -Uflash:w:/tmp/arduino_build_539099/Blink.ino.hex:i

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 "/home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf"
     User configuration file is "/home/jakub/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

     Using Port                    : /dev/ttyUSB0
     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

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xfc

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xfc

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xfc
         Hardware Version: 4238814
         Firmware Version: 21984432.4
         Topcard         : Unknown

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xfc

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xfc

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xfc

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xfc
         Vtarget         : 0.0 V
         Varef           : 1992555.2 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x88

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xfc
avrdude: AVR device initialized and ready to accept instructions

Reading |
avrdude: arduino_read_sig_bytes(): (a) protocol error, expect=0x10, resp=0xfc
avrdude: error reading signature data for part "ATmega328P", rc=-3
avrdude: error reading signature data, rc=-3

avrdude done.  Thank you.

Windows log:
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Adamko\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328 -ide-version=10807 -build-path C:\Users\Adamko\AppData\Local\Temp\arduino_build_858804 -warnings=all -build-cache C:\Users\Adamko\AppData\Local\Temp\arduino_cache_611368 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.2.1.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Program Files (x86)\Arduino\examples\01.Basics\Blink\Blink.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Adamko\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328 -ide-version=10807 -build-path C:\Users\Adamko\AppData\Local\Temp\arduino_build_858804 -warnings=all -build-cache C:\Users\Adamko\AppData\Local\Temp\arduino_cache_611368 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.2.1.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Program Files (x86)\Arduino\examples\01.Basics\Blink\Blink.ino
Using board 'nano' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Detecting libraries used...
"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\sketch\\Blink.ino.cpp" -o nul
Generating function prototypes...
"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\sketch\\Blink.ino.cpp" -o "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\preproc\\ctags_target_for_gcc_minus_e.cpp"
"C:\\Program Files (x86)\\Arduino\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\preproc\\ctags_target_for_gcc_minus_e.cpp"
Kompilujem projekt...
"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -Wall -Wextra -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\sketch\\Blink.ino.cpp" -o "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\sketch\\Blink.ino.cpp.o"
Compiling libraries...
Compiling core...
Using precompiled core: C:\Users\Adamko\AppData\Local\Temp\arduino_cache_611368\core\core_arduino_avr_nano_cpu_atmega328_0c812875ac70eb4a9b385d8fb077f54c.a
Linking everything together...
"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-gcc" -Wall -Wextra -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/Blink.ino.elf" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\sketch\\Blink.ino.cpp.o" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/..\\arduino_cache_611368\\core\\core_arduino_avr_nano_cpu_atmega328_0c812875ac70eb4a9b385d8fb077f54c.a" "-LC:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804" -lm
"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/Blink.ino.elf" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/Blink.ino.eep"
"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/Blink.ino.elf" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/Blink.ino.hex"
"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-size" -A "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/Blink.ino.elf"
Projekt zaberá 930 bytov (3%) pamäte pre program. Maximum je 30720 bytov.
Globálne premenné zaberajú 9 bytov (0%)  dynamickej pamäti, 2039 bytov zostáva pre lokálne premenné. Maximum je 2048 bytov.
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\Adamko\AppData\Local\Temp\arduino_build_858804/Blink.ino.hex:i

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

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

         Using Port                    : COM3
         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\Adamko\AppData\Local\Temp\arduino_build_858804/Blink.ino.hex"
avrdude: writing flash (930 bytes):

Writing | ################################################## | 100% 0.16s

avrdude: 930 bytes of flash written
avrdude: verifying flash memory against C:\Users\Adamko\AppData\Local\Temp\arduino_build_858804/Blink.ino.hex:
avrdude: load data flash data from input file C:\Users\Adamko\AppData\Local\Temp\arduino_build_858804/Blink.ino.hex:
avrdude: input file C:\Users\Adamko\AppData\Local\Temp\arduino_build_858804/Blink.ino.hex contains 930 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.12s

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

avrdude done.  Thank you.

UPDATE Added the avrdude logs and command line.

Comments are not for extended discussion; this conversation has been moved to chat.

The problem is in kernel ch341 driver. Using 5.3.3 on Archlinux and 5.6 rc1.
https://github.com/torvalds/linux/blob/e33eab9ded328ccc14308afa51b5be7cbe78d30b/drivers/usb/serial/ch341.c
This driver version compiled using this Makefile
obj-m += ch341-m.o

all:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

reload: all
        sudo rmmod ch341-m ||true
        sudo insmod ./ch341-m.ko

Made it upload again. Hope it will be solved in kernel soon. I think the problem is addressed here
https://github.com/torvalds/linux/commit/35714565089e5e8b091c1155517b67e29118f09d#commitcomment-37154772
But the guy said it was solved in 5.6 rc1 which was not in my case.

I get make[2]: *** No rule to make target '/home/jrs/Builds/ch341-driver/ch341-m.o', needed by '__build'.  Stop. How does that Makefile work, what prerequisites do you have to have in place?

Makefile is a build configuration file. If you download the link I provided (the first one) and save it with a name "ch341-m" which is said in the mamefile, to the same directory you can use "make" and "make reload" you should have ch341 driver installed. For more questions move to chat in the question comment. Thank you.

Got it working now by downloading the whole kernel source, copying the file you linked to into drivers/usb/serial and following https://wiki.archlinux.org/index.php/Compile_kernel_module. Thank you for the quick answer!

Happy to help :)

I think you should try disconnecting any VCC port you have and see if it uploads if it does, after uploading the code reconnect the VCC ports again.

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Do we have to calibrate LDR before using it in a project?
I am doing a project with Arduino, making a synthesizer, in which an LDR is used.
Before connecting the Arduino to a power source and use the project, do I need to calibrate the LDR like it is explained in Arduino website ?

Either pick some values and hopes if works in most cases. Or have the software keep track of the minimum and maximum values, and use that to 'scale' the light input to a normalize range. You could have the user do a "calibration" routine before using it, by putting their hand over the sensor, and removing their hand completely, and thus getting the max and min values.

An LDR is a pretty inaccurate device. It just gives you a number which relates to darkness or brightness. How do those numbers relate to darkness and brightness? Well, only in a very vague way. All you can really say with any confidence is that bigger numbers mean brighter light, and smaller numbers mean darker darkness.
Even after "calibration" the numbers are pretty meaningless in any real-world sense.
All the "calibration" does is give a rough guide to the range of the numbers produced in any given lighting situation. It's then up to you to program your sketch in such a way that it works within the ranges of those numbers.
And yes, those numbers will change depending on the current lighting situation.
You could incorporate some form of "calibration" routine in your sketch to adjust any relevant values and calculations, or you could just provide some interface for tweaking values. Or your system may just really not care. It's impossible to know until you actually start creating your system.

A good example of this is if you want a program that detects when an object is placed over the sensor and blocks the light.  In that case you wouldn't normally want to write the code such that it looks for some particular value that means darkness, because the number you get from a particular level of darkness changes.  So instead of writing code to look for some particular darkness threshold, you would write the code such that you look for large negative changes in the reading.  Maybe anytime it changes by more than a certain amount in some short time consider it covered.

My application was a little different. My illumination/light source was fixed (and exact). I compensated the sensor for temperature. The results I obtained were very exact and repeatable.
Here are my temperature compensation results.


text:
Random characters transmitted from ESP8266 to Arduino
Below is  the code for getting a value from Firebase and sending the received data to arduino for performing necessary action.
The code here here sends a string "o" to arduino once
//uploaded to ESP8266
.
.
.
if (cu_st == "c")
  {
    sent = 0;
  }
  cu_st = Firebase.getString("feeder");
   if (cu_st == "o")
   {
    Serial.println("\t\trecd req to feed");
    if(sent == 0)
    {
      esp.print("o");
      sent =1;
      cu_st = "c";
      Serial.println("setting feeder to close in firebase");
      Firebase.setString("feeder" ,"c");

   }
.
.
.

Below is the code that gets the value, carries out necessary actions.
//uploaded to arduino
.
.
.
void feed_cmd()
{
  while(ArduinoUno.available())
  {
    char valve = ArduinoUno.read();
    Serial.print("feeder cmd recd ");
    Serial.println(valve);
    if(valve=='o')
    {
       digitalWrite(led, HIGH);
       //feeder.write(0); //open position
       open_time = millis();
       feeder = 1 ;
       Serial.println("I am opening feeder");
    }
  }
}

void close_feed()
{

  if(feeder == 1)
  {
   close_time = millis();
   if(close_time - open_time > 5000)
  {
    feeder = 0;
    digitalWrite(led , LOW);
    Serial.println("I am closing feeder") ;
  }
  }
}
.
.
.

My expectation/understanding is that:
feed_cmd() continually checks for any data
As soon as it receives data LED turns ON and after 5 sec close_feed() turns OFF the LED.
But what happens is that the while() in feed_cmd() continually executes showing some random data and also all of what I said above is also being carried out! (pic attached)

Why is there random serial data, even after sending only once and even after reading the sent data?
Is it bad coding / hardware?
Thanks for reading through and would really appreciate it if you can help me sort it out!!
Edit I found this link smthg abt pin voltages  when I was looking for possible explanation for my code's behaviour, If somebody can simplify it and explain it, it'd be better !!

SoftwareSerial at 115200 baud?

@Juraj Serial monitor is set at 9600 baud , softwareserial i.e sending and receiving data from ESP is set at 4800 baud... so is this the issue?

are both SoftwareSerial on 4800 baud?

@Juraj Yes, they are! Here's smthg I tried, pls let me know if you can make sense of this: i just ran arduino code(disconnecting power to esp8266 but not the data lines between them) , every time arduino sent data, the while loop in feed_cmd gave out 23 bytes(i modified the above code and got 255 or 254 as output to softserial.read() )   then I removed those data lines and saw that while sending data, the while loop no longer got executed

@Juraj I'm begining to think that it's a hardware problem, in my arduino , pins 0-7 are exposed(i.e without those  black female connector heads, it just has 'u' shaped pins ) so i used female connectors to connect to them.. I made sure they weren't touching but still every time data was sent, i was getting additional bytes being read . So i thought maybe there's some short circuit and chose 2 pins that are farther away, but now I'm getting additional 16 bytes

The baud rates, voltages, and timing all have to match up for serial communication to work right.
So, set both of your devices to the same baudrate (you specify the number in Serial.begin()), and ensure they're connected properly. (voltages match, TX to RX, and ground is connected)
You can just read/print the serial input to the arduino with something like Serial.print(softSerial.read()) in your code if you think you don't have serial wired up right.
Also in an unrelated issue; the esp32 spits out data on its main serial line at 115200 when it boots up which you can not disable. you can use the serial port afterwards though.
Here's a copy of what gets printed out on one of mine;
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1044
load:0x40078000,len:8896
load:0x40080400,len:5816
entry 0x400806ac

misread the question as esp32. I think the 8266 spits data out on boot @ 74880 baud, but can't confirm if I did that to the board I was testing, or if it came like that. Other than different baudrate on bootup, the answer is the same.

here's how i have wrote the code for Softserial : in Arduino SoftwareSerial ArduinoUno(3,2) // rx | tx  in esp8266 SoftwareSerial esp(D2 , D3) //rx | tx While wiring, I have wired 3 -> D3 and 2 -> D2. As far as power supplies go, I have connected them both to PC's usb port . In both codes I have kept Serial.begin(9600) and SoftwareSerial.begin(4800)

The baudrate (that number in parentheses after .begin() ) needs to be the same number on both devices. Also, if you have a 5V Uno (by which I mean the high-voltage on a pin is 5V), you could damage your esp8266 by connecting the two together.


text:
i am having Strange issues when trying to read form gps serial connection
I have an Adafruit Ultimate GPS connected to a MEGA2560. I am trying to get the data from the buffer and do other data processing at the same time, however. when i allow other processing to be done the output becomes garbled such as below. the first out is correct and then becomes garbled and outputs now useful data.
16:34:54.466 -> $GPGGA,163453.155,,,,,0,00,,,M,,M,,*7F
16:34:57.111 -> $GPRMC,163453.155,V,,,,$GP$GPGGA,1$GPGGA,$GPGGA

    void loop()
    {

    GetTotalPressure();
      char c = GPS.read();
      Serial.print(c);
       if (GPS.newNMEAreceived()) {

        if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
          return;  // we can fail to parse a sentence in which case we should just wait for another
      }
      if (timer2 > millis())  timer2 = millis();

      if (millis() - timer2 > 1000) {
        timer2 = millis(); // reset the timer
    GPSScreenUpdate();
      SDcardSave();

      }

When GetTotalPressue is commented out The GPS serial output is correct when it is no the error above happens.
GetTotalPressure is below the sensor is connected to a I2C bus
void GetTotalPressure() {
  Totalpressure = ms5611.readPressure();

Many Thanks

Please, link to the GPS library you are using.

https://github.com/adafruit/Adafruit_GPS

You are not reading the GPS often enough. The method
Adafruit_GPS::read() is documented in the comments embedded in the
source code:

Read one character from the GPS device.
Call very frequently and multiple times per opportunity or the buffer
  may overflow if there are frequent NMEA sentences. An 82 character
  NMEA sentence 10 times per second will require 820 calls per second,
  and once a loop() may not be enough. Check for newNMEAreceived() after
  at least every 10 calls, or you may miss some short sentences.
returns: The character that we received, or 0 if nothing was available

Accessing the I2C bus makes loop() slower, slow enough that you get a
buffer overflow, as explained above. I suggest that, instead of reading
a single character per loop iteration, you read as many as are present
in the buffer:
void loop()
{
    GetTotalPressure();

    // Empty the GPS port receive buffer.
    while (GPS.available()) {
        char c = GPS.read();
        Serial.print(c);
    }

    // Parse any newly received NMEA sentence.
    if (GPS.newNMEAreceived()) {  // clears the newNMEAreceived flag
        if (!GPS.parse(GPS.lastNMEA()))
            return;
    }

    // Display and log location every second.
    if (millis() - timer2 > 1000) {
        timer2 = millis(); // reset the timer
        GPSScreenUpdate();
        SDcardSave();
    }
}

As an aside, I removed the line
if (timer2 > millis()) timer2 = millis();

which serves no useful purpose. If you are trying to detect millis()
overflows, you are almost certainly doing something wrong.


text:
ESP8266 not working with MPU 6050 over wire library and I2C
I'm trying to use this version of ESP8266 to access MPU 6050. However, it's not working.
https://www.amazon.com/gp/product/B07HF44GBT/ref=ppx_yo_dt_b_asin_title_o07_s00?ie=UTF8&psc=1 i.e. NodeMCU CP2102 ESP-12E
The code worked with nano very fine. However, when I tried to scan the I2C device, it's said I2C device not found.
I have tried
  Wire.begin(D2, D1);

and
  Wire.begin(4, 5);

i.e. to change the pin to GIOP 4 5 in case if the default was not working.
I have also tried to put a large capacitor between the power lines, still not working.
Why ESP8266 does not work with MPU 6050?(Serial and wire together)
Updates:
Sometimes it does say device found, but after two updates, it turned to be not found again.
Updates 2:
I watched the video and did what G6EJD suggested, i.e. restarted the IDE and everything. Now it's reading data. However, the data reading was somehow incorrect by a large factor.
For example, at flat the device is reading
42.63/-38.37/7.82

for angle x,angle y,and angular speed z with complementary filter applied and steady at flat surface. It worked for nano but not for ESP 8266.
Also, I tried to adjust the circuit like the spectrum dandavis suggested. I tried resistor range from 4.7 k to 10, even directly connect to the power source. The attempts also included 100 $\mu$F capacitor and power board to stabilize the noise. Both pull up and pull down has been attempted as well as changing boards. However, none of those were working and the issue persisted. The pull up resistor did not seem to be response to what the device was reading.
Update 3:
The power consumption has been ruled out and a pair of 100k resistor was also attempted. Not working.

how long are the leads? do you use pullup resistors?

@dandavis the wire is about 10cm each, what's a pull up resistors?

https://learn.sparkfun.com/tutorials/i2c/i2c-at-the-hardware-level

@dandavis It didn't work even if I put in the resistor.

@dandavis I tried to adjust the circuit like the spectrum you suggested. I tried resistor range from 4.7 k to 10, even directly connect to the power source. The attempts also included 100 $\mu$F capacitor and power board to stabilize the noise. Both pull up and pull down has been attempted as well as changing boards. However, none of those were working and the issue persisted.

I am not an arduino veteran, but I could not get I2C communication to work between two of the exact same MCU (NodeMCU CP2102 ESP-12E). There are a couple of issues on github pointing out issues but the devs don't seem in any hurry to do anything about it.

I've been struggling with getting anything with the MPU6050's to work with either a D1 Mini or an older NodeMCU v1. I'm using D1/D2.
I've used the i2cdevlib MPU6050 library as well as the Electronic Cats' version.
I've used an assortment of sketches and even tried code which uses just Wire (no MPU6050 specific libs).

The best I've been able to get is the Electronic Cats MPU6050 library, without DMP, where at least it thinks the MPU6050 has been connected to, but it just puts out 0's as raw values.
The second "best", maybe, was some code that just used plain Wire, but except for Wire.endTransmission() returning success (and I had to slow loop() down for that), its numbers are gibberish (either 0's, or Z will just increment.  Nothing is affected by the movement of the board itself).

The DMP versions always fail to initialize the DMP.
I've tried 8.2k and 4.1k pullups on D1 and D2.
It works fine on an atmega32u4-based Pro Micro 16.

try to use
Wire.begin(0x68);

instead of
  Wire.begin(D2, D1);