message:
Different Output Voltages from Same Source?

I'm wondering whether it is possible to wire multiple buck converters with different voltage requirements and amperage draws to the same power source (this idea is for controlling a radio-controlled boat). Going off other related questions this seems to be possible ([1][1], [2][2]).

My background is in programming, not electronics, so the terminology is difficult for me to understand. I'm getting a grasp on voltage and amperage. My problem is always understanding how electricity can be "split" into different modules. In my understanding, this below would be a parallel circuit and that should be fine.

 1. Are there any gotchas to consider with this type of circuit, or is this the totally normal way of doing things (eg. like wiring a house out of a breaker box)?
 2. Is there a better way to do this?
 3. This won't cause a short circuit, right?

[![SLA battery powering different voltages diagram][3]][3]

  [1]: https://electronics.stackexchange.com/questions/260312/are-there-limits-for-the-number-of-buck-converters-i-can-run-off-a-single-power
  [2]: https://electronics.stackexchange.com/questions/481666/using-buck-converter-and-ldo-from-the-same-power-source
  [3]: https://i.stack.imgur.com/Lmmo3.png

body:
> Are there any gotchas to consider with this type of circuit, or is this the totally normal way of doing things (eg. like wiring a house out of a breaker box)?

That's a perfectly normal way of wiring it.

> Is there a better way to do this?

No, it's how I'd do it.

> This won't cause a short circuit, right?

Not intentionally, no. However it's always good to add a fuse or two to protect everything just in case anything untoward should happen. Especially where water is concerned.


sender: user

message:
Storing and sequencing output value (Arduino)

I am new to Arduino programming, after days and nights trying to use array and for loop, and googling a lot of articles, I am still unable to find how to store each weighing output value from `int Sampling()` to be executed by the respective servo in sequence order.

If you have any clue to share and help me, I'll be very happy.

Below is my base code:

```c++
#include <HX711.h>
///////////////////////////////////////////////////////////////////////
#define calibration_factor -251
#define LOADCELL_DOUT_PIN 7   // data
#define LOADCELL_SCK_PIN 8    // sck
////////////////////////////////////////////////////////////////////////
HX711 scale;
////////////////////////////////////////////////////////////////////////
int servo1 = 12;
int servo2 = 13;
int proxiPin1 = 2;
int proxiPin2 = 3;
////////////////////////////////////////////////////////////////////////
int toggleState = 0;
int proxiState1 = 1;
int proxiState2 = 1;
////////////////////////////////////////////////////////////////////////
int weight;
int weightFinal;
////////////////////////////////////////////////////////////////////////
void setup()
{
  Serial.begin(9600);
  scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
  scale.set_scale(calibration_factor);
  scale.tare();

  pinMode(servo1, OUTPUT); // simulating servo1
  pinMode(servo2, OUTPUT); // simulating servo2
  pinMode(proxiPin1, INPUT_PULLUP); // proximity
  pinMode(proxiPin2, INPUT_PULLUP); // proximity

}
/////////////////////////////////////////////////////////////////////////
void loop()
{
  Serial.print(Sampling());
  Serial.print(" gram");
  Serial.println();
  ///////////////////////////////////////////////////////////////////////
  if ( weightFinal == 10 )
  {
    toggleState = true;
    servo10gr();
  }

  if ( weightFinal == 20 )
  {
    toggleState = true;
    servo20gr();
  }
}
////////////////////////////////////////////////////////////////////////
int Sampling()
{
  int weight = scale.get_units();

  if (weight >= 10  && weight< 20)
  {
    weightFinal = 10;
  }

  else if (weight >= 20  && weight < 30)
  {
    weightFinal = 20;
  }

  return weight;
}
/////////////////////////////////////////////////////////////////////////
int servo10gr()
{
  proxiState1 = digitalRead(proxiPin1);
  if ( proxiState1 == 0 && toggleState == true )
  {
    digitalWrite(servo1, HIGH);  //Simulating servo signal Pin//
    delay(500);
    digitalWrite(servo1, LOW);

    toggleState = false;
    weightFinal=0;
  }
}
/////////////////////////////////////////////////////////////////////////
int servo20gr()
{
  proxiState2 = digitalRead(proxiPin2);
  if ( proxiState2 == 0 && toggleState == true )
  {
    digitalWrite(servo2, HIGH);    //Simulating servo signal Pin//
    delay(500);
    digitalWrite(servo2, LOW);

    toggleState = false;
    weightFinal=0;
  }
}
```

sender: assistant

body:
I'm still not entirely sure what you want to achieve, but maybe this will help:

You have a global variable `int weight`, and in `int Sampling()` you create another `int weight = scale.get_units()` which you give a value.

That second variable is only accessible inside of `Sampling()`. If you want to use it elsewhere for storing or in other functions, change:

`int weight = scale.get_units();`

to

`weight = scale.get_units();`

and you can then use `weight` wherever you like in your code, also in `servo10gr()` and `servo20gr()`.

You don't need to store a sequence of `weight`s to drive the servos; you can just use the current weight immediately to drive a servo and then get a new `weight`.

If, however, you want or need to keep a list of `weights` for some reason, there's a bit more work to be done.

There are better ways of going about this, but let's see first if this solves your problem.


message:
Trouble with ESP8266 on Eero network

I have an ESP8266 Node MCU and am learning to use its wifi capabilities. In my home I have a router provided by my ISP that runs a network we'll call 'network1'. I also have an Eero mesh network that runs in the house, called 'network2'.

When I upload the following minimal example and use network1,
1) my 8266 device connects to network1 (the messages in the serial monitor confirm this) and
2) I can use my phone and laptop to connect to the 8266 - i.e., I can put the IP into my browser and see a webpage telling me 'Hello World'.

However, I have trouble with network2, the Eero network.
1) I *can* connect my 8266 device to network2 (the messages in the serial monitor confirm this)
but
2) I can't connect to the 8266 device with my phone/laptop. (Yes, I switch these over to network2 first.) I put the new IP into my browser and I am told the page is taking too long to respond.

I haven't done anything special with my network1 router; things just worked. With network2, I've tried various settings with my Eero - given the 8266 a static IP address, enabled port forwarding (on port 80) and established a firewall rule for it, but nothing works.

I can run many different programs through network1, and nothing works on the Eero network. Any suggestions on getting things to work?

My minimal working example:

    #include <ESP8266WiFi.h>

    const char* ssid = "network1"; // or 'network2'
    const char* password = "thepassword"; // real password used in code

    WiFiServer server(80); //just pick any port number you like

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

      // Connect to WiFi network
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

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

      Serial.println("");
      Serial.println("WiFi connected");

      // Start the server
      server.begin();
      Serial.println("Server started");

      // Print the IP address
      Serial.println(WiFi.localIP());
      //gateway = WiFi.gatewayIP();
      Serial.print("GATEWAY: ");
      Serial.println(WiFi.gatewayIP());

      // print your subnet mask:
      //subnet = WiFi.subnetMask();
      Serial.print("NETMASK: ");
      Serial.println(WiFi.subnetMask());
    }

    void loop() {
      // Check if a client has connected
      WiFiClient client = server.available();
      if (!client) {
        return;
      }

      // Prepare the response
      String s = "HTTP/1.1 200 OK\r\n";
      s += "Content-Type: text/html\r\n\r\n";
      s += "<!DOCTYPE HTML>\r\n\r\n";
      s += "\r\n";
      s+= "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\r\n";
      s+= "<title>ESP Web Server</title>\r\n";
      s+= "\r\n";
      s += "Hello World";
      s += "\n";

      client.flush();

      // Send the response to the client
      client.print(s);
      delay(1);
    }

body:
I was able to find an answer though I'm not sure _why_ it works. It comes down to adding `WiFi.mode(WIFI_STA);` in the setup, as in

    void setup() {

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);
      ...
      }

I was able to replicate success with another file on my ESP8266 device and Eero network as well.


message:
Interfacing unusual 4 digits 7 segments display

There is a common anode and common cathode of 7 segments display. But I got an unusual one.

There are 7 pins controlling 4 digits 7 segments.
[![enter image description here][1]][1]

I find the pinout by a multimeter. Basically, each pin can be anode or cathode.
[![enter image description here][2]][2]

My questions:

 1. What is the exact name of this 7 segments display?
 2. How to drive this display by Arduino, any website/sample code?
 3. If I am using the 5V tolerant board, which resistor I need to use? And how is the schematic?

  [1]: https://i.stack.imgur.com/TrzuE.jpg
  [2]: https://i.stack.imgur.com/wVI1i.png

body:
1. I don't know. If I had to talk about it, I would say a LED segment display with a matrix layout with a complementary drive.

2. If a pin is used as a cathode, a LOW signal must be applied. If it is used as an anode, a HIGH signal must be applied.

You could define constants for each segments anode and cathode that define a pin number. e.g :

    #define CAT_1A = 2
    #define AN_1A  = 1

and so on. Then if you whant to show segment 1A set CAT_1A to LOW and AN_1A to HIGH.

Of course the whole process is more complicated. You have to define which segments must be light up to show a specific digit. You must show all four digits one by one in a fast loop and so on. But that's the same as you would do for an ordinary LED segment bar. The difference is that you have to configure pin pairs and not single pins.

3. Use your Multimeter to measure the Forward voltage of the segments. If they are red, it should be around 1.8 to 2.4 Volts. Substract this Voltage from 5 Volts. Then devide by 0.02 (20 mA) and you get the Resistor in Ohms. A standard LED is bright enough with about 20 mA.

Example:

    (5V - 1.8V) / 0.02A) = 160 Ohm

Use a resistor of say 100 Ohms at each pin. It is common available and as the current flows always through 2 pins, you have 200 Ohms together.

It is also possible that the LED bar has internal resistors. Try to meassure the resistance beetween to pins.

**Edit**
When I said, "each digit must be shown in a fast loop", I forgot to clearify that, for each digit, the segments must be switched sequentially.

You can do it even more complicated and show all Segments with a common cathode or a common annode at once.   Then you need fewer cycles, but as you use resistors for all pins (see point 3.) this could dim the LEDs remarkably. Also, becaus technically, the forward voltage of different LED may differ, so the some could be brighter the others.

There is also another thing, I did not think of, when I wrote the answer. If you power a segment, say from pin A (+5V) to pin B (GND), you have a resistor (100 Ohms), an LED (minus 1.8 Volts) and a second resitor (100 Ohms) in series. So in an ideal situation the voltage on pin B (also on the second resitor) would by around 1.6 Volts. Pin B is the cathode of the LED segment, but can also be the anode of another segment (S2).  If the cathode of S2 is connected to GND there is a very small chance, that the segment lights up. If you don't see (ghost) lights, all is fine. But if some segments light up (but much darker than the right ones) you have to find a better solution.


body:
This display seems to have 32 addressable LEDs controlled by only
7 pins. Judging from this fact, and from the provided pinout table, it
looks like a [Charlieplexed matrix][charlie].

A typical way to drive this kind of matrix is by looping over the
cathodes. You pull one cathode pin `LOW`, and then pull `HIGH` all the
anodes of the LEDs you want to shine which are connected to this
particular cathode. Wait a few milliseconds, then move to the next
cathode. It is important that all pins that are not involved in lighting
an LED remain in `INPUT` mode.

For example, let's say you want to light all the segments of the first
digit (display an “8”) while keeping everything else off. You first pull
pin 1 `LOW` (first cathode) and pull `HIGH` pins 2–5 (segments F, G, C
and D). Let that shine for a few milliseconds, then put everything to
high impedance (pins to `INPUT`) and move to the next cathode: pin 2
goes `LOW` and pin 1 (segment A) goes `HIGH`. And so on until you have
done all the cathodes.

For the coding part, I would suggest using a 7×7 matrix of booleans
telling whether a particular segment is meant to be lit. The indices of
the array would be row = cathode number and column = anode number. The
array would have the same structure as the pinout table you posted,
except for the fact that the lines and columns would have indices
ranging 0–6 instead of 1–7. This should make it easy to handle
refreshing the display.

Drawing the digits is a bit trickier than with traditional 7-segment
displays, as for each segment you will have to find its coordinates in
the matrix (cathode number and anode number). For this, I would use a
“mapping matrix” that stores the mapping (digit number, segment number)
→ (cathode number, anode number).

Below is a tentative, and untested, implementation of these strategies.
Note that I did not write a function to output a digit, but that should
be easy to implement on top of the `set_segment()` function defined
here. Besides, the question of how to draw a digit once you know how to
control individual segments is the standard 7-segment problem, for which
you should be able to find many tutorials.

Note that this code assumes you drive the display directly, using no
iterface other than current-limiting resistors. This carries the risk of
either overloading the cathode outputs or having the display be too dim,
depending on the current-limiting resistors. You may want to use
transistors for the cathodes, in which case you would have a set of
cathode pins different from the set of anode pins.

```c++
// Arduino pins connected to the display.
const uint8_t display_pins[7] = {2, 3, 4, 5, 6, 7, 8};

// Which segments are lit. Each segment is located in this matrix at
// the coordinates [cathode][anode].
bool segment_lit[7][7];

// Coordinates in the matrix above where a segment can be found.
struct SegmentCoordinates {
    uint8_t cathode;
    uint8_t anode;
};

// segments[digit][segment] gives the coordinates of
// any segment (0 = A) of any digit (0 = 1st digit).
const SegmentCoordinates segments[4][7] = {
// seg: A      B        C       D      E        F       G
    {{1, 0}, {2, 0}, {0, 3}, {0, 4}, {3, 0}, {0, 1}, {0, 2}},
    {{2, 1}, {3, 1}, {1, 4}, {5, 1}, {4, 1}, {1, 2}, {1, 3}},
    {{3, 4}, {4, 2}, {4, 3}, {0, 5}, {2, 5}, {2, 3}, {2, 4}},
    {{5, 6}, {6, 5}, {5, 4}, {3, 5}, {5, 3}, {4, 5}, {6, 4}}
};

// Turn a segment OFF (lit = false) or ON (lit = true).
void set_segment(uint8_t digit, uint8_t segment, bool lit) {
    SegmentCoordinates coordinates = segments[digit][segment];
    segment_lit[coordinates.cathode][coordinates.anode] = lit;
}

void setup(){}

void loop() {
    static uint8_t cathode;  // currently used cathode

    // Set the current cathode to OUTPUT LOW.
    digitalWrite(display_pins[cathode], LOW);
    pinMode(display_pins[cathode], OUTPUT);

    // Set the relevant anodes to OUTPUT HIGH.
    for (int anode = 0; anode < 7; anode++) {
        if (segment_lit[cathode][anode]) {
            digitalWrite(display_pins[anode], HIGH);
            pinMode(display_pins[anode], OUTPUT);
        }
    }

    // Let that shine for a while.
    delay(10);

    // Turn off everything.
    for (int pin = 0; pin < 7; pin++) {
        pinMode(display_pins[pin], INPUT);
    }

    // Move to the next cathode.
    if (++cathode >= 7) cathode = 0;
}
```

I used `delay()` here for simplicity. In production code you would
handdle the timings with `millis()` in a non-blocking fashion, in the
spirit of the “Blink without delay” tutorial.

[charlie]: https://en.wikipedia.org/wiki/Charlieplexing


message:
Arduino boards are not working with powerbanks!

I have used many Arduino boards with adapters and other power supplies. While connecting with a powerbank for portable projects I have noticed that the power goes off after a couple of seconds and then turn on again after sometimes. Why this is happening with power bank?
I have used following powerbanks:
1. Basus
2. Xiaomi

body:
Most USB powerbanks will automatically turn off if there is not a minimum current draw to keep them turned on.  The Arduino is obviously drawing current below the limit for the devices you have.

A couple of options:

 1. Add some additional load to keep the powerbank on indefinitely.  Of course this may waste power but that's part of the price to pay.
 2. Find a power bank that is less sophisticated.  I have one with a manual on/off switch.  It powers the Arduino just fine until it runs out of power.
 3. Find a different powerbank that has a lower threshold for staying on.  Some vendors give you this spec and others don't.
 4. Modify the powerbank to stay on.  I'm not sure there is a general way to do this but you might experiment with it and see.


message:
Record data to SD card with ATtiny85

An application of ATtiny with SD card is complicated due to missing of hardware SPI in attiny.
The "ATmega" code for creating of a "SD file" is:

    #include <SPI.h>
    #include <SD.h>

    File file;
    int const pinCS = 2;

    void setup()

    {
    SD.begin(pinCS);
    file = SD.open("Test.txt", FILE_WRITE);
    file.println("anything");
    file.close();}

    void loop()
    {}

This code creates on SD card a file "Test.txt" and to this file records text "anathing".
Is it possible to rewrite this code for "ATtiny85"?

body:
The ATtiny85 has no dedicated SPI port. It has, however, an “USI” port
(Universal Serial Interface) that should be able to do the job. The lack
of SPI should not be a problem, but the lack of memory _will_ be a
problem.

Files on an SD card are written one sector (512 bytes) at a time.
For this reason, the SD library uses a 512 bytes buffer in RAM.
That cannot work on an ATtiny85, as the buffer would consume the whole
RAM.

You may be able to do something using the [Petit FAT library][petit],
provided you can work around the severe limitations of its write
interface:

> The write function has some restrictions listed below:
>
> * Cannot create file. Only existing file can be written.
> * Cannot expand file size.
> * Cannot update time stamp of the file.
> * Write operation can start/stop on the sector boundary only.
> * Read-only attribute of the file cannot block write operation.

The first two points imply that you would have to create the file and
allocate the sectors for it in your computer.

This [blog post][] mentions a port of the library to the Arduino
environment, and its use on an ATtiny84, which has similar capabilities
to the ATtiny85 (only with more pins).

[petit]: http://elm-chan.org/fsw/ff/00index_p.html
[blog post]: https://harizanov.com/2012/05/toying-with-attiny84-and-sd-card-in-arduino-ide/


message:
Send commands from cPanel website to client ESP8266

I have a project where I want to remotely turn on and off a relay using an Arduino,(ESP8266) over the internet.

 1.  I have a remote web server that hosts my existing hobby website, cPanel hosted by GoDaddy Sites.
 2.  An Arduino (ESP8266) connects to this website listening for relay on/off commands.
 3.  Open a browser and load the webpage dashboard to sent commands to Arduino.

 Yes I could have the Arduino poll the website ever so often to check for a value changed in a database, but I don't want to do that, Just seems unethical to me.

I was looking at WebSockets and thought that might be what I'm looking for but I know too little about it or there's not enough relevant documentation online about it to use it in this type of project.

I am looking forward to your comments and answers, but please do not tell me to host the site on the Arduino, and also using an app or other service is not going to work either, We are working with my own webpage and thats it no thirdparty apps, Thanks.

body:
I don't believe you will have the capability to implement a Websocket interface on the GoDaddy cPanel web site.  I think you are limited to just serving up HTML content and associated files.  Websocket requires a server-side resource to talk to which you cannot implement.

I see nothing wrong with having a simple HTML page, that doesn't even need to really contain HTML that your ESP8266 can "GET" and examine and determine to turn your relay on or off.


message:
Multitasking with Arduino?

I am making a Christmas Tree with Arduino. I found a 12 led chaser code on internet so I made 12 rows of leds and hook them up to my Arduino pro mini.
They are working just fine.

However, I also want to add music with piezo buzzer while running the LEDs. Is that possible somehow or should I use another microcontroller for piezo? I also used pin 10 for piezo buzzer and used pin 14(a0) for led assigned for pin 10 previously..

Here are the codes:
12 led chaser

```c++
#define t   30
#define t1  20
#define t2  100
#define t3  50

void setup() {
  // set up pins 2 to 13 as outputs
  for (int i = 2; i <= 13; i++) {
    pinMode(i, OUTPUT);
  }
}
/////////////////////////////////////////////////////////////////////////////////Effect 1
void loop(){

effect_1();
effect_1();

 effect_2();
 effect_2();

 effect_3();
 effect_3();

 effect_4();
 effect_4();

 effect_5();
 effect_5();

 effect_6();
 effect_6();

 effect_7();
 effect_7();
  }
//left to right and right to left
void effect_1()
{
for(int i=2; i<14; i++){
digitalWrite(i, HIGH);
delay(t1);
digitalWrite(i+1, HIGH);
delay(t1);
digitalWrite(i+2, HIGH);
delay(t1);
digitalWrite(i, LOW);
delay(t1);
digitalWrite(i+1, LOW);
delay(t1);
}
for(int i=13; i>1; i--){
digitalWrite(i, HIGH);
delay(t1);
digitalWrite(i-1, HIGH);
delay(t1);
digitalWrite(i-2, HIGH);
delay(t1);
digitalWrite(i, LOW);
delay(t1);
digitalWrite(i-1, LOW);
delay(t1);
}
}
/////////////////////////////////////////////////////////////////////////////////Effect 2
void effect_2()
{
int count = 13; // keeps track of second LED movement

  // move first LED from left to right and second from right to left
  for (int i = 2; i < 13; i++) {
    clear();
    digitalWrite(i, HIGH);      // chaser 1
    digitalWrite(count, HIGH); // chaser 2
    count--;
    // stop LEDs from appearing to stand still in the middle
    if (count != 7) {
      delay(t2);
    }
  }

  // move first LED from right to left and second LED from left to right
  for (int i = 13; i > 2; i--) {
    clear();
    digitalWrite(i, HIGH);      // chaser 1
    digitalWrite(count, HIGH); // chaser 2
    count++;
    // stop LEDs from appearing to stand still in the middle
    if (count != 8) {
      delay(t2);
    }
  }
}

////////////////////////////////////////////////////////////////////////////////Effect 3

void effect_3()
{
for(int i=2; i<14; i++){
  digitalWrite(i, HIGH);
  delay(t3);
}
for(int i=2; i<14; i++){
  digitalWrite(i, LOW);
  delay(t3);
}

for(int i = 14; i>=2; i--){
  digitalWrite(i, HIGH);
  delay(t3);
}
for(int i = 14; i>=2; i--){
  digitalWrite(i, LOW);
  delay(t3);
}
}
  ///////////////////////////////////////////////////////////////////////////Effect 4
void effect_4()
{
for(int j = 2; j <= 13; j++){
  digitalWrite(j, HIGH);
  delay(t2);
  j=j+1;
  }
for(int j = 2; j <= 13; j++){
  digitalWrite(j, LOW);
  delay(t2);
  }

  for(int k = 15; k > 2; k--){
  digitalWrite(k, HIGH);
  delay(t2);
  k=k-1;
  }
for(int k = 15; k > 2; k--){
  digitalWrite(k, LOW);
  delay(t2);
  }
}
//////////////////////////////////////////////////////////////////////////////Effect 5
  void effect_5()
{
 for(int pin = 13; pin >= 2; pin--)
  {
  digitalWrite(pin, HIGH);
  delay(t1);
  digitalWrite(pin+1, LOW);
  delay(t1);
  }
  for(int pin = 13; pin >= 2; pin--)
  {
  digitalWrite(pin+1, HIGH);
  delay(t1);
  digitalWrite(pin+2, LOW);
  delay(t1);
  }
  for(int pin = 13; pin >= 2; pin--)
  {
  digitalWrite(pin+2, HIGH);
  delay(t1);
  digitalWrite(pin+3, LOW);
  delay(t1);
  }
  for(int pin = 13; pin >= 2; pin--)
  {
  digitalWrite(pin+3, HIGH);
  delay(t1);
  digitalWrite(pin+4, LOW);
  delay(t1);
  }
    for(int pin = 13; pin >= 2; pin--)
  {
  digitalWrite(pin+4, HIGH);
  delay(t1);
  digitalWrite(pin+5, LOW);
  delay(t1);
  }
  for(int pin = 13; pin >= 2; pin--)
  {
  digitalWrite(pin+5, HIGH);
  delay(t1);
  digitalWrite(pin+6, LOW);
  delay(t1);
  }
  for(int pin = 13; pin >= 2; pin--)
  {
  digitalWrite(pin+6, HIGH);
  delay(t1);
  digitalWrite(pin+7, LOW);
  delay(t1);
  }
   for(int pin = 13; pin >= 2; pin--)
  {
  digitalWrite(pin+7, HIGH);
  delay(t1);
  digitalWrite(pin+8, LOW);
  delay(t1);
  }
  for(int pin = 9; pin >= 2; pin--)
  {
  digitalWrite(pin+8, HIGH);
  delay(t1);
  digitalWrite(pin+9, LOW);
  delay(t1);
  }
    for(int pin = 9; pin >= 2; pin--)
  {
  digitalWrite(pin+9, HIGH);
  delay(t1);
  digitalWrite(pin+10, LOW);
  delay(t1);
  }
  for(int pin = 9; pin >= 2; pin--)
  {
  digitalWrite(pin+10, HIGH);
  delay(t1);
  digitalWrite(pin+11, LOW);
  delay(t1);
  }
  for(int pin = 14; pin >= 2; pin--)
  {
  digitalWrite(pin+11, HIGH);
  delay(t1);
  }
  for(int pin = 13; pin >= 2; pin--)
  {
    digitalWrite(pin, LOW);
  delay(t1);
    }
  }
  /////////////////////////////////////////////////////////////////////////////Effect 6
void effect_6()
{
for(int j=2; j<14; j++){
  digitalWrite(j, LOW);
  delay(t);
  digitalWrite(j, HIGH);
  delay(t);
  digitalWrite(j-2, LOW);
  delay(t);
  digitalWrite(j, HIGH);
}
for(int k = 15; k>2; k--){
  digitalWrite(k, LOW);
  delay(t);
  digitalWrite(k, HIGH);
  delay(t);
  digitalWrite(k+2, LOW);
  delay(t);
  digitalWrite(k, HIGH);
}
for(int k = 2; k<14; k++){
  digitalWrite(k, LOW);
  delay(t);
  digitalWrite(k, HIGH);
  delay(t);
  digitalWrite(k-2, LOW);
  delay(t);
  digitalWrite(k, HIGH);
}
for(int k = 15; k>2; k--){
  digitalWrite(k, LOW);
  delay(t);
  digitalWrite(k, HIGH);
  delay(t);
  digitalWrite(k+4, LOW);
  delay(t);
  digitalWrite(k, HIGH);
}
for(int k = 2; k<14; k++){
  digitalWrite(k, LOW);
  delay(t);
  digitalWrite(k, HIGH);
  delay(t);
  digitalWrite(k-4, LOW);
  delay(t);
  digitalWrite(k, HIGH);
}
}
///////////////////////////////////////////////////////////////////////////////////Effect 7
void effect_7()
{
for(int j=2; j<14; j++){
  digitalWrite(j, HIGH);
  delay(t);
  digitalWrite(j+2, LOW);
  delay(t);
}
for(int k = 15; k>2; k--){
  digitalWrite(k, HIGH);
  delay(t);
  digitalWrite(k+2, LOW);
  delay(t);
}
}

// function to switch all LEDs off
void clear(void)
{
  for (int i = 2; i <= 13; i++) {
    digitalWrite(i, LOW);
  }
}
```

Melody tone for buzzer:
```c++
/*
  We Wish You a Merry Christmas - Traditional Christmas song
  Connect a piezo buzzer or speaker to pin 11 or select a new pin.
  More songs available at https://github.com/robsoncouto/arduino-songs

                                              Robson Couto, 2019
*/
#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978
#define REST      0

// change this to make the song slower or faster
int tempo = 140;

// change this to whichever pin you want to use
int buzzer = 11;

// notes of the moledy followed by the duration.
// a 4 means a quarter note, 8 an eighteenth , 16 sixteenth, so on
// !!negative numbers are used to represent dotted notes,
// so -4 means a dotted quarter note, that is, a quarter plus an eighteenth!!
int melody[] = {

  // We Wish You a Merry Christmas
  // Score available at https://musescore.com/user/6208766/scores/1497501

  NOTE_C5,4, //1
  NOTE_F5,4, NOTE_F5,8, NOTE_G5,8, NOTE_F5,8, NOTE_E5,8,
  NOTE_D5,4, NOTE_D5,4, NOTE_D5,4,
  NOTE_G5,4, NOTE_G5,8, NOTE_A5,8, NOTE_G5,8, NOTE_F5,8,
  NOTE_E5,4, NOTE_C5,4, NOTE_C5,4,
  NOTE_A5,4, NOTE_A5,8, NOTE_AS5,8, NOTE_A5,8, NOTE_G5,8,
  NOTE_F5,4, NOTE_D5,4, NOTE_C5,8, NOTE_C5,8,
  NOTE_D5,4, NOTE_G5,4, NOTE_E5,4,

  NOTE_F5,2, NOTE_C5,4, //8
  NOTE_F5,4, NOTE_F5,8, NOTE_G5,8, NOTE_F5,8, NOTE_E5,8,
  NOTE_D5,4, NOTE_D5,4, NOTE_D5,4,
  NOTE_G5,4, NOTE_G5,8, NOTE_A5,8, NOTE_G5,8, NOTE_F5,8,
  NOTE_E5,4, NOTE_C5,4, NOTE_C5,4,
  NOTE_A5,4, NOTE_A5,8, NOTE_AS5,8, NOTE_A5,8, NOTE_G5,8,
  NOTE_F5,4, NOTE_D5,4, NOTE_C5,8, NOTE_C5,8,
  NOTE_D5,4, NOTE_G5,4, NOTE_E5,4,
  NOTE_F5,2, NOTE_C5,4,

  NOTE_F5,4, NOTE_F5,4, NOTE_F5,4,//17
  NOTE_E5,2, NOTE_E5,4,
  NOTE_F5,4, NOTE_E5,4, NOTE_D5,4,
  NOTE_C5,2, NOTE_A5,4,
  NOTE_AS5,4, NOTE_A5,4, NOTE_G5,4,
  NOTE_C6,4, NOTE_C5,4, NOTE_C5,8, NOTE_C5,8,
  NOTE_D5,4, NOTE_G5,4, NOTE_E5,4,
  NOTE_F5,2, NOTE_C5,4,
  NOTE_F5,4, NOTE_F5,8, NOTE_G5,8, NOTE_F5,8, NOTE_E5,8,
  NOTE_D5,4, NOTE_D5,4, NOTE_D5,4,

  NOTE_G5,4, NOTE_G5,8, NOTE_A5,8, NOTE_G5,8, NOTE_F5,8, //27
  NOTE_E5,4, NOTE_C5,4, NOTE_C5,4,
  NOTE_A5,4, NOTE_A5,8, NOTE_AS5,8, NOTE_A5,8, NOTE_G5,8,
  NOTE_F5,4, NOTE_D5,4, NOTE_C5,8, NOTE_C5,8,
  NOTE_D5,4, NOTE_G5,4, NOTE_E5,4,
  NOTE_F5,2, NOTE_C5,4,
  NOTE_F5,4, NOTE_F5,4, NOTE_F5,4,
  NOTE_E5,2, NOTE_E5,4,
  NOTE_F5,4, NOTE_E5,4, NOTE_D5,4,

  NOTE_C5,2, NOTE_A5,4,//36
  NOTE_AS5,4, NOTE_A5,4, NOTE_G5,4,
  NOTE_C6,4, NOTE_C5,4, NOTE_C5,8, NOTE_C5,8,
  NOTE_D5,4, NOTE_G5,4, NOTE_E5,4,
  NOTE_F5,2, NOTE_C5,4,
  NOTE_F5,4, NOTE_F5,8, NOTE_G5,8, NOTE_F5,8, NOTE_E5,8,
  NOTE_D5,4, NOTE_D5,4, NOTE_D5,4,
  NOTE_G5,4, NOTE_G5,8, NOTE_A5,8, NOTE_G5,8, NOTE_F5,8,
  NOTE_E5,4, NOTE_C5,4, NOTE_C5,4,

  NOTE_A5,4, NOTE_A5,8, NOTE_AS5,8, NOTE_A5,8, NOTE_G5,8,//45
  NOTE_F5,4, NOTE_D5,4, NOTE_C5,8, NOTE_C5,8,
  NOTE_D5,4, NOTE_G5,4, NOTE_E5,4,
  NOTE_F5,2, NOTE_C5,4,
  NOTE_F5,4, NOTE_F5,8, NOTE_G5,8, NOTE_F5,8, NOTE_E5,8,
  NOTE_D5,4, NOTE_D5,4, NOTE_D5,4,
  NOTE_G5,4, NOTE_G5,8, NOTE_A5,8, NOTE_G5,8, NOTE_F5,8,
  NOTE_E5,4, NOTE_C5,4, NOTE_C5,4,

  NOTE_A5,4, NOTE_A5,8, NOTE_AS5,8, NOTE_A5,8, NOTE_G5,8, //53
  NOTE_F5,4, NOTE_D5,4, NOTE_C5,8, NOTE_C5,8,
  NOTE_D5,4, NOTE_G5,4, NOTE_E5,4,
  NOTE_F5,2, REST,4
};

// sizeof gives the number of bytes, each int value is composed of two bytes (16 bits)
// there are two values per note (pitch and duration), so for each note there are four bytes
int notes = sizeof(melody) / sizeof(melody[0]) / 2;

// this calculates the duration of a whole note in ms
int wholenote = (60000 * 4) / tempo;

int divider = 0, noteDuration = 0;

void setup() {
  // iterate over the notes of the melody.
  // Remember, the array is twice the number of notes (notes + durations)
  for (int thisNote = 0; thisNote < notes * 2; thisNote = thisNote + 2) {

    // calculates the duration of each note
    divider = melody[thisNote + 1];
    if (divider > 0) {
      // regular note, just proceed
      noteDuration = (wholenote) / divider;
    } else if (divider < 0) {
      // dotted notes are represented with negative durations!!
      noteDuration = (wholenote) / abs(divider);
      noteDuration *= 1.5; // increases the duration in half for dotted notes
    }

    // we only play the note for 90% of the duration, leaving 10% as a pause
    tone(buzzer, melody[thisNote], noteDuration * 0.9);

    // Wait for the specief duration before playing the next note.
    delay(noteDuration);

    // stop the waveform generation before the next note.
    noTone(buzzer);
  }
}

void loop() {
  // no need to repeat the melody.
}
```

body:
I think the method suggested by chrisl is probably the best for you to use here.  If you want to make a more-conventional multitasking system, you would set a timer such as TIMER2 to the minimum time slice, then at the start of your code (after setup) you'd have something like this:

ISR(TIMER2_COMPA_vect)
{
  myIntHandler();
}

Here myIntHandler() does whatever needs to get done on each tick of TIMER2.  I use this general approach in my open-source DaqPort code to do simultaneous oscilloscope data acquisition and signal generation, while still handling serial commands in the background.
But that's probably overkill for your project. You can find out more about DaqPort at
<https://www.daqarta.com/dw_rraa.htm>


message:
Arduino Wifi Rev2, bug when reading PWM duty cycle value on pin 6

I am trying to read the PWM duty cycle set for pin 6 on the Arduino Wifi Rev2.

By default, the timer used is TCB0, used in 8-bit PWM mode. The 16-bit Compare channel CCMP is used as two 8-bit registers, the lowest byte CCMPL is for the period, while the highest byte CCMPH is for the duty cycle.

However, something weird happens when I try to read the Compare channel register, the value of CCMPH is unexpecteadly copied into CCMPL.

```

// PWM on pin 6, timer TCB0
//TCB_t* timer_B0 = (TCB_t *)&TCB0; // pointer on timer structure

void setup() {
  pinMode(6, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  setPWMValueOnPin6(20);
  setPWMValueOnPin6(40);
  setPWMValueOnPin6(60);
  setPWMValueOnPin6(80);
}

void printCompareChannelValues()
{
  Serial.print("Compare channel = ");
  unsigned int r = TCB0_CCMP;
  //byte r = timer_B0->CCMP;
  Serial.println(r);

  Serial.print("Compare channel L = ");
  byte l = TCB0_CCMPL;
  //byte l = timer_B0->CCMPL;
  Serial.println(l);

  Serial.print("Compare channel H = ");
  byte h = TCB0_CCMPH;
  //byte h = timer_B0->CCMPH;
  Serial.println(h);
}

void setPWMValueOnPin6(byte value)
{
  analogWrite(6, value);
  printCompareChannelValues();
  delay(2000);
}

```
Here is the serial monitor output:

```
Compare channel = 5375
Compare channel L = 255
Compare channel H = 20
Compare channel = 10260
Compare channel L = 20
Compare channel H = 40
Compare channel = 15400
Compare channel L = 40
Compare channel H = 60
Compare channel = 20540
Compare channel L = 60
Compare channel H = 80
Compare channel = 5200
Compare channel L = 80
Compare channel H = 20
Compare channel = 10260
Compare channel L = 20
Compare channel H = 40
Compare channel = 15400
Compare channel L = 40
Compare channel H = 60
Compare channel = 20540
Compare channel L = 60
Compare channel H = 80
Compare channel = 5200
Compare channel L = 80
Compare channel H = 20
```

Problem occurs even when removing the serial functions (by watching at a led intensity on pin 6).
The same behavior occurs on pin 3 (timer TCB1).

Does someone has any idea what is going on? Thanks for your help.

body:
Arguable bug location
---------------------

The problem appears to be [here in the `analogWrite()` code][1]:

```c
 timer_B->CCMPH = val;
```

I suppose it could be argued that you're using the timer in an way unintended
by the Arduino megaavr core, but I think it's *reasonable* to consider this as
a bug that should be fixed in the core.

16-bit hardware register access and analogWrite() internals
-------------------------------
According to the "Accessing 16-Bit Registers" of the [ATMega4809 datasheet][2] (among others no doubt):

> The AVR data bus has a width of eight bits, and so accessing 16-bit registers requires atomic operations. These
> registers must be byte accessed using two read or write operations. 16-bit registers are connected to the 8-bit bus
> and a temporary register using a 16-bit bus.
>
> **For a write operation, the low byte of the 16-bit register must be written before the high byte. The low byte is then
> written into the temporary register. When the high byte of the 16-bit register is written, the temporary register is
> copied into the low byte of the 16-bit register in the same clock cycle.**
>
> **For a read operation, the low byte of the 16-bit register must be read before the high byte. When the low byte register
> is read by the CPU, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as
> the low byte is read. The high byte will now be read from the temporary register.**
>
> This ensures that the low and high bytes of 16-bit registers are always accessed simultaneously when reading or
> writing the register.
> Interrupts can corrupt the timed sequence if an interrupt is triggered and accesses the same 16-bit register during an
> atomic 16-bit read/write operation. To prevent this, interrupts can be disabled when writing or reading 16-bit registers.
> The temporary registers can be read and written directly from user software.

So in effect, `timer_B->CCMPH = val;` is not just writing the real `CCMPH` hardware register, it is also writing the real `CCMPL` register with whatever is in this anonymous temporary register that was filled by either the last read or write operation.

So here's what's happening in your code:
----------------------------------------

* You execute `byte l = TCB0_CCMPL;` in `printCompareChannelValues()` which both reads TCB0_CCMPL **and loads the temporary register with the real CCMPH register's value**, which as you'll see is important.

* You execute `byte h = TCB0_CCMPH;` which is reading the temporary register rather than the real CCMPH hardware register from which the temporary register was loaded in your read from `TCB0_CCMPL` above.  Note: technically this statement doesn't play a role in problem.  I'm mentioning it only to drive home the behaviour of the temporary register.

* You exit `printCompareChannelValues()` and exit-and-reenter `setPWMValueOnPin6()` which calls `analogWrite()` which inside runs `timer_B->CCMPH = val;`,
  which **stores `val` in the real CCMPH with and stores the temporary register (containing the previous CCMPH value) into the real CCMPL**.

So yeah, on each time through the previous CCMPH becomes the new CCMPL value.

Patching the core
-----------------
Arguably what the core should contain, instead of  `timer_B->CCMPH = val;`, is something like:

```c++
{
 const uint8_t saved_SREG = SREG;
 cli();

 uint16_t temp  = timer_B->CCMP;
    temp          &= 0xFF;
 temp          |= (uint16_t)val << 8;
 timer_B->CCMP  = temp;

 SREG = saved_SREG;
}
```

Here we're doing full 16-bit register reads.  The load from CCMP reads the CCMPL first which primes the temporary register with the real CCMPH. Then the second half of the load from CCMP tries to read CCMPH, but is really  reading the temporary register *correctly* containing CCMPH's value.  And now there are no unpleasant surprises when this plays out in reverse.

The statement that assigns CCMP writes the CCMPL (really the temp register) then writes to the real CCMPH and simultaneously commits the temp register to the real CCMPL.

You can patch the above snipped over the `timer_B->CCMPH = val;` in your `PATH-TO-ARDUINO15-DIRECTORY/packages/arduino/hardware/megaavr/CORE-VERSION/cores/arduino/wiring_analog.c`

I have not spent a pile of time thinking about that patch, so use a bit of caution.  I may well have forgotten something important.

Priming the temporary register instead
--------------------------------------

If you don't want to mess with the core or you can't for some reason or another, a ugly hack would be to turn your simple `analogWrite(6, value);` call into something like the following:

```c++
{
  const uint8_t saved_SREG = SREG; cli();
  TCB0_CCMPL = TCB0_CCMPL;
  analogWrite(6, value);
  SREG = saved_SREG;
}
```

Besides turning off interrupt and then restoring them, the only thing happening here is this somewhat ridiculous looking statement:
`TCB0_CCMPL = TCB0_CCMPL;`

All this is doing is priming the temporary register for you.  On the right-hand side of the assignment we read the real CCMPL register.  This is also loading the temporary register with the real CCMPH, but we don't care about that.  Then on the left-hand side of the assignment, we attempt to write into CCMPL, but what we're in fact doing is writing to the temporary register.  And now your temporary register has the correct CCMPL value for when you run the `timer_B->CCMPH = val;` in the original `analogWrite()` code.

So, I suppose if you want to do this and you're unable/unwilling to modify your core, you could do this, potentially wrapping with an `#if #else` based on the Arduino megaavr core version, should they update the core in the future with patch given above or something equivalent.

Core patch using the same priming technique
-------------------------------------------

The same priming technique could be applied inside the patch as follows.  This is maybe more confusing but slightly more efficient than the comparatively normal looking first patch.

```c
{
 const uint8_t saved_SREG = SREG; cli();
 timer_B->CCMPL = timer_B->CCMPL; // Prime temporary register
 timer_B->CCMPH = val;
 SREG = saved_SREG;
}
```

  [1]: https://github.com/arduino/ArduinoCore-megaavr/blob/1.8.6/cores/arduino/wiring_analog.c#L173
  [2]: https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega4808-09-DataSheet-DS40002173B.pdf


message:
Any way to use DMA to transfer data to SD Card in ESP8266

I'm using ESP8266 at speed of 160 MHz to record ADC results into SD card, I need to do this at rate of 8 KHz. Means that i should save it on the SD Card or i'll run out of memory before 4 Sec passes.
I used timer1 to trigger sampling, but my problem is that surprisingly ESP8266 can not do this fast enough and the maximum sampling rate i get is about 7 KHz. I also tried to write data in ESP8266 Flash using littleFS in hope of acceleration but there was no luck. Here is my code:

    #include <SPI.h>
    #include <SD.h>

    File dataFile;

    int flag = 0;
    int count = 0, level = 0, se_count = 0;

    void inline analogReader() // Sampling and Recording processed which is done sequentially :(
    {
      uint16_t dataByte = (uint16_t) analogRead(A0);
      dataFile.write((uint8_t*) &adcBuf, 2);

    }

    void ICACHE_RAM_ATTR onTimerISR() { // Timer sets the flag every 0.125 MS
      flag = 1;
    }

    void setup() {
      pinMode(A0, INPUT);
      pinMode(D0, OUTPUT);

      Serial.begin(115200);

      if (!SD.begin(D0)) {
        Serial.println("Card failed, or not present");
        // don't do anything more:
        return;
      }
      Serial.println("card initialized.");

      File root = SD.open("/");

      if (SD.exists("real_test.bin"))
      {
        SD.remove("real_test.bin");
      }

      dataFile = SD.open("real_test.bin", FILE_WRITE);

      if (dataFile) {
        Serial.println("File created!");
      }
      else
      {
        Serial.println("Failed to create file!");
        return;
      }

      // Setting the timer so that timer interrupt fires every 0.125 MS
      timer1_attachInterrupt(onTimerISR);
      timer1_enable(TIM_DIV1/*from 80 Mhz*/, TIM_EDGE/*TIM_LEVEL*/, TIM_LOOP/*TIM_SINGLE*/);
      timer1_write(10000); /* ( 80 / 1 ) * 125 */
    }

    void loop() {
      if (flag) // To check whether its time to sampling or not, because of the low speed of the process
      {         // The flag is set again before one iteration ends.
        flag = 0;

        if (se_count < 10)
          analogReader();

        count++;
        if (count == 8000) // When 8000 sample & write process done notify using serial monitor. (it is
                              always more that 1 Sec. for example 1.3 Sec.)
        {
          count = 0;
          level = !level;
          Serial.println(level);

          se_count++;
          if (se_count == 10) // When we done 8000 * 10 sample & write we close the file. it supposed to
                              // be done in almost 10 sec. but it takes more time in practice. for
                              // example 13 Sec.
          {
            dataFile.close();
            Serial.println("Write ended");
          }
        }

      }
    }

I even used a faster method system_adc_read_fast(buf, num, clk_div) that is available in ESP-SDK, So i'm desperately seeking for one or two of approaches bellow if possible:

1. To use a non-blocking approach: If there is any possibility to hand SD writing to DMA so that i only fill the ADC buffer for DMA, or an interrupt for ADC complete so that i write to SD and when interrupt fired put the result in the buffer and return back to SD writing.
2. Yet faster approach for both ADC sampling and writing: Can i increase the SD write speed of SD library? for example by configuring SPI for maximum speed rate.

I also tried SDFat library but it does not recognize my SD Card. The whole process is odd to me that even by using a 160 MHz CPU and hardware i can not record ADC data at rate of 8000 Sample/S. I have TIME limitation so please help me.

Any suggestion is appreciated. Thanks in advance.

body:
So, sorry for late response, i figured it out. Because it took lots of time for me and it might be a prevalent issue, i think it worth to contribute my experience for further similar issues.

As mentioned buffering can do the job, here are some constraints that should be satisfied to have right buffering mechanism;

 - Writing to SD card SHOULD NOT be handled in the Timer ISR, but store ADC data into a buffer, aka int[] which is normally kept in SRAM (Your Timer ISR should be as short and fast as needed)

 - Handle reading from buffer to SD outside of Timer ISR in, for example in loop().

 - priority of ISR should be more than loop(), and it is so by default.

 - It's a good practice to divide your buffer into chunk of 512 or 1024. for example 2 chunks of 1024 Bytes making your buffer. you check for "filled" flag to be set in the loop() and when this happens call SDFile.write(..) for corresponding filled chunk and then reset the flag.

By conforming to these constraints you enjoy these benefits:

 - you can be sure that no ADC on time sampling missed because of sluggish SD write process.

 - by buffering and pilling data and then storing, you have chance to avoid byte wise write to SD, which is  really inefficient. and instead handle write in chunks of 512 or 1024 bytes. which is equal to sector size of SDs. so you have faster SD write process too.

This way you can easily handle voice recording up to 16 ksps even without using DMA.

I have added the code to my github, in this repository; https://github.com/A-R-S-D/WAVRecorder


message:
controlling 2 sensor and 3 pump using millis

i make a 3 pump for output and im using millis for it, i want to stop if rach the intervalm now in my code its still looping not realy stop for it thx

    int pump1 = 5;//pin D5
    int pump2 = 6;//pin D6
    int pump3 = 7;//pin D7
    float pompa1;
    float pompa2;
    float pompa3;
    unsigned long prev_pump1    = 0;
    unsigned long prev_pump2    = 0;
    unsigned long prev_pump3    = 0;
    unsigned long initiate_start = 0;
    int pump_state1 = false;
    int pump_state2 = false;
    int pump_state3 = false;

and after this this is my loop program

      //-----------PUMP ALGORITHM--------------------
      long int pompa01 = pompa1*1000;//interval pump1
      long int pompa02 = pompa2*1000;//interval pump2
      long int pompa03 = pompa3*1000;//interval pump2

      unsigned long initiate_start = millis();

      //pompa1
      if(intiate_start-prev_pump1 > pompa01)
      {
        pump_state1 = !pump_state1;

        if(pump_state1)
        {
          digitalWrite(pump1, HIGH);
        }
        else
        {
          digitalWrite(pump1, LOW);
        }
        prev_pump1 = initiate_start;
      }

        //pompa2
      if(intiate_start-prev_pump2 > pompa02)
      {
        pump_state2 = !pump_state2;

        if(pump_state2)
        {
          digitalWrite(pump2, HIGH);
        }
        else
        {
          digitalWrite(pump2, LOW);
        }
        prev_pump2 = initiate_start;
      }

        //pompa3
      if(intiate_start-prev_pump3 > pompa03)
      {
        pump_state3 = !pump_state3;

        if(pump_state3)
        {
          digitalWrite(pump3, HIGH);
        }
        else
        {
          digitalWrite(pump3, LOW);
        }
        prev_pump3 = initiate_start;
      }

body:
Note: this is not an answer (my previous version of the answer contained a problem, thanks Edgar Bonet for notifying and a fix for the remainder of the answer). However, I don't want to remove this answer as it may help in removing a lot of duplication. I took the liberty to convert it into a class.

It compiles, but I can't check the functionality but hopefully it helps you to continue. If there are problems, use write commands to send text to the serial to check the times and state.

Sketch:

    #include  "Pump.h"

    const int NR_OF_PUMPS = 3;

    Pump pumps[NR_OF_PUMPS] =
    {
      Pump(5, 1.0),
      Pump(6, 2.5),
      Pump(7, 3.2)
    };

    void setup()
    {
    }

    void loop()
    {
      process();
    }

    void process()
    {
      for (int pumpIndex = 0; pumpIndex < NR_OF_PUMPS; pumpIndex++)
      {
        pumps[pumpIndex].Process(millis());
      }
    }

Pump.h:

    class Pump
    {
    public:
      Pump::Pump(int pin, float interval);
      void Process(uint32_t currentTime);

    private:
      int _pin;
      float _interval;
      uint32_t _prevTime;
      bool _state;
    };

Pump.cpp:

    #include "Arduino.h"
    #include "Pump.h"

    Pump::Pump(int pin, float interval)
    :
      _pin(pin),
      _interval(interval * 1000.0),
      _prevTime(0),
      _state(false)
    {
    }

    void Pump::Process(uint32_t currentTime)
    {
      if (currentTime - _prevTime > _interval)
      {
        _state = !_state;
        digitalWrite(_pin, _state ? HIGH : LOW);
        _prevTime = currentTime;
      }
    }


body:
This is meant as a complement to Michel Keijzers' answer. I fully agree
with his assessment: code duplication is something to be avoided, as it
greatly hurts maintainability. And I sympathise with him feeling the
urge to implement this as a proper class. ;-)

I would argue, however, that between the simplistic version of the OP's
code, and the fully object-oriented one of that answer, there is an
intermediate step that is worth targeting as the next thing to learn. I
mean: arrays and loops.

Many cases of code duplication follow a pattern roughly like this:

```c++
// At the top of the sketch:
some_type data0 = some_value;
some_type data1 = some_other_value;
// etc.

// Within a function:
do_lots_of_stuff(data0);
do_lots_of_stuff(data1);
// etc.
```

where `do_lots_of_stuff()` may be a lot of code, rather than a single
function call (and it would indeed not be that bad if it was just a
function call).

The simple solution to this kind of code duplication is to put the
variables in an array, and process them by looping through the array:

```c++
// At the top of the sketch:
const int data_count = ...;
some_type[data_count] = {some_value, some_other_value, ...};

// Within a function:
for (int i = 0; i < data_count; i++)
    do_lots_of_stuff(data[i]);
```

Here is my attempt at applying this technique to the OP's code. Note
that, since there are multiple variables for each pump, we need multiple
arrays:

```c++
const int pump_count = 3;
const uint8_t pump_pins[pump_count] = {5, 6, 7};
const uint32_t pump_half_periods[pump_count] = {1000, 2500, 3200};

uint8_t pump_states[pump_count];  // LOW or HIGH
uint32_t pump_last_actuations[pump_count];  // time in ms

void setup() {
    for (int i = 0; i < pump_count; i++) {
        pinMode(pump_pins[i], OUTPUT);
    }
}

void loop() {
    unsigned long now = millis();
    for (int i = 0; i < pump_count; i++) {
        if (now - pump_last_actuations[i] >= pump_half_periods[i]) {
            pump_states[i] = (pump_states[i] == HIGH) ? LOW : HIGH;
            digitalWrite(pump_pins[i], pump_states[i]);
            pump_last_actuations[i] = now;
        }
    }
}
```

This removes all the duplication, and should be easier to maintain and
debug.

Once one is comfortable with this concept, I would argue the next step
in terms of building abstractions would be to bundle together all the
data relative to one pump into a `struct`. Then we would have a single
array (the elements of which are structs) instead of a collection of
arrays:

```c++
// Data structure describing a pump.
struct Pump {
    const uint8_t pin;
    const uint32_t half_period;  // half period in ms
    uint8_t state;               // LOW or HIGH
    uint32_t last_actuation;     // time in ms
};

const int pump_count = 3;

Pump pumps[pump_count] = {
// pin, half-T, state, last_actuation
    {5, 1000, LOW, 0},
    {6, 2500, LOW, 0},
    {7, 3200, LOW, 0}
};
```

The body of `setup()` and `loop()` would be very similar to the previous
version, but with `pump_pins[i]` replaced by `pumps[i].pin` and so on.

The third step in the abstraction ladder would be to embed the code that
handles the data structure with the data itself in a `class`, as shown
in Michel Keijzers' answer. With the proper methods defined, the main
sketch could be reduced to something like this:

```c++
#include "Pump.h"

Pump pumps[] = {
    Pump(5, 1000),
    Pump(6, 2500),
    Pump(7, 3200)
};

void setup() {
    for (Pump &pump : pumps)
        pump.begin();
}

void loop() {
    for (Pump &pump : pumps)
        pump.process();
}
```

I tried all these methods, and it turns out the first one (with a
collection of arrays) is the one that uses the least lines of code, and
the last one (with a class) uses the most. One could wonder then why use
more advanced abstractions, if they increase the amount of code one has
to type. The reason is, these abstractions become useful when the
program grows in complexity. On can put together all the code that deals
with the pumps in one place (maybe in a separate file), all the code
that deals with sensors in another place... and the main sketch that
puts all the pieces together remains simple.


message:
System crash after using sprintf

My Arduino crashes after using sprintf, To reduce system ram am trying to move away from strings to char and now this happened. Loop not working properly and it's not going to webrequest, spent 2 days to find a solution nothing worked yet. My project is to send temp and humidly to my server i was using strings and after one day of use system very slow to send data to server then i realized stings are the culprit then i changed to char

    char ventionoroff[6];

    char Foggeronoroff[6] ;

    char Exhuastonoroff[6] = "OFF";

    char current[4];

    char today[10];

    bool running = false;
    bool isFoggerRunning = false;
    bool isExhaustFanRunning = false;

    Time t;

    void loop() {

     t = rtc.getTime();

      hum = dht.readHumidity();
      temp = dht.readTemperature();
      delay(1000);

      if (isnan(hum) || isnan(temp)) {
        Serial.println(F("Failed to read from DHT sensor!"));
        return;
      }
      val = digitalRead(powerStatus);

          byte MIN = t.hour;
          byte SEC = t.min;

      char timeStamp[20];
     snprintf(today, "d:d",  MIN, SEC);

       Serial.println(today);

    if (millis() - lastConnectionTime > postingInterval) {
       Serial.println("reaching here2");
        httpRequest();
      }

      if (val)
      snprintf( current , "YES");

      else
     snprintf( current , "NO");

      if (running == false) {
        snprintf( Foggeronoroff , "WAIT");

      } else {
       snprintf( Foggeronoroff , "READY");

      }

        ventilationfan();

    void httpRequest() {
    Serial.println("shit reached here");
      client.stop();
      char data[10];
      const char phpScript[21]  = "";
      const char server[20]  =  ""; // also change the Host line in httpRequest()

       char strt[6];
       char str[6];
      sprintf(strt, "te=%d", temp);
      strcpy(data, strt);
      strcat (data,"&ti=");
      strcat (data,today);
       strcat (data,"&mot=");
       strcat (data,ventionoroff);
       strcat (data,",");
       strcat (data,Foggeronoroff);
        strcat (data,",");
        strcat (data,current);
         strcat (data,"&mo=");
         strcat (data,Exhuastonoroff);
          sprintf(str, "&hum=%d",hum);
          strcat (data,str);

     Serial.println(data);
       int len = strlen(data);
      if (client.connect(server, 80)) {
        client.print("POST ");
        client.print(phpScript);
        client.println(" HTTP/1.1");
        client.println("Host:");
        client.println("User-Agent: Arduino/1.0");
        client.println("Connection: close");
        client.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
        client.print("Content-Length: ");
        client.println(len);
        client.println();
        client.print(data);
        restartnet = 0;
         data[0] = 0;
         Serial.print("data after sucessfull connection");
         Serial.println(data);
         Serial.print("freeMemory after connection");
         Serial.println(freeMemory());
        lastConnectionTime = millis();

      } else {

         Serial.println(F("Failed"));
         data[0] = 0;

      }
    }

body:
There are quite a few points that could be improved in this code. The
main ones have already been shown in the comments:

1. the `data` buffer was not large enough to hold the whole string,
   which leads to a buffer overflow, memory corruption and, ultimately,
   the crash you are experiencing.

2. The second parameter to `snprintf()` should be the size of the
   provided buffer.

Here I will add a few points that, although not really defects of this
program, could help improved it and save memory.

Here:

```c++
char current[4];
// ...
if (val)
    snprintf(current, "YES");
else
    snprintf(current, "NO");
```

you are not using the `current` buffer to build a string, but only to
store one of two pre-existing strings (the literals `"YES"` and `"NO"`)
that are already stored in memory. Rather than making a copy, you could
instead reuse those pre-existing strings, and have `current` be a
pointer to the relevant one:

```c++
const char *current;
// ...
if (val)
    current = "YES";
else
    current = "NO";
```

This only saves two bytes (size of the buffer minus size of the
pointer), but this pattern happens multiple times in the program, and
the savings add up.

Now, another small optimization. Here:

```c++
char strt[6];
sprintf(strt, "te=%d", temp);
strcpy(data, strt);
```

you do not need the extra `strt` buffer, as you can write directly into
the `data` buffer. Better yet, you can write _everything_ into the
buffer in a single call to `snprintf()`:

```c++
snprintf(data, sizeof data,
        "te=%d&ti=d:d&mot=%s,%s,%s&mo=%s&hum=%d",
        temp, t.hour, t.min, ventionoroff, Foggeronoroff, current,
        Exhuastonoroff, hum);
```

If you don't like this approach, and would prefer writing the data in
separate calls to `snprintf()`, you can do so without using auxiliary
buffers. You have to remember (with a pointer) where within the buffer
you finished your previous write, and pass this address to the next
`snprintf()` call. Note that you also have to keep track of the room
that is still available, which is easy to do with a second pointer that
points to the end of the buffer:

```c++
char *p = data;                  // current writing position
char *end = data + sizeof data;  // end of the buffer
p += snprintf(p, end - p, "te=%d", temp);
p += snprintf(p, end - p, "&ti=%s", today);
// ...
```


message:
Why does Arduino round off some integers but not others when my desktop PC does not do this?

I am writing (in C) some low level digit manipulation routines that convert int to float and vice versa for Arduino. I came across some puzzling behaviour with Arduino rounding some numbers but not others. So I located and extracted the offending code into a simple program which I compiled on desktop Linux PC with GCC and on Arduino - they give different results. Why?
Here are the programs. The goal is to take the float number 1.3140 and the float number 2.3140 and split them into two integers. In the first case I expect '1' and '3140' and in the second case I expect '2' and '3140' (the terminal '0' is important for my application).
The Arduino code:
 ```
void setup() {
 double dnum,x,y;
 uint16_t intpart,fracpart;

 Serial.begin(9600);

 dnum = 1.3140;

  x=modf(dnum,&y);
  intpart = (uint16_t)y;
  fracpart = (uint16_t)(10000.0*x);

 Serial.println(dnum,4);
 Serial.println(intpart);
 Serial.println(fracpart);

}
```
and the output I get is:
```
1.3140
1
3140
```
Fantastic! Success. But hold on. If I change the hard-coded number to ```dnum = 2.3140``` I get this:
```
2.3140
2
3139
```
What? Why did it round the second part down? Am I doing something fundamentally wrong? So I wrote a little C program for my PC (compiled with gcc). Here is the code:
```
#include<stdint.h>
#include<stdio.h>
#include<math.h>

int main (int argc, char *argv[])
{
 double dnum,x,y;
 uint16_t intpart,fracpart;

 dnum = 2.3140;

  x=modf(dnum,&y);
  intpart = (uint16_t)y;
  fracpart = (uint16_t)(10000.0*x);

 printf("Int_part = %u\nFrac_Part = %u\n",intpart,fracpart);

 return 0;
}
```
When run I get this result:
```
Int_part = 2
Frac_Part = 3140
```
Now that's what I expect - and to be thorough I also did the above C program with ```dnum = 1.3140;``` and I again got the 'correct' expected result:
```
Int_part = 1
Frac_Part = 3140
```
So why does the Arduino round the fractional part down when I convert it to an integer sometimes and not others?
I tried this on a genuine Arduino Uno, a clone Arduino uno and a clone Arduino nano and all give the same results. In 'theory' it could be some difference in the compiler tolerance to some coding impropriety I have done (gcc is more tolerant) but can anyone tell me what I did wrong and how to get the Arduino to behave (the way I want it to)? Thanks.

body:
When you cast a floating point number to an integer, it always gets
rounded towards zero. If you want round-to-nearest behavior, you should
use the Arduino `round()` function.

As to the origin of the discrepancy you see, it comes from two facts:

1. The numbers you use are not exactly representable as floating point
   numbers.
2. The `double` on an Arduino Uno is actually equivalent to a `float`
   (32 bits only).

When you write a statement such as `dnum = 1.3140;`, the compiler stores
in `dnum` the floating point number that is closest to the decimal
number `1.3140`.

Compare:

```text
float32(1.3140) = 1.31400001049041748046875
float64(1.3140) = 1.31400000000000005684341886080801486968994140625
float32(2.3140) = 2.3139998912811279296875
float64(2.3140) = 2.31400000000000005684341886080801486968994140625
```

Out of these 4 examples, only `float32(2.3140)` is rounded down.


message:
Cant upload sketches

I started using the arduino as a hobby and it really is quite fun. I took a break for a bit and when I came back I wasnt able to upload a sketch to my UNO. I checked to see if I was using the correct port and programmer and everything seemed fine. Not exactly sure what to do so I was hoping someone could help me.
Thanks in advance.

Here is the error message I receive every time I try to upload a sketch:

```
Arduino: 1.8.13 (Windows 7), Board: "Arduino Uno"

C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\User\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\User\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\User\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=2341_0043 -ide-version=10813 -build-path C:\Users\User\AppData\Local\Temp\arduino_build_36096 -warnings=none -build-cache C:\Users\User\AppData\Local\Temp\arduino_cache_693101 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Users\User\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\User\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.avrdude.path=C:\Users\User\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\User\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avr-gcc.path=C:\Users\User\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\User\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -verbose C:\Users\User\Desktop\Arduino\Blink\Blink.ino

C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\User\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\User\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\User\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=2341_0043 -ide-version=10813 -build-path C:\Users\User\AppData\Local\Temp\arduino_build_36096 -warnings=none -build-cache C:\Users\User\AppData\Local\Temp\arduino_cache_693101 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Users\User\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\User\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.avrdude.path=C:\Users\User\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\User\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avr-gcc.path=C:\Users\User\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\User\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -verbose C:\Users\User\Desktop\Arduino\Blink\Blink.ino

Using board 'uno' from platform in folder: C:\Users\User\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3

Using core 'arduino' from platform in folder: C:\Users\User\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3

Detecting libraries used...

"C:\\Users\\User\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/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=10813 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR "-IC:\\Users\\User\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\User\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\standard" "C:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096\\sketch\\Blink.ino.cpp" -o nul -DARDUINO_LIB_DISCOVERY_PHASE

Generating function prototypes...

"C:\\Users\\User\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/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=10813 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR "-IC:\\Users\\User\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\User\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\standard" "C:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096\\sketch\\Blink.ino.cpp" -o "C:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096\\preproc\\ctags_target_for_gcc_minus_e.cpp" -DARDUINO_LIB_DISCOVERY_PHASE

"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\\User\\AppData\\Local\\Temp\\arduino_build_36096\\preproc\\ctags_target_for_gcc_minus_e.cpp"

Compiling sketch...

"C:\\Users\\User\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR "-IC:\\Users\\User\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\User\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\standard" "C:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096\\sketch\\Blink.ino.cpp" -o "C:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096\\sketch\\Blink.ino.cpp.o"

Compiling libraries...

Compiling core...

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\wiring_pulse.S.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\WInterrupts.c.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\wiring_analog.c.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\wiring.c.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\wiring_digital.c.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\hooks.c.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\wiring_pulse.c.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\wiring_shift.c.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\CDC.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\HardwareSerial.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\HardwareSerial1.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\HardwareSerial2.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\HardwareSerial3.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\HardwareSerial0.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\Print.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\Stream.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\Tone.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\WMath.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\PluggableUSB.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\WString.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\USBCore.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\new.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\abi.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\IPAddress.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\main.cpp.o

Using previously compiled file: C:\Users\User\AppData\Local\Temp\arduino_build_36096\core\core.a

Archiving built core (caching) in: C:\Users\User\AppData\Local\Temp\arduino_cache_693101\core\core_arduino_avr_uno_cac111a68e84b6e7f84741aaeecd4f29.a

Linking everything together...

"C:\\Users\\User\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o "C:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096/Blink.ino.elf" "C:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096\\sketch\\Blink.ino.cpp.o" "C:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096/core\\core.a" "-LC:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096" -lm

"C:\\Users\\User\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096/Blink.ino.elf" "C:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096/Blink.ino.eep"

"C:\\Users\\User\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096/Blink.ino.elf" "C:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096/Blink.ino.hex"

"C:\\Users\\User\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-size" -A "C:\\Users\\User\\AppData\\Local\\Temp\\arduino_build_36096/Blink.ino.elf"

Sketch uses 924 bytes (2%) of program storage space. Maximum is 32256 bytes.

Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x33

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x33

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x33

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x33

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x33

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x33

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x33

avrdude: stk500_recv(): programmer is not responding

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

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x33

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x33

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x33

```

Hope you will be able to help

body: It's a generic communications error between the Arduino and your PC, there can be many reasons for this, going through the steps outlined in Juraj's link above may get you closer to the cause. Another thing worth trying is holding down the Arduino reset button until uploading starts then releasing it.


message:
MQTT connection not being recognised in void loop()

I am trying to publish MPU 9250 readings in the Adafruit IO sending the data from ESP32. The WiFi connection is being established, but the code is not going inside the `if(mqtt.connected())` inside the `void loop()` whereas it's going inside the same command inside the `void setup()`.

I am sure there are no connection issues because once I change `if(mqtt.connected())` to `while(mqtt.connected())` inside `setup()`, code is going inside the `while` loop continuously.

Why is the code not going inside the `if` command and how can this be solved?

```c++
#include <WiFi.h >
#include <Adafruit_MQTT_Client.h>
#include <MPU9250.h>

#define wifi "********"
#define password "********"
#define server "io.adafruit.com"
#define port 1883
#define username "*******"
#define key "********"

WiFiClient esp;
MPU9250 IMU(Wire,0x68);
Adafruit_MQTT_Client mqtt(&esp, server, port, username, key);
Adafruit_MQTT_Publish feed = Adafruit_MQTT_Publish(&mqtt, username"feeds/accelerodata");

void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println("Adafruit MQTT Demo");
  Serial.println("Connecting to");
  Serial.println(wifi);
  WiFi.begin(wifi,password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting...");
  }
  Serial.println("Connected");
  Serial.println("IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Connecting to MQTT");

  if (mqtt.connect()) {
    Serial.println("MQTT Connected");
  }
}

void loop () {
  Serial.println("Test line to check if code reaches inside loop");
  delay(1000);

  if (mqtt.connected()) {
    int data=IMU.getAccelX_mss();
    Serial.println("\nSending accelero data");
    Serial.println(data);
    Serial.println("....");
    if (feed.publish(data)) {
      Serial.println("Success");
    } else {
      Serial.println("Fail");
    }
    delay(800);
  }
}

```

body:
I believe your problem is that you are attempting to use the MQTT connection before it's actually connected.  So your check:

    if(mqtt.connected())

is always FALSE since it's not really connected.  The Adafruit library information here:

[Adafruit MQTT][1]

Says to initialize MQTT as:

    // Function to connect and reconnect as necessary to the MQTT server.
    // Should be called in the loop function and it will take care if connecting.
    void MQTT_connect() {
      int8_t ret;

      // Stop if already connected.
      if (mqtt.connected()) {
        return;
      }

      Serial.print("Connecting to MQTT... ");

      while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
           Serial.println(mqtt.connectErrorString(ret));
           Serial.println("Retrying MQTT connection in 5 seconds...");
           mqtt.disconnect();
           delay(5000);  // wait 5 seconds
      }
      Serial.println("MQTT Connected!");
    }

  [1]: https://learn.adafruit.com/mqtt-adafruit-io-and-you/intro-to-adafruit-mqtt


message:
What's the best way to operate a remote control circuit board?

What would be the best way of using an Arduino to operate the pictured remote control circuit board? My initial instinct would be to leave the batteries in the remote and use a separate transistor for each of the five switches, connecting wires (solder or electrical tape) to the two sides of each button and the base to an Arduino output pin. I'm certainly not an expert, so I wanted to confirm whether (a) that would work and (b) if there's a much better way. The control is normally powered by two AAA batteries.
[![enter image description here][1]][1]

Edit: There's also a small capacitor on the underside of the circuit board, if that changes anything.
[![enter image description here][2]][2]

Thanks in advance for your help

Note: I've tried to simply record and emit the IR signals from the remote using my Arduino, but have thus far been unsuccessful, so want another way of using the Arduino to control my fan: https://arduino.stackexchange.com/questions/79935/unable-to-control-fan-with-ir-circuit-despite-capturing-and-reproducing-the-ir-t

  [1]: https://i.stack.imgur.com/x4Sep.jpg
  [2]: https://i.stack.imgur.com/4cnIa.jpg

body:
All the right sides of the buttons are connected to the negative of the battery (that is ground). So you connect the remotes GND to the Arduinos GND.

Next solder five wires to the left side of the buttons. You can do this by scraping away a bit of the green solder mask that's on top of the trace going to that button pad. Or find out which pin on the IC goes to the button, and solder a wire to that leg.

I wouldn't mess with the black stuff (graphite?) on top of button pad. That way you can always return the remote to it's original function.

Then connect those wires to the Collectors of NPN transistors. The Emitters all connect to GND. The Bases (via a resistor) to the Arduino pins.

Alternatively, you can connect them directly to the Arduino pins. But you'd have to be careful to never set the pin to HIGH, as the remote won't like 5V on it's input pins while it is itself running on only 3V. You "press" the button by setting the pin to OUTPUT. After a "press" you set it back to input.

To prevent accidentally supplying 5V to the button pin, you can also use diodes (instead of transistors described above). Put the diode between the Arduino pin, and the button wire, pointing towards the Arduino. That way current can only go towards the Arduino. Then you can safely use `digitalWrite`.


message:
ESPTOOL not recognizing ESP32-S2 chip for SPIFFs transfer

I have a spiff file that uploads fine using a regular esp32, but when I try on the esp32-32, with a fresh installation, I get:

esptool.py v3.0-dev
Serial port COM3
Connecting....

A fatal error occurred: This chip is ESP32-S2 not ESP32. Wrong --chip argument?
SPIFFS Upload failed!

Any ideas??

Thanks

body:
Is the missing double dash?

    esptool.py --chip esp32s2 --port COM3 --baud 115200 write_flash -z 0x110000 filename.spiffs.bin


message:
LCD shows wrong value from MQ-135 sensor and the txt is stuck on screen

i am using a MQ-135 gas sensor and 20x4 LCD screen and it shows different values on the serial
monitor it shows 756 PPM and on the LCD screen it is stuck below 320PPM the text BAD is also stuck on the screen and doesn't update on the
lowering of PPM value of CO2

[![enter image description here][1]][1]

 this is my code

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    #define sensor A0
    int gas, co2lvl;
    #define updateDisplay();

    void setup()
    {
    pinMode(sensor,INPUT);
    Serial.begin(9600);
    lcd.begin(20,4);
      lcd.clear();
    }

    void loop()
    {
    co2lvl=gas-255;
    co2lvl=map(co2lvl, 0,1024,400,5000);
    Serial.print(co2lvl);
    Serial.print("ppm");
    Serial.println();
    delay(200);
    if(co2lvl>=699){
    updateDisplay();
    lcd.setCursor(0,0);
    lcd.print("CO2 IN THE AIR");
    lcd.setCursor(0,1);
    lcd.print(analogRead(co2lvl));
    lcd.setCursor(6,1);
    lcd.print("EXCELLENT");
    }
    else if(co2lvl<=700){
    updateDisplay();
    lcd.setCursor(0,0);
    lcd.print("CO2 PRESENT IN THE AIR");
    lcd.setCursor(0,1);
    lcd.print(analogRead(co2lvl));
    lcd.setCursor(4,1);
    lcd.print("GOOD");}
    else if(co2lvl<=900){
      updateDisplay();
      lcd.setCursor(0,0);
    lcd.print("CO2 PRESENT IN THE AIR");
    lcd.setCursor(0,1);
    lcd.print(analogRead(co2lvl));
    lcd.setCursor(5,1);
    lcd.print("FAIR");}
    else if(co2lvl<=1100){
      updateDisplay();
      lcd.setCursor(0,0);
    lcd.print("CO2 PRESENT IN THE AIR");
    lcd.setCursor(0,1);
    lcd.print(analogRead(co2lvl));
    lcd.setCursor(5,1);
    lcd.print("MEDIOCRE");
    }
    else(co2lvl<=1600);{
      updateDisplay();
      lcd.setCursor(0,0);
    lcd.print("CO2 PRESENT IN THE AIR");
    lcd.setCursor(0,1);
    lcd.print(analogRead(co2lvl));
    lcd.setCursor(5,1);
    lcd.print("BAD");}
    }

  [1]: https://i.stack.imgur.com/Zmlgn.jpg

body:
You made a mistake in the line:

    else(co2lvl<=1600);

Because of the semicolon (;) it will not do anything for that condition. But instead the following lines will be executed always.

The following is a slight refactoring making your code more clear, removing also duplicated code:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    #define sensor A0
    int gas, co2lvl;

    void setup()
    {
      pinMode(sensor,INPUT);
      Serial.begin(9600);
      lcd.begin(20,4);
      lcd.clear();
    }

    void loop()
    {
      co2lvl=gas-255;
      co2lvl=map(co2lvl, 0,1024,400,5000);
      Serial.print(co2lvl);
      Serial.print("ppm");
      Serial.println();
      delay(200);

      lcd.setCursor(0,0);
      lcd.print("CO2 PRESENT IN THE AIR");
      lcd.setCursor(0,1);
      lcd.print(analogRead(co2lvl));

      if      (co2lvl <=  300) { show(6, "EXCELLENT"); }
      else if (co2lvl <=  700) { show(4, "GOOD"     ); }
      else if (co2lvl <=  900) { show(5, "FAIR"     ); }
      else if (co2lvl <= 1100) { show(5, "MEDIOCRE" ); }
      else if (co2lvl <= 1600) { show(5, "BAD"      ); }
    }

    void show(int position, char* text)
    {
      lcd.setCursor(position, 1);
      lcd.print(text);
    }


message:
Multiple peripherals using SPI with a Mega

I am using a Mega 2560 and 2 x [AD9833 programmable waveform generators.](https://www.analog.com/media/en/technical-documentation/data-sheets/ad9833.pdf)

The AD9833's use a SPI protocol and I have used [vwlowen's code](http://www.vwlowen.co.uk/arduino/AD9833-waveform-generator/AD9833-waveform-generator.htm) as a jumping off point (I'm not usng the display just the generators). I added a `channel` variable to select the slave device.

It all works fine until I try to add a second AD9833. I saw [this post](https://arduino.stackexchange.com/questions/17447/arduino-mega-2560-multiple-slave-via-spi) about more than 1 peripheral using SPI & a Mega, that says I can use any pin for slave selection (SS) but the following code only ever works if I use pin 53. The upshot if which is that I can send the same data to both i.e. both share the same SS pin as long as that pin is 53. Any other SS pin selection is ignored by the devices. I tried pin 49 for both & no change, I''ve tried 53 & 49 yet only the device on 53 changes.

So what's going on here? What's so special about pin 53 that it cant be replicated by another output pin?

    /*
    Amended code for AD9833 Waveform Module originally from vwlowen.co.uk
    Common SPI terminology & pinout on AD9833
    MOSI - DATA
    SCLK - CLK
    SS   - FSYNC
    MISO - not implemented i.e. ther is no MISO pin on the AS9833
    */

    #include <SPI.h>

    const int SINE     = 0x2000;                // Define AD9833's waveform register value.
    const int SQUARE   = 0x2028;                // When we update the frequency, we need to
    const int TRIANGLE = 0x2002;                // define the waveform when we end writing.

    const float refFreq = 25000000.0;           // On-board crystal reference frequency

    const int FSYNCA = 53;                       // Standard SPI pins for the AD9833 waveform generator.
    //const int FSYNCB = 49;
    const int CLK    = 52;                       // CLK and DATA pins.
    const int DATA   = 51;

    unsigned long freq = 1000;                   // Set initial frequency.

    void setup() {

      pinMode(FSYNCA, OUTPUT);
      // pinMode(FSYNCB, OUTPUT);

      SPI.begin();
      SPI.setDataMode(SPI_MODE2);
      delay(50);

      AD9833reset();                                   // Reset AD9833 module after power-up.
      delay(50);
      AD9833setFrequency(freq, SQUARE, FSYNCA);        // Set the frequency and Sine Wave output
     // AD9833setFrequency(freq, SINE, FSYNCB);

    }

    void loop() {

    // TODO: PC control via USB

    }

    // AD9833 documentation advises a 'Reset' on first applying power.
    void AD9833reset() {
      WriteRegister(0x100, FSYNCA);   // Write '1' to AD9833 Control register bit D8.
      delay(10);
     // WriteRegister(0x100, FSYNCB);
     // delay(10);
    }

    // Set the frequency and waveform registers in the AD9833.
    void AD9833setFrequency(long frequency, int Waveform, int channel) {

      long FreqWord = (frequency * pow(2, 28)) / refFreq;

      int MSB = (int)((FreqWord & 0xFFFC000) >> 14);    //Only lower 14 bits are used for data
      int LSB = (int)(FreqWord & 0x3FFF);

      //Set control bits 15 ande 14 to 0 and 1, respectively, for frequency register 0
      LSB |= 0x4000;
      MSB |= 0x4000;

      WriteRegister(0x2100, channel);
      WriteRegister(LSB, channel);                  // Write lower 16 bits to AD9833 registers
      WriteRegister(MSB, channel);                  // Write upper 16 bits to AD9833 registers.
      WriteRegister(0xC000, channel);               // Phase register
      WriteRegister(Waveform, channel);             // Exit & Reset to SINE, SQUARE or TRIANGLE

    }

    void WriteRegister(int dat, int channel) {

      digitalWrite(channel, LOW);         // Set FSYNC low before writing to AD9833 registers
      delayMicroseconds(10);              // Give AD9833 time to get ready to receive data.

      SPI.transfer(highByte(dat));        // Each AD9833 register is 32 bits wide and each 16
      SPI.transfer(lowByte(dat));         // bits has to be transferred as 2 x 8-bit bytes.

      digitalWrite(channel, HIGH);        //Write done. Set FSYNC high
    }

body:
> What's so special about pin 53

Pin 53 is the slave select pin of the SPI peripheral. As such it has a bearing on how the SPI peripheral operates.

It is intimately tied to the master/slave operation in that when it's an input SPI works in slave mode, and when it's an output it runs in master mode.

So to use SPI in master mode, whether you use pin 53 or not, it *must* be in OUTPUT for SPI to work at all.

There is nothing much wrong with your methodology, but one thing is missing: the initial state of the chip select pins.

You should always start with all chip select pins *disabled* (i.e., HIGH) rather than in an unknown (probably low - I'd have to check the datasheet) state - the exception might be pin 53 which SPI might itself set HIGH for you.

So if you add:

```c++
digitalWrite(FSYNCA, HIGH);
digitalWrite(FSYNCB, HIGH);
```

right after setting the `pinMode` for your pins and still use both pins 53 and 49 then it *should* work.


message:
Adding a common activation pin to a group of buttons

I'm working on an Uno, which has only two interrupt capable pins, but i need at least three buttons to wake it up from its power saving mode.

Is there a way to wire buttons such that, in addition to their individual pin, they will also activate a common pin (in this case, the interrupt one)?

body:
You can connect all the buttons to a single interrupt pin by ORing them via diodes (like Gerben wrote in the comments). That would look like this:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/K970B.png)

<!-- End schematic -->

The diodes isolate each input pin from the other, but allow the buttons to pull down the interrupt pin.

Though that is not the way, that I would suggest. Instead you could simply use the PinChange interrupt. That is a different type of interrupt, which can react to all pins of a port in a single ISR for the whole port. You can mask unused pins of the port away, so that the interrupt doesn't trigger for them. Nearly every pin is usable that way.

If you want to use the Arduino framework for this, you can just use the `attachInterrupt()` function, which can use the PinChange interrupt in the background.

If you want to go more down into the hardware side and configure the interrupt yourself, you should look into the corresponding sections of the datasheet. The Uno uses the [Atmega328p][1]. From 12.2.4 on you see the registers used for the PinChange interrupt (aka PCINT).

- With the bits in `PCICR` you can enable the PinChange interrupt for the ports (3 distinct interrupts for the Uno).
- The `PCMSKn` (`n` meaning number between 0 and 2) is used to mask unused pins of the port away. You should set the bits for the used pins to 1, the others to zero.

Then you need to define the actual Interrupt Service Routine (ISR) in your code:

    ISR (PCINTn_vect) // handle pin change interrupt for D8 to D13 here
    {
        ...
    }

Here again substitute the `n` for the number of the PinChange interrupt, that you are using. Inside the ISR you need to read all the input pins of the buttons, that are connected to this PinChange interrupt, and execute your code accordingly. **Note:** As the name states, the interrupt is triggered on every change of the pin. Inside the ISR you need to sort out, what change that was. It comes down to just reading the pin, but you should keep that fact in mind.

Also make sure to never do long things inside an ISR; it has to be as short as possible; Do long things inside the main code, which can get triggered via a flag variable from the ISR)

If you google for something like "Arduino pin change interrupt" you can find detailed tutorials for this, which can go way deeper, than I can on this Q&A site.

> Will this also work while in CPU sleep mode from the avr/sleep.h
> library?

According to Table 9-1 in Chapter "9.1 Sleep Modes" in the datasheet, the PinChange interrupts are on the same level as the External Interrupts INTn in regard of sleep modes. So this should work just like with the INTn interrupts.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf


message:
DFPlayer Mini with its standard library does not being initialized

I have a [DFPlayer Mini][1] bought from AliExpress.
The player works correctly in standalone mode, but I am having troubles while using it with the following components:

 - Seeduino v4.0;
 - 2GB Smartbuy MicroSD card.

When I try to use [this][2] standard sketch for Arduino to connect my Seeeduino V4 to the player:

 -  if I set the serial like `mySoftwareSerial(11, 10)`, the player's tiny LED turns on for 2 seconds, then it switches off, and after that, the board tells me the error message below ([video here][3]);
 -  if I set the serial like `mySoftwareSerial(10, 11)`, the player`s tiny LED switches on and remains being switched on, while the board tells me the error message below ([video here][4]):
```
DFRobot DFPlayer Mini Demo
Initializing DFPlayer ... (May take 3~5 seconds)
Unable to begin:
1.Please recheck the connection!
2.Please insert the SD card!
```
This module's image:
[![Image][5]][5]

The circuit diagram:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/jkQ6J.png)

<!-- End schematic -->

I have tried almost everything I could. I changed the filenames on my SD card, tried to use different pins, tried to use different wires..! I even tried to disconnect the speaker from the player!

I also had seen [this][6] message on the manufacturer`s forum:
>I found that the solder joint on the TX pin was bridged to the SD card holder, effectively bridging the pin to the ground. Try a continuity test between the TX and ground. If they are connected you have a bad joint.
I was able to remove the excess solder and it worked fine after that. It's a medium difficulty soldering task.

Maybe, it`s my case?

  [1]: https://aliexpress.com/item/32657798948.html?cv=815660&af=701906&utm_campaign=701906&aff_platform=link-c-tool&utm_medium=cpa&afref=https://trade.aliexpress.ru/orderList.htm?spm=a2g0o.home.1000001.13.75df5c98WvdGQj&tracelog=ws_topbar&tsp=1607520665047&sk=mr6wR6CC&aff_trace_key=c2657ff46a764496af298ef45bc120e6-1607520697616-05778-mr6wR6CC&dp=a66fcc28efcfbf5dab07e08864c73497&terminal_id=049661e6cfa5453b8ac1fb4fa188d0b9&utm_source=admitad&utm_content=815660&sku_id=59838362104
  [2]: https://wiki.dfrobot.com/DFPlayer_Mini_SKU_DFR0299#target_7
  [3]: https://youtu.be/-WJ0eYgYyD8
  [4]: https://youtu.be/a1FzlGiyJK8
  [5]: https://i.stack.imgur.com/Irdwr.jpg
  [6]: https://www.dfrobot.com/forum/viewtopic.php?p=43180#p43180

body: Please check if the `RX`/`TX` pins are messed up. In my case, simply `RX` and `TX` wires' places' switching did help!


body: I simply removed the test for the return value of the constructor and assumed it initialised correctly.  It then ran properly every time I started it.  I have no explanation for this, but it worked.


message:
Remove a sudden pulse on pin d3 of nodemcu when powering it up

I am using node mcu and a 2 channel relay connected to the motor via pin d3.
When I power on the circuit, it shoots a pulse to the relay and i think it will damage the motor.
Please suggest me how to stop that pulse from turning on the motor.

body:
D3 is GPIO0, which is used as an active low input to signal the ESP8266 bootloader to expect programming after a reset.

Use a different pin.