body:
The only problem I can see is in your use of the `counter` variable. This is a volatile variable that is incremented in an interrupt routine and read from the main loop context.  The variable is "non atomic" in that it is made up of a number of smaller bytes (at least on 8 bit Arduinos it is) which means it takes multiple sequential instructions to read it from memory.

At any point during that sequence the interrupt could trigger and modify the value, corrupting your data.

You should always use a *critical section* around any accesses to variables that are modified inside interrupt routines, such as:

```c++
noInterrupts(); // Disable interrupts
uint32_t currentCount = this->counter; // Grab the current count
interrupts(); // Re-enable interrupts

// Do things with currentCount instead of this->counter
```


sender: user

message:
Is there anything wrong with this code

Hi I'm pretty new to cpp.
Could someone review my code and explain any pitfalls or problems?
Below is the code and an example to read from a flow meter with a hall sensor.
Thanks in advance.
Greg

```c++
    /** example
    #include "flow.h"
    Flow f(3);
    Flow f2(4);
    volatile unsigned int counter;
    void flow_counter() // ISR
    {
          // Increment the pulse counter
          counter ++;
    }

    void setup()
    {
      f.start(); //using default ISR
      f2.assign_isr(&flow_counter);
      f2.assign_counter(&counter);
      f2.start();
    }

    void loop()
    {
     Serial.printf("flow rate on 3 = %f \n",f.rate());
     Serial.printf("flow total = %dml %f%% of 500ml \n",f.total_ml(),f.percent(500));
     Serial.printf("flow rate on 4 = %f \n",f2.rate());
     delay(1000);
    }

    */

    #include <math.h>
    #include "Arduino.h"

    volatile unsigned int flowPulseCounter;
    void flowCounter() // ISR
    {
          // Increment the pulse counter
          flowPulseCounter ++;
    }

    class Flow{
      public:
        Flow(uint8_t pin)
        {
          if(flowPin==254)
           flowPin = pin;
        }

        void assign_isr ( void (*isr)()){ this->flowISR = isr; };
        void assign_counter (volatile unsigned int * counter ){ this->counter = counter; };
        void assign_pin(uint8_t pin){ flowPin = pin; };

        void  set_calibration_factor( float factor ) { this->calibrationFactor = factor; };
        float get_calibration_factor( ) { return this->calibrationFactor; };

        uint8_t retrieve_pin(){ return flowPin; };

        void start()
        {
          detachInterrupt(digitalPinToInterrupt(this->flowPin));
          *this->counter = 0; // counter is a pointer so * assigns the value at that address to 0
          this->flowRate = 0;
          this->flowMillilitres = 0;
          this->flowMilliseconds = millis();
          pinMode(this->flowPin, INPUT_PULLUP);
          this->running = true;
          attachInterrupt(digitalPinToInterrupt(this->flowPin), this->flowISR, FALLING);
        }

        void calculate()
        {
          if(this->running)
          {
            this->flowRate = ((1000.0 / (millis() - this->flowMilliseconds)) * ( *this->counter )) / this->calibrationFactor;
            this->flowMilliseconds = millis();
            // convert to millilitres.
            this->flowMillilitres = (this->flowRate / 60) * 1000;
            // Add the millilitres to the cumulative total
            this->totalMillilitres += this->flowMillilitres;
          }
        }

        void stop()
        {
          detachInterrupt(digitalPinToInterrupt(flowPin));
          this->calculate();
          this->running = false;
          pinMode(this->flowPin, INPUT_PULLUP);
        }

        bool is_max( uint32_t millilitres )
        {
          this->calculate();
          return (this->totalMillilitres >= millilitres) ? true : false;
        }

        float percent( uint32_t millilitres )
        {
          this->calculate();
          return (float)((double) this->totalMillilitres / (double) millilitres)  * 100.0;
        }

        float rate ()
        {
          this->calculate();
          return this->flowRate;
        }

        uint32_t total_ml()
        {
          this->calculate();
          return this->totalMillilitres;
        }

      private:
        uint8_t flowPin=0;
        uint32_t flowMilliseconds = 0;
        float flowRate=0;
        uint32_t flowMillilitres = 0;
        uint32_t totalMillilitres = 0;
        float calibrationFactor = 4.5;
        bool running = false;
        void (*flowISR)() = &flowCounter;
        volatile unsigned int * counter = &flowPulseCounter;
    };

```

sender: assistant

body:
Here are some random comments from looking at the code.

First issue, which is more about the example than the library itself:
there is no `Serial.printf()` in the standard Arduino cores. Yes, it is
provided by some alternate cores, and it is a shame it is not available
in the Arduino ones, but that's how it is.

In the constructor, there is `if(flowPin==254)`. Why this condition?
`flowPin` is initialized to zero, so it would seem the condition should
always be false.

As a matter of style, you can remove all the `this->` from the methods.
It is implicit anyway.

For the sake of naming consistency, I would rename `retrieve_pin()` as
`get_pin()`, and all the `assign_*()` method as `set_*()`.

It is not useful to `detachInterrupt()` right before
`attachInterrupt()`, as the latter implies the former.

In `calculate()`, avoid calling `millis()` twice. You have no guarantee
that both calls will return the same value and, if they do not, the
timing calculations will be off. Also, this function will fail badly
(division by zero) if called twice within the same millisecond.

It makes no sense to convert a flow rate to milliliters. Do you mean
milliliters per minute? Per second? In any case, you here converting a
rate to another unit, but it is still a flow rate.

The computation of `totalMillilitres` is wrong: it is incremented by a
flow rate. It should instead be incremented by a product rate × time. Or
better yet: compute it from the pulse count, without going through the
rate. Otherwise you are computing a numerical derivative (to get the
rate) only to integrate it later (to get a total volume). This extra
computations serve no purpose other than accumulating rounding errors.

------------------------------------------------------------------------

**Edit**: Thinking further about this program, I found a few more things
that I think could be improved. A couple of minor points an one not so
minor.

One of the minor points is that `begin()` would be a better name for
`start()`, for consistency with most other Arduino libraries.

Another one is that there are a couple of methods that have no business
being in the class: `is_max()` and `percent()`. They are trivial
calculations that are in no way related to handling a flow meter. As a
user of the library, I would rather write

```c++
if (flow.total_ml() >= threshold_volume) ...
```

than

```c++
if (flow.is_max(threshold_volume)) ...
```

as the former is way clearer and easy to understand.

The more serious point is about the handling of multiple flow meters.
The first one is completely handled by the library, which is nice.
However, for the second one, the user has to provide the lowest level
bricks. The user of a library should not have to handle himself such
low-level details. Thus, I think both the counter variable and the ISR
function should be handled by the library, as members of the `Flow`
class.

I am aware this creates some difficulties. In order to be attached to an
interrupt, the ISR should be a static method of the class. In order for
this method to access the counter, that counter should be a static
member. In order for each flow meter to have its own counter, we must
have a separate class for each one.

I found a solution that I think is elegant enough: have `Flow` be a
_class template_, parametrized by the pin number. This creates a
separate class for each flow meter. In order to avoid code duplication,
these classes could be almost empty shells that delegate as much as
possible to a handler which is a common, regular class.

Here is what that “handler” class could look like. It has everything
but the ISR:

```c++
class FlowMeterHandler {
    // Everything here is private, only accessible to the Flow class.
    template<uint8_t pin> friend class Flow;
private:
    void begin(uint8_t pin, void (*isr)()) {
        attachInterrupt(digitalPinToInterrupt(pin), isr, FALLING);
    }
    float flow_rate() {
        uint32_t now = millis();
        if (now - last_millis >= 10) {
            uint32_t this_count;
            noInterrupts();
            this_count = count;
            interrupts();
            last_flow = calibration * (this_count - last_count)
                                    / (now - last_millis);
            last_millis = now;
            last_count = this_count;
        }
        return last_flow;
    }
    // + other methods...
    volatile uint32_t count = 0;
    uint32_t last_count = 0;
    uint32_t last_millis = 0;
    float last_flow = 0;
    float calibration = 1e3 / 4.5;
};
```

I've written the methods inline, but you could also put the
implementations in a separate .cpp file.

And here is the template class. Save for the ISR, it forwards everything
to the handler.

```c++
template<uint8_t pin> class Flow {
public:
    static void begin() { handler.begin(pin, isr); }
    static float flow_rate() { return handler.flow_rate(); }
    // other methods also forwarded to the handler...
private:
    static FlowMeterHandler handler;
    static void isr() { handler.count++; };
};

template<uint8_t pin> FlowMeterHandler Flow<pin>::handler;
```

Note that the class has no instance data: everything in it is `static`.

Here is how this would be used:

```c++
Flow<3> f1;
Flow<4> f2;

void setup()
{
    f1.begin();
    f2.begin();
}

void loop()
{
    Serial.print(F("flow rate on 3 = "));
    Serial.println(f1.flow_rate());
    Serial.print(F("flow rate on 4 = "));
    Serial.println(f2.flow_rate());
    delay(1000);
}
```


body:
Ok so if anyone is interested here is what I ended up with

```c++
/*
  this is yet to be varified but comes from the following links
  *
  https://www.bc-robotics.com/tutorials/using-a-flow-sensor-with-arduino/

  "These are not able to monitor a flow of less than 1 liter per minute or in excess of 30 liters per minute.
  The sensor is rated to a Maximum of 2.0MPa (290 PSI) "
  and
  every rotation means 2.25mL of fluid has passed the sensor

  another is

  https://diyhacking.com/projects/FlowMeterDIY.ino
  "// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
   // litre/minute of flow.
  "

  then finally

  https://arduino.stackexchange.com/questions/84578/is-there-anything-wrong-with-this-code

  I make no personal claim to any of this code. It is simply my version of Edgar's version.
  Thanks Edgar
  *
  *
  *
  * I have used start and stop as they signify the start and stop of the process
  * the class begins when it starts and has no end the isr stays linked to the class for the duration
  * and start simply attaches the interrupt to the isr
  * stop simply calculates the total volume and detaches the interrupt.
  *
  * as flow rate related to time
  * just set your own start time
  * read the total_ml
  * then after your own predefined time
  * read the total_ml again
  * and work out the flow rate from that.
  */

class FlowMeterHandler {
  // Everything here is private, only accessible to the Flow class.
  template<uint8_t pin> friend class Flow;
private:

  void start(uint8_t pin, void (*isr)())
  {
    noInterrupts();
    count = 0;
    interrupts();
    attachInterrupt(digitalPinToInterrupt(pin), isr, FALLING);
  }

  void stop(uint8_t pin)
  {
    detachInterrupt(digitalPinToInterrupt(pin));
  }

  unsigned int count_is()
  {
    unsigned int this_count;
    noInterrupts();
    this_count = count;
    interrupts();
    return this_count;
  }

  volatile unsigned int count = 0;
  unsigned int ul_per_tick = 2250;

};

template<uint8_t pin> class Flow {
public:
    static void start() { handler.start(pin, isr); }
    static void stop() { handler.stop(pin); }
    static unsigned int total_ul() { return handler.count_is() * handler.ul_per_tick; }
    static unsigned int total_ml() { return ( handler.count_is() * handler.ul_per_tick ) / 1000 ; }
    static void set_ul_per_rotation( unsigned int ul) { handler.ul_per_tick = ul; }
private:
    static FlowMeterHandler handler;
    static void isr() { handler.count++; };
};

template<uint8_t pin> FlowMeterHandler Flow<pin>::handler;

```

the example ino looks like this
```c++
#include "flow.h"
Flow<3> f1;
Flow<4> f2;

void setup()
{
    f1.start();
    f2.start();
}

void loop()
{
    Serial.print(F("So far volume on 3 = "));
    Serial.println(f1.total_ml());
    Serial.print(F("and the volume on 4 = "));
    Serial.println(f2.total_ml());
    delay(1000);
}
```

Compiles cleanly on all my boards.
Runs ???
Any other suggestions will be gratefully received.

Thanks.
Greg


message:
LEDs not lighting up even though current is flowing through them, problem with ground?

I'm using a 74HC595N shift register to light up 8 LEDs but for some reason they won't turn on even though current is flowing through all of them. I provided an image of my circuit below, there is a test LED for checking current flow:

[![This is my circuit][1]][1]

I am using a 9A103G resistor network to connect all the LEDs to a common ground. I have tried this with 8 individual 330 ohm resistors in the past but the result is the same, and every time the problem was with the ground wire, current is not flowing through it even though all the resistors I've used showed that current was flowing through them (see below):

[![Current going through resistor network][2]][2]

The following image shows the same test LED not lighting up when connected to the common ground pin of the resistor network:

[![No current going through ground wire][3]][3]

  [1]: https://i.stack.imgur.com/lHNmZ.jpg
  [2]: https://i.stack.imgur.com/h1Zg2.jpg
  [3]: https://i.stack.imgur.com/WfdOw.jpg

I could use some help fixing this issue because it is preventing me from using shift registers for future projects (this only happens when I use shift registers) - I would like to know what is causing this problem so I can avoid it later on. Thanks in advance!

body:
(Just to illustrate what Majenko is saying.)

This is the inside of a breadboard:

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

All your connections are on one side of that; you've tied everything to a single point.

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


message:
Arduino with LCD Display does not reset/restart/start on connection to power

A friend and I have been working on an Arduino Sketch that does a request to a local API, parses that data and prints it out on an LCD Display.

When we upload the sketch to the Arduino it does exaclty what it should and shows the following on the LCD Display:
[![LCD with Data][1]][1]

But when we disconnect the Arduino from the PC and reconnect it to the PC (or to any other power source), the following shows up on the LCD:
[![enter image description here][2]][2]

It seems as if the Arduino simply does not restart the Sketch and stays idle, while giving the LCD a weird output. When we open the Serial Monitor, in the Arduino IDE, the Arduino reboots and the correct information shows up again. Pressing the reset button on the Arduino itself did not work and seems to do nothing.

When trying other examples (e.g. Blink) it does restart on reconnecting to the PC, so it seems that the problem lies with our code.

Here is our full code:
```lang-cpp
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoJson.h> // Library to deserialize JSON
#include <Wire.h> // Library for I2C communication
#include <LiquidCrystal_I2C.h> // Library for LCD

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

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

int refreshRate = 5000;

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

WiFiClient client;

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

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

  memset(json, 0, sizeof json);

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

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

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

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

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

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

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

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

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

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

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

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

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

Thanks in advance!

  [1]: https://i.stack.imgur.com/W7mCM.jpg
  [2]: https://i.stack.imgur.com/CLqsB.jpg

body:
You've tagged the question with both `nano` and `arduino-nano-33-iot`, but I'm guessing between the two you're using the latter, because on Arduinos with native USB (not a plain Arduino Nano) `while (!Serial) continue;` [waits][1] for a serial connection, e.g. Serial Monitor, to be connected.

This doesn't happen when you're on a power supply, or just connecting it to a machine without opening the port.

If you want blink an led inside this loop to see that it is in fact stuck there.

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/ifserial/


message:
SPI synchronization with Arduino DUE and ADIS16364 IMU

I'm trying to use an Arduino Due to interface with an ADIS16364 IMU from Analog Devices ([product info here][1]) via SPI.

There are two modes for retrieving the measurements from this particular IMU (six 16 bit values, 3 acc, 3 gyros):

1. The first mode is, if I'm not wrong, the standard one with SPI, in which each successive transfer command retrieves the last data requested and indicates which one should be retrieved next.

2. The second possibility is a so called "burst mode". For this one you have to request the 0x3E00 register. After that, the IMU will burst out the six measurements (plus a few other bits of information like temperature and supply voltage). From the specs sheet:

[![enter image description here][2]][2]
[![enter image description here][3]][3]

The problem is, I can not manage to make the Arduino read the data using this burst mode. This is the code I'm using to test the communication:

    #include <SPI.h>
    #define SerialBT Serial2

    short supply, xgyro, ygyro, zgyro, xacc, yacc, zacc, xtemp, ytemp, ztemp, aux;
    volatile byte fDataIMUtoRead = 0;
    int pauseBetweenTransfers;

    void setup() {

      SerialBT.begin(230400);

      pinMode(52, OUTPUT);

      // Configure SPI
      SPI.begin(52);
      SPI.setClockDivider(52, 200); // 84e6/200 = 420kHz
      SPI.setDataMode(52, SPI_MODE3);
      SPI.setBitOrder(52, MSBFIRST);

      // Set sample rate
      float Fs = 1; // Target sampling frequency [Hz]
      float tb = 0.61035 * (Fs >= 12.7009) + 18.921 * (Fs < 12.7009);
      unsigned long tbsel = 0 * (Fs >= 12.7009) + 1 * (Fs < 12.7009);
      unsigned long Ns = (uint16_t) round((1000.0 - tb * Fs) / (tb * Fs));
      float Feff = 1000 / (tb * (Ns + 1));
      SerialBT.print("Selected freq: ");
      SerialBT.println(Feff, DEC);

      digitalWrite(52, LOW);  // Doesn't seem to be necessary
      SPI.transfer16(52, (0L << 15) | (0x36L << 8));                       delayMicroseconds(100);
      SPI.transfer16(52, (1L << 15) | (0x36L << 8) | (tbsel << 7) | Ns );  delayMicroseconds(100);
      SPI.transfer16(52, (0L << 15) | (0x36L << 8));                       delayMicroseconds(100);
      zgyro = SPI.transfer16(52, 0x00);
      digitalWrite(52, HIGH);

      SerialBT.print("SMPL_PRD = ");
      SerialBT.println(zgyro, HEX);

      attachInterrupt(3, availableIMUData, RISING);
    }

    void loop() {

    if (fDataIMUtoRead) {

    SerialBT.print("Loop... ");

    // Read values (standard mode)
    pauseBetweenTransfers = 100;
    digitalWrite(52, LOW); // Doesn't seem to be necessary

            SPI.transfer16(52, 0x0400, SPI_CONTINUE); delayMicroseconds(pauseBetweenTransfers);
    xgyro  = SPI.transfer16(52, 0x0600, SPI_CONTINUE); delayMicroseconds(pauseBetweenTransfers);
    ygyro  = SPI.transfer16(52, 0x0800, SPI_CONTINUE); delayMicroseconds(pauseBetweenTransfers);
    zgyro  = SPI.transfer16(52, 0x0A00, SPI_CONTINUE); delayMicroseconds(pauseBetweenTransfers);
    xacc   = SPI.transfer16(52, 0x0C00, SPI_CONTINUE); delayMicroseconds(pauseBetweenTransfers);
    yacc   = SPI.transfer16(52, 0x0E00, SPI_CONTINUE); delayMicroseconds(pauseBetweenTransfers);
    zacc   = SPI.transfer16(52, 0x0000, SPI_CONTINUE);

    digitalWrite(SS, HIGH);

    /*
    // Read values (burst mode)
    pauseBetweenTransfers = 5;
    digitalWrite(52, LOW);    // Doesn't seem to be necessary

             SPI.transfer16(52, 0x3E00);    delayMicroseconds(pauseBetweenTransfers);  // Request data burst
    supply = SPI.transfer16(52, 0x0000, SPI_CONTINUE);  delayMicroseconds(pauseBetweenTransfers);
    xgyro  = SPI.transfer16(52, 0x0000, SPI_CONTINUE);  delayMicroseconds(pauseBetweenTransfers);
    ygyro  = SPI.transfer16(52, 0x0000, SPI_CONTINUE);  delayMicroseconds(pauseBetweenTransfers);
    zgyro  = SPI.transfer16(52, 0x0000, SPI_CONTINUE);  delayMicroseconds(pauseBetweenTransfers);
    xacc   = SPI.transfer16(52, 0x0000, SPI_CONTINUE);  delayMicroseconds(pauseBetweenTransfers);
    yacc   = SPI.transfer16(52, 0x0000, SPI_CONTINUE);  delayMicroseconds(pauseBetweenTransfers);
    zacc   = SPI.transfer16(52, 0x0000, SPI_CONTINUE);  delayMicroseconds(pauseBetweenTransfers);
    xtemp  = SPI.transfer16(52, 0x0000, SPI_CONTINUE);  delayMicroseconds(pauseBetweenTransfers);
    ytemp  = SPI.transfer16(52, 0x0000, SPI_CONTINUE);  delayMicroseconds(pauseBetweenTransfers);
    ztemp  = SPI.transfer16(52, 0x0000);

    digitalWrite(52, HIGH);
    */

    SerialBT.println(zgyro, DEC); // Print the reading

    fDataIMUtoRead = 0; // Reser the "there is new data"-flag

    }
  }

void availableIMUData() {
  fDataIMUtoRead = 1; // Set the "there is new data"-flag
}

The standard way to communicate seems to work without any problem, provided that I set the right delays after each transfer16 command. But I'm not able to make the Arduino read the data in burst mode (commented in the code above).

So does anybody have any ideas on how to make the Arduino retrieve the readings in this burst mode? I understand this is a tricky unless you have (had) access to the same hardware, but any suggestion will be welcome.

Thanks a lot.

  [1]: https://www.analog.com/en/products/adis16364.html#product-documentation
  [2]: https://i.stack.imgur.com/v5CBQ.png
  [3]: https://i.stack.imgur.com/Fluov.png

body:
First of all, this may not related to your question, but you are using old SPI methods `setClockDivider()`, `setDataMode()`, and `setBitOrder()` that has been deprecated since 2014. It is recommend to use use transactional SPI APIs which I have some explanation [here](https://arduino.stackexchange.com/a/79760/40646).

>Why I actually need those delays?

If you read page 6 of [ADIS16364 datasheet](https://www.analog.com/media/en/technical-documentation/data-sheets/ADIS16364.pdf), there is a tSTALL time between each data transmission that could be as long as 75uS (when operating on Low Power mode), this value can be much lower if you operate on Normal or Bust mode.

> why this combination of delays with the 200 clock divider?

The clock divide set the clock used for the SPI SCLK rate, for Due a clock divide of 200 means 84,000,000 / 200 = 420,000Hz, Why this rate? again, you have to look into datasheet, on page 6 table 2, max fsck is 2MHz for Normal mode, and 1MHz for Bust mode, and only 300kHz at Low Power mode.

>Shouldn't this be done automatically by the SPI library?

This is a wrong perception, SPI library do nothing than handling the communication. All the timing requirements are component/chip specific, and therefore if you want to communicate with the chip at SPI communication level, you will have to deal with all the timing requirements yourself. Most of the people in the Arduino community get used of using some pre-written library which was written by someone who care to read the datasheet and provide high level abstract API so that users don't need to deal with all the timing.

>Any ideas on how to make the Arduino retrieve the readings in this burst mode?

**Update**

<s>As suggested by the datasheet, "To start a burst read sequence, **set DIN = 0x3E00**", what this means is that you need to **WRITE** into the register 0x3E00 first to setup the burst mode. Fig 11. of the datasheet indicate that a WRITE operation would have a set most significant bit to 1, so you will need to send `0x3E00 | 0x8000` or `0xAE00` for writing into register `0x3E00`. What you did is basically reading form `0x3E00`, not writing into `0x3E00`.</s>

**I re-read the datasheet and you are right, it should be okay to just send out `0x3E00`. I never use an Arduino Due before, but I realised that the SPI.transfer16() might send out the `0x00` first instead of `0x3E`. I modified the code to send out two bytes `0x3E` and `0x00` separately using `SPI.transfer()`**

I don't have the IMU, but I think the follow code should works for bust mode:

```
SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));    //initialises SPI clock speed, mode and bit order
digitalWrite(SS, LOW);              // adjust this as per your chip select pin
SPI.transfer(0x3E);
SPI.transfer(0x00);
delayMicroseconds(1);               //bust mode only 1uS required as per datasheet
xgyro_out = SPI.transfer16(0x0000);
delayMicroseconds(1);
ygyro_out = SPI.transfer16(0x0000);
delayMicroseconds(1);
zgyro_out = SPI.transfer16(0x0000);
delayMicroseconds(1);
xaccl_out = SPI.transfer16(0x0000);
delayMicroseconds(1);
yaccl_out = SPI.transfer16(0x0000);
delayMicroseconds(1);
zaccl_out = SPI.transfer16(0x0000);
delayMicroseconds(1);
data16    = SPI.transfer16(0x0000);
delayMicroseconds(1);
data16    = SPI.transfer16(0x0000);
delayMicroseconds(1);
data16    = SPI.transfer16(0x0000);
delayMicroseconds(1);
data16    = SPI.transfer16(0x0000);
delayMicroseconds(1);
digitalWrite(SS, HIGH);   // deselect slave
SPI.endTransaction();


message:
Water level switches / reed switches and Arduino Uno

How could I estimate the max number of switches that I could connect to an Arduino Uno?

I am questioning if Arduino has enough power to simultaneously operate an X number of switches with no issues.

I am using an external power adapter of 12 volt/2 amps (barrel).

Here is the hardware: https://m.hellasdigital.gr/el/products/tank-pool-water-level-liquid-sensor-float-switch

body:
thank you a lot about your input it was very useful.
My source of issues was a faulty sensor. After I changed it things are smooth now.
I separated the power cables from the signal as well that is super important.

Thank you a lot about the valuable input!


message:
How to connect SIM7100A to Arduino?

I've been searching for how to connect a SIM7100A module to an Arduino (Uno or Mega), but I haven't been able to find any posts anywhere, nor videos nor any kind of documentation that shows how to do it. Does anyone here know how to connect it so I can send simple AT commands to the module from the Arduino? (I just want to make GET requests and get GPS coordinates)
[![enter image description here][1]][1]

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/PMmMW.jpg
  [2]: https://i.stack.imgur.com/AP9sx.jpg

body:
Got it to work, in part thanks to the documentation that @Juraj posted.
My pinout is the following, in case anyone needs it:

SIM7100A -> Arduino Mega

SUPPLY -> 5V (the SIM7100A's SUPPLY pin powers the actual board, it's different from the VDD pin which is only for the Serial communication)

GND (both lower & upper) -> GND

VDD -> 3.3V

TXD -> RXD2

RXD -> voltage divider (5V to 3.3V) -> TXD2

Once the module is powered (the PWR LED is on), you gotta press the module's reset button for about 3 seconds and then wait for the NET and STA LEDs to turn on, then you can start sending AT commands to it.

I don't know if this will be the case for everyone, but for me, the serial communication through the SIM's USB debug port is with 9600 bauds, but the communication through the TXD and RXD pins is with 115200 bauds.


message:
how do i make stepper stop if both sensors are LOW ? im using a adafruit l293d motor shield

I've tried this code below but it doesn't stop it just rapidly switch direction that it looks like it's trembling I think because it always reads the void startF/R thats why it's trembling .

I need help on how to completely stop the stepper if it reads both sensor LOW

    if (sensLval== LOW || sensRval == LOW){
         steppStop();
    }

this is my void loop code below

        void startF()
      {
        motor1.step(10, FORWARD,SINGLE);

      }

        void startR()
      {
        motor1.step(10, BACKWARD,SINGLE);

      }

        void steppStop(){
      motor1.step(0, BACKWARD, SINGLE);

     motor1.step(0, FORWARD, SINGLE);
    }

        void loop() {
      sensRval=digitalRead(sensR);

    sensLval=digitalRead(sensL);

      if (sensLval == LOW)

    {
        startF();
      }

    if (sensLval== LOW && sensRval == LOW)

    {
         steppStop();
      }

      if (sensRval == LOW)

    {
        startR();
      }

    }

body:
Isolate your conditions.

You currently check for:

* *Both* sensors LOW at the same time **and**
* *Either* sensor LOW on its own

If *both* are low—don't check for *either* being LOW (which triggers `startX`.)

```cpp
if (sensLval == LOW && sensRval == LOW) {
    steppStop();
} else if (sensLval == LOW) {
    startF();
} else if (sensRval == LOW) {
    startR();
}
```

There may be other considerations as well, but this is enough to get past that issue.

---

Unrelated, but consistent indentation goes a long way towards code readability and helping others be able to reason about code in general. When posting code it's a good idea to format your code as code, [described here](https://arduino.stackexchange.com/editing-help) and when you are editing the question.


message:
Simple GET request is failing silently

I'm trying to make a simple GET request to a server (which has a static IP but does not have a name). I'm using [EtherCard][1] library and a cheap [ENC28J60 Ethernet Module][2]. The basic configurations are OK (I can get DHCP assignment and DNS lookup), but when I try to make a simple GET request with the `browseUrl` method, nothing happens. I've tried to call the page from the browser and everything works fine, so it's not a server issue. The code is the following:

    #include <EtherCard.h>

    // ethernet interface mac address, must be unique on the LAN
    byte mymac[] = { 0x54, 0x55, 0x58, 0x10, 0x00, 0x24 };

    const char website[] PROGMEM = "http://10.10.10.10"; // my server
    const char dnsLook[] PROGMEM = "google.com";

    byte Ethernet::buffer[700];
    uint32_t timer;
    Stash stash;

    // called when the client request is complete
    static void requestCallback (byte status, word off, word len) {
      Serial.print(">>>");
      Serial.print(status);
      Serial.print("-");
      Serial.print(status);
      Serial.print("-");
      Serial.print(status);
      Serial.println("<<<");
    }

    void setup () {

      Serial.begin(9600);
      delay (10000);
      int res = ether.begin(sizeof Ethernet::buffer, mymac, 8);

      if (res == 0)
        Serial.println( "Cannot access ethernet interface");

      const static uint8_t ip[] = {192,168,1,117};
      const static uint8_t gw[] = {192,168,1,1};
      const static uint8_t dns[] = {8,8,8,8};

      if (!ether.staticSetup(ip, gw, dns))
      {
          Serial.println("Cannot set static parameters");
      }

      // manually set netmask
      ether.netmask[0] = 255;
      ether.netmask[1] = 255;
      ether.netmask[2] = 255;
      ether.netmask[3] = 0;

      // dns lookup
      if (!ether.dnsLookup(dnsLook))
        Serial.println("DNS failed");
    }

    void loop () {
      ether.packetLoop(ether.packetReceive());
      if (millis() > timer) {
        timer = millis() + 10000;
        ether.browseUrl(PSTR("/page.php?"), "var=value", website, requestCallback);
      }
    }

  [1]: https://github.com/njh/ethercard
  [2]: https://www.amazon.it/Hiletgo-ENC28J60-Ethernet-modulo-Arduino-STM32/dp/B00WX1NRO0/

body:
I made it by using `EthernetENC` library, as suggested by @Juraj.
To install the library, simply use the library manager and search for EthernetENC.
For those in need, below is a working code

    #include <SPI.h>
    #include <EthernetENC.h>

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };  // ethernet module MAC address
    IPAddress server(10,10,10,10);                        // server IP address, without DNS
    //char server[] = "www.site.com";                     // if your server has a DNS name, use this variable for connection

    // static configuration variables
    IPAddress staticIp(192, 168, 1, 217);
    IPAddress staticDnsServer(8, 8, 8, 8);

    EthernetClient client;                                // ethernet client object

    void setup() {
      // configure CS pin
      Ethernet.init(8);

      // begin serial connection
      Serial.begin(9600);

      // wait some seconds to let the module start
      delay(5000);

      // initialize ethernet module with static configuration
      Ethernet.begin(mac, staticIp, staticDnsServer);

      // wait to let the module properly initialize
      delay(1000);

      // connection to the server
      Serial.print("Connecting to: ");
      Serial.print(server);
      Serial.println("...");

      // notify successful connection
      if (client.connect(server, 80)) {

        Serial.print("Connected to ");
        Serial.println(client.remoteIP());

        // simple GET request
        client.println("GET /page.php?var=test HTTP/1.1");
        client.println("Host: 10.10.10.10");
        client.println("User-Agent: Arduino/1.0");
        client.println("Connection: close");
        client.println();

      } else {
        // connection failed notifiation
        Serial.println("Connection failed");
      }
    }

    void loop() {

      // if I got a response from the server, read and print to serial
      int len = client.available();
      if (len > 0) {
        byte buffer[80];
        if (len > 80) len = 80;
        client.read(buffer, len);
        Serial.write(buffer, len);
      }

      // disconnection
      if (!client.connected()) {

        Serial.println();
        Serial.println("Disconnected");
        client.stop();

        // stop execution
        while (true) {
          delay(1);
        }
      }
    }

at [this link][1], you can see how to properly connect this module to Arduino UNO.

  [1]: https://create.arduino.cc/projecthub/Sourcery/how-to-connect-the-enc28j60-to-an-arduino-efd0dd


message:
STM32f4 Warning: The core is locked up

I built a custom board that uses a STM32F411CEU6. My problem is that tried to upload a simple blink sketch (I'm using Arduino IDE with STM32 libraries) and I get the error:

    ST-LINK SN  : 57FF72067166535645342467
    ST-LINK FW  : V2J37S7
    Board       : --
    Voltage     : 3.23V
    SWD freq    : 4000 KHz
    Connect mode: Under Reset

    Reset mode  : Hardware reset
    Device ID   : 0x431
    Revision ID : Rev A

    Device name : STM32F411xC/E
    Flash size  : 512 KBytes (default)
    Device type : MCU
    Device CPU  : Cortex-M4

    Memory Programming ...
    Opening and parsing file: Blink.ino.bin
      File          : Blink.ino.bin
      Size          : 11256 Bytes
      Address       : 0x08000000

    Erasing memory corresponding to segment 0:
    Erasing internal memory sector 0
    Error: failed to erase memory

    Error: failed to erase memory

    RUNNING Program ...
      Address:      : 0x8000000
    Warning: The core is locked up
    Start operation achieved successfully
    the selected serial port Start operation achieved successfully
     does not exist or your board is not connected

I'm using an ST-LINK V2 USB pen that works fine. I have a Black Pill with the same STM32 to use as a control and everything works ok.

Also, when I try to check the custom board with STM32CudeProgrammer, I get the error:

      22:16:27 :   Size          : 1024 Bytes
      22:16:27 :   Address       : 0x8000000
      22:16:27 : Read progress:
      22:16:27 : Error: Data read failed

  [1]: https://www.amazon.de/gp/product/B07YX83NSL/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1

body:
The solution:

 1. Open STM32CubeProgramer and click connect
 2. Click Option Bytes (OB) located in the left bar
 3. Select Read Out Protection and choose AA option
 4. Then select PCROP and uncheck the box
 5. Click apply


message:
How fast does the Arduino execute code?

I am using the Arduino Nano every. Take this example where I am measuring two things A and B.

```c++
Loop{// this loop runs once every second
    //Read A,B
    //Change something using analogueWrite which would effect A,B values
    //Read A,B
}
```

Would the `analogueWrite` values have changed fast enough such that the third line would read the new and changed A,B values?

body:
The Arduino Nano Every does not have analog outputs. The function
`analogWrite()` uses PWM as an ersatz of analog output. As soon as the
function returns, you know that the timer registers controlling the PWM
feature have been set to the proper duty cycle. The timer, however, will
complete the current PWM cycle using the previous settings. Only when
this cycle is over will it use the updated settings for the next one.
Completing the current cycle can take up to 2 ms.

Now, I wonder how the PWM cycle can have any effect on what you are
measuring. If you expect to measure something that depends on the
apparent “analog” value you are outputting, this can only work if your
circuit contains (or behaves like) a low-pass filter. In order to
convert the PWM to an analog value, the filter's time constant has to be
significantly longer than the PWM period. This in turn will cause a
corresponding lag, so your readings will take roughly one filter's time
constant to catch up with the value you are outputting.

Note that all this has absolutely nothing to do with how fast the
Arduino executes code.


message:
ESP-01 OTA Error uploading

Im trying to do OTA upload from Arduino IDE.

Uploaded BasicOTA to ESP-01 with flash size set to (FS:2mb, OTA 1019kb).
ESP-01 connects and shows up in Port selection, but when trying to upload I get

    Uploading.................................................

    14:40:35 [ERROR]: Error Uploading

Thats the only output I get.
Anyone had similar issue?

Thx

body:
The ESP-01 comes in two variants: blue, with 512KiB flash, and black, with 1MiB flash.

You have chosen an arrangement that needs 4MiB flash.  It won't fit.

Choose a suitable flash size for your board.


message:
Accessing Physical Pins in Arduino Due from Arduino IDE

It is possible to access the Physical Pin 93, Pin PC11 on ATSAM3X8E in [Arduino Due][1]  from the Arduino IDE?

I am programming a Barebone ATSAM3X8E, and it do not seems to be allocated by [Arduino Due][2] nor by ATSAM3X8E for any other purpose than the PC Port.

[![enter image description here][3]][3]
[![enter image description here][4]][4]
[![enter image description here][5]][5]

  [1]: https://www.arduino.cc/en/Hacking/PinMappingSAM3X
  [2]: https://forum.arduino.cc/t/due-pinout-diagram/129258
  [3]: https://i.stack.imgur.com/mfC61.png
  [4]: https://i.stack.imgur.com/rJh43.png
  [5]: https://i.stack.imgur.com/ZIuZU.png

body:
# Modifying/Making a variant

If you wanted to do it in an Arduino-like way it would require editing the Arduino Due [variant.cpp][1] or copying the making your own variant, say from a copy of the Due, and editing the `extern const PinDescription g_APinDescription[]` array to include an entry that matches for PC11.

## Example changes

As an experiment I made the following changes to files in the `packages/arduino/hardware/sam/1.6.12/variants/arduino_due_x` under the arduino15 directory.

In variant.cpp, an entry for in the `g_APinDescription` array is insert an index number 79, between the existing two entries (shown for context):

```c
  { PIOB, PIO_PB23B_SPI0_NPCS3,ID_PIOB,PIO_PERIPH_B,PIO_DEFAULT, PIN_ATTR_DIGITAL,                  NO_ADC, NO_ADC, NOT_ON_PWM,  NOT_ON_TIMER }, // NPCS3
  // Addition line here VVVV (this is the line for PC12, copied with PIO_PC12 changed to PIO_PC11
  { PIOC, PIO_PC11,          ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT, PIN_ATTR_DIGITAL,                  NO_ADC, NO_ADC, NOT_ON_PWM,  NOT_ON_TIMER }, //
  // 79 .. 84 - "All pins" masks

  // 79 - TWI0 all pins
  { PIOA, PIO_PA17A_TWD0|PIO_PA18A_TWCK0, ID_PIOA, PIO_PERIPH_A, PIO_DEFAULT, (PIN_ATTR_DIGITAL|PIN_ATTR_COMBO), NO_ADC, NO_ADC, NOT_ON_PWM, NOT_ON_TIMER },
```

This is a copy of the entry for PC12, with `PIO_PC12` changed to `PIO_PC11`.

In variant.h, `PINS_COUNT` changes to `80u`, because we've inserted  the pin:

```c
#define PINS_COUNT           (80u)
```

and later in the file the pin number associate with CAN are bumped up by one also because they're all numbered after the point of insertion:

```c
/*
 * Complementary CAN pins
 */
static const uint8_t CAN1RX = 89;
static const uint8_t CAN1TX = 90;

// CAN0
#define PINS_CAN0            (91u)
// CAN1
#define PINS_CAN1            (92u)
```

I programmed a sketch the blinks PC11 by way of `digitalWrite(79, state);` and carefully placed a logic probe on the the unrouted pin on the Due board, and it "blinks" just fine.  That's as far as I've tested.

# Direct control

Alternately you could control the pin in your code manually, doing what `digitalWrite` or `digitalRead` would normally do.  In other words, you could read the description of something like digitalWrite [here][2] and substitute all of the references that it would have gotten from `g_APinDescription` with hard-coded values.

  [1]: https://github.com/arduino/ArduinoCore-sam/blob/c43d4be/variants/arduino_due_x/variant.cpp
  [2]: https://github.com/arduino/ArduinoCore-sam/blob/c43d4be431bd5673f6bb26f83411bbd8f9ef89ef/cores/arduino/wiring_digital.c#L91


message:
I have a problem with this code where the buzzer won't work

const int buzzerPin = 7;
    const int flamePin = 10;
    int Flame = HIGH;
    int redled = 8;
    void setup()
    {
      pinMode(buzzerPin, OUTPUT);
      pinMode(redled, OUTPUT);

      pinMode(flamePin, INPUT);
      Serial.begin(12000);
    }

    void loop()
    {
      Flame = digitalRead(flamePin);
      if (Flame== HIGH)
      {
        digitalWrite(redled, HIGH);
      int i=0;
      do {
        digitalWrite(buzzerPin, HIGH);
        tone(buzzerPin,450);
        delay(200);
        noTone(buzzerPin);
        delay(200);

      }while (i<2);
      }
      else
      {
        digitalWrite(buzzerPin, LOW);
        digitalWrite(redled, LOW);
      }
    }

body:
**Here are the modifications I have done**

* I changed the Piezo Buzzer frequency to 3000 Hz
The green Button simulates the Flame signal
* Change the RED LED from pin 8 to Pin 13 so that I don't have to use an external LED

**Here is the simulation output**

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

Observe the onboard LED going HIGH and the buzzer going off. You can find the project link [**here**][2] where you can test with different Piezo buzzer frequency.

**Code**

    const int buzzerPin = 7;
    const int flamePin = 10;
    int Flame = HIGH;
    int redled = 13;
    void setup()
    {
      pinMode(buzzerPin, OUTPUT);
      pinMode(redled, OUTPUT);

      pinMode(flamePin, INPUT);
      Serial.begin(12000);
    }

    void loop()
    {
      Flame = digitalRead(flamePin);
      if (Flame== HIGH)
      {
        digitalWrite(redled, HIGH);
      int i=0;
      do {
        digitalWrite(buzzerPin, HIGH);
        tone(buzzerPin,3000);
        delay(200);
        noTone(buzzerPin);
        delay(200);

      }while (i<2);
      }
      else
      {
        digitalWrite(buzzerPin, LOW);
        digitalWrite(redled, LOW);
      }
    }

*Disclaimer: I am not the Wokwi creator but I support it since it is open source and free to use*

  [1]: https://i.stack.imgur.com/pTzPR.gif
  [2]: https://wokwi.com/arduino/projects/300993767428588045


message:
Digispark Rev.3 Kickstarter ATTiny85 using all 6 pins

i have some trouble to use i2c and the other pins at the same time.

im tring to control the attiny over i2c with a arduino and the attiny should control a 28byj-48 stepmotor.

i started to setup the i2c connection pin 0 and pin 2 is use for that. it is working fine but then i connected the stepmotor driver on pin 1,3,4,5 after connecting the 5 pin i lose my i2c connection.

here is the code from the attiny, nothing special

```
#include <TinyWireS.h>                // wrapper class for I2C slave routines

#define I2C_SLAVE_ADDR  0x29            // i2c slave address (38)
#define A 1
#define B 3
#define C 4
#define D 5
#define NUMBER_OF_STEPS_PER_REV 512

void setup(){
  pinMode(1,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  TinyWireS.begin(I2C_SLAVE_ADDR);      // init I2C Slave mode
}

void loop(){
  byte byteRcvd = 0;
  if (TinyWireS.available()){           // got I2C input!
    byteRcvd = TinyWireS.receive();     // get the byte from master
    //Blink(byteRcvd);           // master must wait for this to finish before calling Wire.requestFrom
    //byteRcvd += 10;                                                    // add 10 to what's received
    //TinyWireS.send(byteRcvd);           // send it back to master

    //             Blink(1);                  // show we transmitted
  }
}
```

body:
There is no such Digispark board as the Rev 3. There was going to be, but there was a mistake, so they went straight from Rev 2 to Rev 4. However unscrupulous Chinese counterfeiters are making "Rev 3" boards.

So... your mileage may vary since the components used on there could be of *any* dubious quality.

But to your problem: P5 is also the RESET pin.  If the fuses on that chip are set correctly then it can be used as an IO port. But being a counterfeit, who knows what they set the fuses to?

But if you *do* change the fuses you will have to rely on the power-on reset (plugging it in) to trigger uploads.


body:
As an addition to [Majenko][1]'s answer I can report having used many of the "Rev.3" counterfeits, every single one came with *chip default fuses* thereby **reset enabled**.

You can set the [RSTDISBL][2] fuse with your [Arduino][3], plus update the [micronucleus][4] bootloader in the process (freeing 0.4k).

Keep in mind setting this fuse will **disable ISP programming**, so you will need a working bootloader to reprogram the chip unless you revert it via [HV programming][5].

  [1]: https://arduino.stackexchange.com/users/4143/majenko
  [2]: https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf#G1.2073549
  [3]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/ArduinoISP
  [4]: https://github.com/micronucleus/micronucleus
  [5]: https://www.instructables.com/How-to-unlock-Digispark-ATtiny85-and-convert-it-to/


message:
How can I pause serial transfer and then un-pause it?

So I am running a USB (UART) connection from my Arduino UNO (using the serialtransfer.h library) to my pc (using the pyserial transfer library).
This how the ***INTENDED*** cycle of code goes:
I receive the list_ packet and save it to a list on the Arduino . Then the elements in the list are checked and used to control parameters of motor a using GPIO pins. Finally a return message is sent to acknowledge each transfer.

I was hoping to make the return message from Arduino as sort of a flag ; whether to wait or move onto the next transfer, this is on the python side of things.

***However this is not the case as the sending of packets from Arduino is almost instantaneous even with delay functions and before the Arduino can process the information the transfer is done.***

***1)Why doesn't delay() work ?***

***2) Why isn't code sequential ?***

***This is the Arduino side of things***
```
#include "SerialTransfer.h"

SerialTransfer myTransfer;
int motor1 = 13;
int motor2 = 10;

int obj_cordinates[9];
char reply [16] = {"Packet Recieved"};
void setup()
{
  Serial.begin(115200);
  pinMode(motor1,OUTPUT);
  pinMode(motor2,OUTPUT);

  myTransfer.begin(Serial);
}

void loop()
{
  if(myTransfer.available())
  {
    // use this variable to keep track of how many
    // bytes we've processed from the receive buffer
    uint16_t recSize = 0;
    uint16_t sendSize = 0;

    recSize = myTransfer.rxObj(obj_cordinates, recSize);
    sendSize = myTransfer.txObj(reply, sendSize);

     if( obj_cordinates[4] == 15)
    {
      digitalWrite(motor1, HIGH);
      digitalWrite(motor2, LOW);

      delay(5000);

      digitalWrite(motor1, LOW);
      digitalWrite(motor2, HIGH);
      delay(5000);
    }

    myTransfer.sendData(sendSize);
  }

}
```

***The python side of things***
```
import time
from pySerialTransfer import pySerialTransfer as txfer

def Ser_tran_list (list_):

    try:
        link = txfer.SerialTransfer('COM6')
        link.open()
        time.sleep(2) # allow some time for the Arduino to completely reset

        to_transfer = True
        while to_transfer:
            send_size = 0

            # Send a list

            list_size = link.tx_obj(list_)
            send_size += list_size

            # send a character
            str_ = 'Sending data Packet'
            str_size = link.tx_obj(str_, send_size) - send_size
            send_size += str_size
            link.send(send_size)

            while not link.available():
                if link.status < 0:
                    if link.status == txfer.CRC_ERROR:
                        print('ERROR: CRC_ERROR')
                    elif link.status == txfer.PAYLOAD_ERROR:
                        print('ERROR: PAYLOAD_ERROR')
                    elif link.status == txfer.STOP_BYTE_ERROR:
                        print('ERROR: STOP_BYTE_ERROR')
                    else:
                        print('ERROR: {}'.format(link.status))

            # Parse response string

            rec_str_   = link.rx_obj(obj_type=type(str_),
                                     obj_byte_size=16,
                                     start_pos=0)

            # Display the received data

            print('SENT: {} {}'.format(list_,str_))
            print('Recieved: {}'.format(rec_str_))

            to_transfer = False

```

body: The `delay()` function uses the milliseconds interrupt. Inside an interrupt handler, all other interrupts are suspended so the `millis()` counter doesn't count and `delay()` never ends. `delayMicroseconds()` will work in the interrupt routine because it just sits in a busy loop. Rewrite the code to eliminate the delay function, you can use millis if you want. This is telling you while in the delay function just about everything stops until it is finished.


message:
Recover .ino file from tmp files?

Is it possible to recover an .ino file/sketch in/for Arduino? I really need my file back, but ones i uploaded it to my device it vanished from the sketch folder, nor can I find it in the build folder; however, a ton of TMP files are left. Is it possible to use those to recover my .ino file?
They're named something like filename.ino1238437381212.TMP

body: Well, stupidly enough, the missing code was inside of the TMP files... in all of them...


message:
Fader OOP Problem

This code works and it can fade three LEDs without any problem, obviously you can even add more of them : )

    // Pins Definition
    const int button1 = 13;
    const int button2 = 12;
    const int button3 = 11;
    const int redled = 2;
    const int greenled = 3;
    const int blueled = 4;

    // Timing States
    unsigned long ElapsedLoopTime;
    unsigned long Now;

    class LED
    {
        // Parameters
        unsigned long ParamStartFeed = 300;
        unsigned long ParamDebounce = 50;
        float ParamMinLux = 25.5;
        float ParamMaxLux = 255.0;
        float ParamFeedRamp;

        // Pins
        int led;
        int buttonpin;

        // Status Variables
        bool INDownFront;
        bool LastINValue;
        bool LedStatus;
        float Lux = 127.0;
        bool Direction = true;
        unsigned long LastPressed;
        bool INStatus;
        bool Pressed;
        float Delta;

      public:

        void Initialize(int pin, int ledpin)
        {
          led = ledpin;
          buttonpin = pin;
          pinMode(led, OUTPUT);
          pinMode(buttonpin, INPUT);
          LastINValue = digitalRead(buttonpin);
          LastPressed = millis();
          ElapsedLoopTime = millis();
        }

        void Execute(float ParamFeedRamp)
        {
          INStatus = digitalRead(buttonpin);

          INDownFront = LastINValue && !INStatus;
          Pressed = ((Now - LastPressed) > ParamStartFeed) && INStatus;

          if (INDownFront && (Now - LastPressed  < ParamStartFeed) && (Now - LastPressed  > ParamDebounce))
          {
            LedStatus = !LedStatus;
          }

          if (!INStatus) LastPressed = Now;
          LastINValue = INStatus;

          if (Pressed && LedStatus)
          {
            Delta = (ParamMaxLux - ParamMinLux) * ElapsedLoopTime / ParamFeedRamp;

            if (Direction)
            {
              Lux += Delta;
            }
            else
            {
              Lux -= Delta;
            }

            if  (Lux > 255) {
              Lux = 255;
              Direction = false;
            }
            if  (Lux < 25) {
              Lux = 25;
              Direction = true;
            }

          }
          analogWrite(led, Lux * LedStatus);
        }
    };

    LED ledblue;
    LED ledgreen;
    LED ledred;

    void setup()
    {
      Serial.begin(115200);
      ledred.Initialize(button3, redled);
      ledgreen.Initialize(button2, greenled);
      ledblue.Initialize(button1, blueled);
    }

    void loop()
    {
      Now = millis();
      ledred.Execute(3000); // 3000ms
      ledgreen.Execute(3000); // 3000ms
      ledblue.Execute(3000); // 3000ms
      ElapsedLoopTime = millis() - Now;
    }

body:
I don't really know about the

    // Pins
    byte led;
    byte buttonpin;

but maybe you can try

    // Pins
    int led;
    int buttonpin;


message:
Arduino (line follower + ultrasonic sensor + servomotor)

I am making a line follower car that follows the line when push button is pressed. And by using ultrasonic sensor I want the car to stop when object ahead distance is closer than 100 and then make servo motor turn to 180 degrees.

Used:

* Arduino UNO
* 2 DC motor
* cytron maker line sensor
* 1 servo motor
* 1 ultrasonic sensor
* 1 push button.

Got stuck coding, I would like some help please.

```c++
int E1 = 4;
int M1 = 5; // Right
int M2 = 6; // Left
int E2 = 7;
int trigPin = 4;
int echoPin = 5;

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

  pinMode(E1, OUTPUT);
  pinMode(M1, OUTPUT);
  pinMode(E2, OUTPUT);
  pinMode(M2, OUTPUT);

  digitalWrite(E1, HIGH);
  digitalWrite(E2, HIGH);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  float duration, distance;

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = ((float)(340 * duration) / 1000) / 2;

  Serial.print("\nDIstance:");
  Serial.print(distance);
  Serial.println("mm\n");
  delay(200);

  int D1 = digitalRead(8);
  int D2 = digitalRead(9);
  int D3 = digitalRead(10);
  int D4 = digitalRead(11);
  int D5 = digitalRead(12);

  if (D1 == 0 && D2 == 0 && D3 == 1 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 100);
    analogWrite(M2, 100);
  }
  else if (D1 == 0 && D2 == 1 && D3 == 1 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 80);
    analogWrite(M2, 100);
  }
  else if (D1 == 0 && D2 == 1 && D3 == 0 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 60);
    analogWrite(M2, 100);
  }
  else if (D1 == 1 && D2 == 1 && D3 == 0 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 30);
    analogWrite(M2, 100);
  }
  else if (D1 == 1 && D2 == 0 && D3 == 0 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 0);
    analogWrite(M2, 100);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 1 && D4 == 1 && D5 == 0) {
    analogWrite(M1, 100);
    analogWrite(M2, 80);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 0 && D4 == 1 && D5 == 0) {
    analogWrite(M1, 100);
    analogWrite(M2, 60);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 0 && D4 == 1 && D5 == 1) {
    analogWrite(M1, 100);
    analogWrite(M2, 30);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 0 && D4 == 0 && D5 == 1) {
    analogWrite(M1, 100);
    analogWrite(M2, 0);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 0 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 0);
    analogWrite(M2, 0);
  }
  else if (D1 == 1 && D2 == 1 && D3 == 1 && D4 == 1 && D5 == 1) {
    analogWrite(M1, 00);
    analogWrite(M2, 00);
  }
  else {
  }
}
```

body:
```c++
int M1 = 5; // Right
...
int echoPin = 5;
```

You appear to be trying to use one of your motors on the same pin as your return signal from the ultrasonic range finder.  When `analogWrite(M1, whatever)`, the internals of `analogWrite` will [set the pin to output][1], overriding your own `pinMode(echoPin, INPUT)` in `setup()`.

Later when you `pulseIn(echoPin, HIGH)`, you're just seeing whatever `analogWrite` is doing with it.  If you're not touching any buttons, your code is executing `analogWrite(M1, 0);`, so no "distance".

For more fun:  If all of this is correct, if you hold down the buttons to execute `analogWrite(M1, 100)`, `pulseIn` should report a value of about (1.0/980) * 100/256 or 399.  The 980 being the frequency pin 5 uses on the UNO for [analogWrite][2].  This should cause your code to print something around 66.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/cores/arduino/wiring_analog.c#L111
  [2]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/


message:
Proper Micro SD card schematic

I am using a micro sd card shield with an arduino zero, and I am not sure I am using a proper circuit with it. This is the circuit I am using right now:

[![sd card circuit schematic][1]][1]
That is all it is there, just a capacitor for the power and a pullup resistor for the chipselect. The tags just go to the processor.

I have seen a lot of schematics out there with resistors in series to the processor, some times with pull up resistors, some times with pulldown resistors...

I'm not sure the pullup resistor I am using is a good idea, and I am unsure about the value.

To me something like this makes more sense:

[![enter image description here][2]][2]

Can someone teach me a proper circuit for this? what is best and why?

Right now I am not very happy with the performance of the micro SD card socket. That's why I want to improve it.

  [1]: https://i.stack.imgur.com/mRfRK.jpg
  [2]: https://i.stack.imgur.com/DVoKp.png

EDIT: Turns out I didnt really understand very well the second schematic, it was just voltage dividers to lower the 5v os arduino uno to 3V. But what about the pullup resistor of the MISO?

body:
As per the SD card specification:

> When an SD card is operating in SPI mode or 1-bit SD mode, the CMD and DATA (DAT0 - DAT3) lines of the SD bus must be pulled up by 10 kOhm resistors. Slaves should also have pull-ups on all above-mentioned lines (regardless of whether these lines are connected to the host) in order to prevent SD cards from entering a wrong state.

Basically you need to ensure that "everything is off" until the Arduino actively drives the SD card. Without them the SD card's inputs will be floating and doing anything they like until the Arduino starts communicating.

Resistors in-line with the signals are there really just to increase the impedance and prevent damage when hot-swapping a card.

If you have a 5V Arduino you will require logic level translation. This is a *separate* thing to the resistors. While resistors are OK for UART or simple IO logic level translation they are *not* suitable for use with an SD card. This is because the clock frequencies involved are too high and the resistors will corrupt the signal (through low pass filtering). Instead you require an active logic level translation system, such as a dual voltage, or TTL input, buffer, or active MOSFET level shifters.


body:
There's an excellent tutorial on Instructables I recommend one to read.
here's the link
https://www.instructables.com/Select-SD-Interface-for-ESP32/

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

  [1]: https://i.stack.imgur.com/xZrJh.png


body:
There are a couple of "do and don't" when designing an SPI interface.

**Do add pull-up resistors on SS or set SS HIGH for multiple-slave system**

SPI is a bus system, means that your device might not be the only one using the interface. When designing an SPI interface, you therefore has to consider the scenario where multiple SPI devices are used, and especially when some of the slaves are not coded by your system.

Without a pullup resistor, the SS line might be neither LOW nor HIGH, this might caused some of the devices on the bus to “hear” the communication on its MISO that was not intend for the device. This might explained why some of the Arduino shields or breakout boards with SPI works when used alone, but fail when used together with other SPI boards, causing by some of those boards lack of pullup resistor or the user didn't pull the SS lines in the system HIGH at the `setup()` before calling the `SPI.begin()`!

**Do ensure MISO can be tri-state in multiple-slave system**

Most SPI chips will be at tri-state on their MISO pin (but there are some chips out there requires extra external tri-state buffer chip) when their chip select signal is HIGH. Tri-stage means that it is neither HIGH nor LOW (i.e. floated) and effectively disconnect. However, A SPI device without tri-state MISO could caused potential problem on a SPI bus where multiple SPI devices are connected. If the MISO is unable to be at tri-state, it will be either HIGH or LOW, this will affect other devices connected on the same bus in receiving data.

With this in mind, it is not a good idea to add a pull-up resistor on MISO line.


message:
Anyone know why my pushbutton is always returning HIGH?

Been trying to figure this out for a couple hours, despite how ridiculously simple it should be. I have no idea why it's always returning 1, even when i'm pushing the button. Fritzing sketch:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/gq7E1.png

My code:

    #include <Servo.h>
    #define button 3

    Servo myservo1;
    Servo myservo2;
    Servo myservo3;

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

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

    }

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

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

      //checkerthing();

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

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

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

      }

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

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

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

    }

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

    }

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

    }

Basically, the point of this is to have the servo motors go off at specific intervals as given by the user in the serial monitor. The button exists so that the user can restart the timer at any point in the code. But the problem is, I can't even get it to register the button being pushed. It always returns "HIGH", which leads me to believe there's something wrong with the circuits. I've tried using some different methods, but no luck. Can anyone tell me what the issue here is?

Edit: ...I hadn't pushed the pushbutton all the way into the breadboard. I'm gonna go cry in the corner for a bit. And then get back to coding I guess lol. Thanks for the answers.

body: Hadn't pushed the button all the way in lol


message:
Dealing with USB Unplugging?

The following code, debugs SerialUSB Native Port, *plugged* to a PC, and *connected* through a Terminal Monitor (such as *Termite*, with any bps, 8N1, RTS/CTS).

At start, the ports seeks for communication, and you see fast blinks.

If **`SerialUSB`**, **Plugged** and **Connected**, communication happens, a.k.a. slow blinks.

But if USB is **Unplugged** after **`SerialUSB`**, even if you **Disconnect** it before, the code turn into an **`Halt`** state, a.k.a. no blinks.

If you **Plug** back the USB, it returns to **`!SerialUSB`**, so if you **Disconnect** (if it were connected) and **Connect** back the terminal, it recovers the **`SerialUSB`** state, not without a `reset()` line to react.
Seems the same happens for `Serial`.

**Any clue about why the Arduino goes into that `Halt` state after a USB disconnect?**

**How should we deal with that? How one should prevent this state?**

Most people asserts this is a power source problem. This happens *with* and *without* the 5V Barrel Power Source.

    // ARDUINO DUE BLINK LED
    void setup(){
      pinMode(13,OUTPUT);
      Serial.begin(115200);
      SerialUSB.begin(115200);
      while(!Serial){
        digitalWrite(13,HIGH);delay(500);
        digitalWrite(13,LOW);delay(500);
      }
      Serial.println("System Reset");
    }
    void loop(){
      int n=0;
      while(!SerialUSB){
        Serial.println("USB Unplugged or Terminal Disconnected");
        digitalWrite(13,HIGH);delay(50);
        digitalWrite(13,LOW);delay(450);
        n=n+1;
        if (n>=5){
          Serial.println("Resetting to Connect if Disconnected");
          digitalWrite(13,HIGH);delay(450);
          digitalWrite(13,LOW);delay(50);
          rstc_start_software_reset(RSTC);
        }
      }
      SerialUSB.println("USB Plugged and Terminal Connected");
      Serial.println("USB Plugged and Terminal Connected");
      digitalWrite(13,HIGH);delay(50);
      digitalWrite(13,LOW);delay(50);
    }

body: This is not possible to do because the protocol CDC/ACM don't send that type of information so you can't detect if the Arduino is connected or not, that's why it halts. (You could make a keep-alive function but I don't know if this is possible with what you're doing)


message:
Higher than 12V Arduino Uno

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

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

  [1]: https://www.robotshop.com/media/files/pdf/arduinomega2560datasheet.pdf


body:
You could use a step-down converter to lower the voltage and also stabilize it to 12V or even lower and you wouldn't have any problem even if you power supply isn't really stable and outputs higher voltage.

(Instead of buying one you can even build it, it isn't really hard to make one)


message:
Using External Power Supply Arduino Uno

I have an AA battery holder for 9V. Two wires come out of it, one for positive and another for negative. How can I wire it up to my Arduino Uno? It kind of looks like this.[![][1]][1]

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

body:
I would suggest a barrel jack, you know, ones on eBay. For instance, those 2.1 x 5.5mm barrel jack connectors. Just solder the positive and negative wires respectively with barrel jack. Here is a link: [eBay Barrel Jack][1]
Make sure the red or the positive goes with the red on the Barrel Jack and that the black or negative goes with the black of the Barrel Jack. Like in the image.[![This is what I mean by soldering the wires to the barrel jack.][2]][2]

  [1]: https://www.ebay.com/itm/253803093868?_trkparms=ispr=1&hash=item3b17d7df6c:g:pYMAAOSwGHxcz6-n&amdata=enc:AQAGAAACkPYe5NmHp%2B2JMhMi7yxGiTJkPrKr5t53CooMSQt2orsSg3Ye8yTWgOW7pmE1t838dpT7AD8sxbO0VOebe4CPmrZXmmDuPDQbE9XxV%2FUmz3za4AS5ntxim9hOFB2pETiXAThNaYYqnoMlalCssp2ACiM7XXERF9akKV%2F6Tq2qJdFDgLxur%2Fv4t%2Ba2pGI%2FHzRP3shGkNm2lN3jrtycgpR94QtVVMJ%2FHu1oKp8m3LtYYIzEqHmQjISkX%2BFgJ0exzhcoXEha0jgcKAiXNUfUQM0cIZBuihJCKqEQCvTvzCrjt2wQa7tlmU4AGgzYCq95nTn%2FS10%2Bf3hAqkeCqpd6TGCagQOkLqjRBHER6iU6mJAaKEqXUEtN4b3iEiVz9OfmhlpfPB%2F52U2rAxQliOYKxIPh9S8hZJtnKbLt%2FiuGHcCG%2B%2Fx3pgY9uZs6zVqsRoz%2BIhI0l9nqU2HpOuXUZ2HLcnwxoO%2FCuHq%2FeqGcIL3uSQ4D7PpAXEdBafbEDWeTMGTNWNDbTKVUtgueh4hjHHl2Lpcku879o2oC5wwIi%2FftrAGgdKHl5Yk9wK%2FqYU2eCbEAIZKKctbUln%2BE2GDw2ogZYLEuCTzoX1QLTY9LRWO04jLjv00wfzPjjiwwAXflc94l0TBQfLwL69V1kyAUJIzdu8YUC2QnCxGH1SAxG2mP6XIQk4aMYKQKgABjWJ0OCMEzQVt%2FQd7eTvMa7sDHt%2BKDKWeut9r6ZlVwkYGzOSONjk%2FAwalDqo2m4saH2cXBV4rRSQ%2FSpyLlzPeL11fvw72KSWqPFJOofdpmBz6uquwAuO0Sshh8YZgKSIuG9S17tD83X7exn80usxYzywvpuIWwCwdN8%2FfzY%2FvYwDEvRwQyy2iuIFLF|cksum:2538030938687aaa9e7bf0fe4519aef2c1b3df89dd93|ampid:PL_CLK|clp:2334524
  [2]: https://i.stack.imgur.com/i764b.jpg


message:
Can Arduino Due be programmed with both USB ports connected?

It seems, due *SAM-BA* (*SAM Boot Assistant*) inside ATSAM3X8E being listening to both *Native USB* and *UART USB* ports after a Reset for programming, allowing talking with *SAM-BA*, this time from your PC, through *BOSSA* (*bossac.exe*, *Basic Open Source Sam boot Assistant*), then it would make **not possible to program an Arduino Due while having both USB port connected** to a PC.

Can somebody confirm, this is the reason?

body:
It should be possible to do because when you flash the microcontroller needs to be in the flashing mode that only works with the Native port, to enable that mode you have to press the erase button for around 2 seconds and then press Reset...

I made a guide on how to do this [here][1]

  [1]: https://github.com/alessandromrc/Atmel-Studio-with-Arduino-Due-board


message:
Battery for WS2812 Strip? (Something's not right)

I have posted this in a few places, so sorry if you have seen it somewhere else

Im working on a battery powered led strip project,

iv put the project together and have been testing with a mains power supply

Iv run some tests and found at max I'd be pulling 4.5 amps

Averaging around 2 ish

I rounded out to about 3.5 amps, and said for 90 mins run time id be looking at the 7ah battery

7/2 = 3.5 so 2 hours runtime

I got a 7ah SLA 12v battery, running though a 12v to 5v converter to power the led strips

(Arduino is running off a usb battery pack)

However after about 45 mins I tested the battery and it said 10.9 v

Which I understand to be too low for SLA batteries (11 should be the minimum?)
 so I shut it off

My question is did I mess up somewhere and get my math wrong?

Many thanks in advance

body:
There are a few things that may contribute to your lower than expected battery lifetime.

**Effective capacity**: you should aim to never use more than 50% of the capacity of a lead acid battery or you will shorten its lifespan considerably.

Also, note that lead acid battery capacity is usually given for a discharge time of 20 hours (C20 rating). The “C” rating could be different but its value should be on the label of the battery.

In the case of a stated capacity of 7Ah at C20, this means the capacity has been calculated at a discharge rate of 7Ah/20h = 350mA. For higher discharge rates, such as in your application, the effective capacity will be much lower.

**Battery voltage**: measuring battery voltage under load does not say much. Measure the battery voltage “at rest”, when completely disconnected from the load for about 1 hour.

**Charging**: Are you charging the battery with a proper charger?


message:
Pulsing 3v into a capacitor to create custom Voltages

I was wondering if it is possible to create diffrent voltages by just pulsing power into a capacitor,

Im using an esp32 which can only output 3v or nothing on its GPIO pins, and i need to make it possible for it to adjust the amount of voltage without anyone touching the device, so i thought maybe you could pulse 3v into a capacitor and the capacitor would only unload what ever the pulses would give in voltages combined, so e.g. 50% 3v 50% 0v, then it gives 1.5v, i have no idea how this would work or the physics behind it

all help would be appreciated

body:
Yes. That's basically PWM through a Low Pass Filter.

Use PWM to set the "duty cycle", which is the percentage of voltage. Then ise a low-pass filter (an inductor + capacitor, or resistor + capacitor) tuned to filter out the carrier frequency (should be around 500Hz if it's the same as an Arduino) to give you a voltage that is proportional to the duty cycle.

<!-- 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/xtkFI.png)

<!-- End schematic -->

That should filter at about 150Hz. The bigger the capacitor the smoother your output will be, but the slower it will be to respond to changes in the specified voltage.  Note that this is not going to give you large currents, but is fine for using as a reference voltage. To boost the current you can feed it into a *voltage follower*:

<!-- 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/KfZr3.png)

<!-- End schematic -->


message:
Select pin to connect RF receiver

I use the RCSwitch library receive signals with a RF receiver. I really need to change the pin the receiver is connected to on my Arduino Uno.

What should I change in my sketch?
What pins can I connect the receiver to?

This is my code:
```
#include <RCSwitch.h>

RCSwitch receiver = RCSwitch();

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

  receiver.enableReceive(0);
  pinMode(1, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

  Serial.println("READY");
}

void loop() {
  if (receiver.available()) {

    int value = receiver.getReceivedValue();

    Serial.println(value);

    switch(value) {
      case 1:
        digitalWrite(1, HIGH);
        digitalWrite(9, HIGH);
        digitalWrite(10, HIGH);
        break;
      case 2:
        digitalWrite(1, LOW);
        digitalWrite(9, HIGH);
        digitalWrite(10, HIGH);
        break;
      case 3:
        digitalWrite(1, HIGH);
        digitalWrite(9, LOW);
        digitalWrite(10, HIGH);
        break;
      case 4:
        digitalWrite(1, HIGH);
        digitalWrite(9, HIGH);
        digitalWrite(10, LOW);
        break;
    }
  }
}
```

body:
You can change

    receiver.enableReceive(0);

which uses pin 2, to

    receiver.enableReceive(1);

which is pin 3 on the Uno. These are the numbers of the external interrupt. The Uno only has two of them, which are tied to those two pins. So as long as you are using the Arduino Uno, you need to use one of these. The Arduino Mega for example has more external interrupts.

For reference also look at the [github page of the RCSwitch library][1] and it's [wiki][2], especially the [site about receiving][3], where this is described.

---

Besides that: As you are using Serial, you might want to change

    pinMode(1, OUTPUT);

to a different pin, since pins 0 and 1 are used for the Hardware Serial interface (`Serial`, which is connected to USB). So the usage of that pin collides with the serial communication.

  [1]: https://github.com/sui77/rc-switch
  [2]: https://github.com/sui77/rc-switch/wiki
  [3]: https://github.com/sui77/rc-switch/wiki/HowTo_Receive


message:
Can Arduino take 19.5 V

I have a 19.5 V power adapter, can I safely connect it to my Arduino? I don't want to damage it. It is very simple, just lights some LEDs, and I don't want to burn the LEDs either.

body: You can do it but you will have nothing left from the regulator for LEDs etc. The best solution is to invest in a buck converter, they are only a few dollars from your favorite china supplier, sometimes even less then a buck. While you are at it purchase two or three you can then use them to generate other voltages as you progress with the Arduino. I use this method a lot, it is a way to use my old laptop power supplies. If you do not have one your next purchase should be a multimeter, even a cheap one is better than none. Then a logic analyzer, again less than $10.00 US. You could also purchase a 8 to 12V wall wart with maybe about 2 amp output and be safe while probably costing less then the buck converter. Have fun!


body:
The Arduino Uno has a maximum voltage range of 6 to 20 v and a recommended range of 7 to 12 v

Using it at 19.5 v may work if the power supply is well regulated but it is uncomfortably close to the limits and dropping nearly 15v across the linear regulator on the Uno may cause it to get fairly hot.


message:
Can at least one Arduino emulate a USB hub?

What I'd *like* to do is have some kind of compact (and preferably inexpensive) Arduino-compatible device emulate a USB hub, and simulates plugging in a USB keyboard, pressing a key, then simulates unplugging the keyboard.

The goal here being a USB-connected device with media-control buttons for an Android device, but since plugging in a device that acts as a keyboard disables the on-screen keyboard, the idea is that it only acts like a keyboard when a button is pressed, but keeps a connection going while it's plugged in.

Is this at all possible with any Arduino-compatible device, do I need to look for a different embedded architecture, or do I need a particular kind of USB converter chip?

body:
Since an Arduino is "just" a microcontroller with some specific bootloader and commonly programmed via the Arduino IDE, you can also program it like any other microcontroller.

There are several projects offering USB functionality as a library, in the Arduino world or outside of it. Use your favorite web search engine to find them. With such a library you should be able to tackle your task.

However, this is not a beginner's task. Please note that you might need to learn a lot.

I'd say that even the simplest AVR based Arduino should suffice.


message:
Arduino Keypad: the following key does not respond

I was wondering, by the time I press the following key, it does not return to the main_screen() function. How can I fix my code?

    void loop()
      {
        int exit = 0;
        char input = customKeypad.getKey();

        main_screen();
         if (input=='A')
            {
              delay(100);
              lcd.clear();

              do{

               lcd.setCursor(1,0);
               lcd.print("Enter minutes: ");

                 if (input=='B')
                   {
                    break;
                  lcd.clear();
                   }
               }
               while(1);
           }
 }

body: You need to read the input again after you get `input == 'A'`.  At the moment, when you enter the `do ... while` loop, the input is always 'A', so `input == 'B'` is never true, and the loop never exits.


message:
PID Arduino UNO

I want to implement a PD controller in Arduino using the PID library. Should I put Ki=0 and the rest of the constants as desired?

```c++
/*
BALL BALANCING USING A PID CONTROL with 6" resistive Touchscreen
*/
//////////////////////////////////////////////////////
///Libraries///
#include <PID_v1.h>
#include <stdint.h>
#include <TouchScreen.h>
#include <Servo.h>

//______________________________________________________________
// Definitions TOUCH PINS
#define YP A1 //brown
#define XM A2 //black
#define YM 7  //yellow
#define XP 6  //red

//______________________________________________________________
// For better pressure precision, we need to know the resistance
// between XP and XM Use any multimeter to read it
// For the 6" its 273 ohms across the X plate
#define Rx 273 //  Resistance in Ohm of Touchscreen measured in X-Direction
TouchScreen ts = TouchScreen(XP, YP, XM, YM, Rx);

// Coordinates Touchscreen
TSPoint p;
double xmin = 146.0;  //154
double xmax = 854.0;   //851
double xLength = 160.0; //Width of Touchscreen in mm at 6.0" 158

double ymin = 63.0;    //63.0
double ymax = 953.0;    //950.0
double yLength = 96.0; //Length of Touchscreen in mm at 6.0" 94

double convertX = xLength / (xmax - xmin);   // converts raw x values to mm. found through manual calibration  0.2295   0.225988
double convertY = yLength / (ymax - ymin);   // converts raw y values to mm. found through manual calibration  0.1082   0.107865

//______________________________________________________________
//Center-Position
double x0=74.35; double y0=42.71; //center  Correct: 0.5//-7     double x0=74.35; double y0=42.71
//______________________________________________________________

int state = 0;

// servos variables
Servo servoX; //X axis
Servo servoY; //Y axis

/////TIME SAMPLE
int Ts = 45;  //Delay between taking samples/measurements

unsigned long Stable=0;
unsigned int noTouchCount = 0; //variable for noTouch
//______________________________________________________________

double Kpx = 0.08;  //Kpx = 0.08; //Proportional (P) Get the ball to set point
double Kix = 0.02;  //Kix = 0.02 0.022 //Integral (I)
double Kdx = 0.035;  //Kdx = 0.035; //Derivative (D)  Stop the ball at set point

double Kpy =0.08;  //Kpy = 0.08
double Kiy =0.02; //Kiy = 0.02 0.022;
double Kdy =0.035;  //Kdy = 0.035;

//______________________________________________________________
//INIT PID
double SetpointX, InputX, OutputX; //for X
double SetpointY, InputY, OutputY; //for Y
PID myPIDX(&InputX, &OutputX, &SetpointX, Kpx, Kix, Kdx, REVERSE);
PID myPIDY(&InputY, &OutputY, &SetpointY, Kpy, Kiy, Kdy, REVERSE);
//______________________________________________________________

void setup(){
servoX.attach(9);
servoY.attach(10);

  OutputX=92;
  OutputY=100;
  servoX.write(OutputX); // Make Plate flat in X-Direction
  servoY.write(OutputY); // Make Plate flat in Y-Direction

  //INIT OF TOUSCHSCREEN
   p = ts.getPoint();

  //INIT SETPOINT, Center of Plate
  SetpointX = 0.0;
  SetpointY = 0.0;

  //Setup PID Controller
  myPIDX.SetMode(AUTOMATIC);
  myPIDX.SetOutputLimits(77, 107); // 83 107
  myPIDY.SetMode(AUTOMATIC);
  myPIDY.SetOutputLimits(85, 115); // -- 81 105

  // TIME SAMPLE
  myPIDX.SetSampleTime(Ts);
  myPIDY.SetSampleTime(Ts);
  delay(100);

  state=0;
  setDesiredPosition();

} // end of setup

void loop()
{
  while(Stable < 15)    //REGULATION LOOP
  {
   p = ts.getPoint();   //measure pressure on plate
   if (p.x > 0 ) //ball is on plate
   {
      servoX.attach(9); servoY.attach(10); //connect servos
      setDesiredPosition();
      noTouchCount = 0;
      p = ts.getPoint(); // measure actual position
      InputX = (p.x - xmin) * convertX;  // read and convert X coordinate
      InputY = (p.y - ymin) * convertY;  // read and convert Y coordinate
      if((InputX == SetpointX && InputY == SetpointY ))

          { Stable = Stable + 1;}

       myPIDX.Compute();  // action control X compute
       myPIDY.Compute();  // action control  Y compute
  }
   else //if there is no ball on plate
  {
    noTouchCount++; //increment no touch count
    if(noTouchCount == 150)
    {
     noTouchCount++;
     OutputX=92; OutputY=100;  //make plate flat
     servoX.write(OutputX); servoY.write(OutputY);
    }
    if(noTouchCount == 300) //if there is no ball on plate longer, detach servos
    { servoX.detach(); servoY.detach(); }
  }
  servoX.write(OutputX); servoY.write(OutputY);  //control

  } // END OF REGULATION LOOP

servoX.detach(); servoY.detach(); //detach servos

///STABILITY////
 while(Stable==15)    //if is stable
 { //still measure actual postiion
    setDesiredPosition();
    p = ts.getPoint();
    InputX = (p.x - xmin) * convertX;  // read and convert X coordinate
    InputY = (p.y - ymin) * convertY; // read and convert Y coordinate
    if(InputX < SetpointX || InputX > SetpointX || InputY > SetpointY || InputY < SetpointY  ) //if ball isnt close to setpoint
    {
      servoX.attach(9); //again attach servos
      servoY.attach(10);
      Stable=0; //change STABLE state
    }

  }//end of STABLE LOOP
}//loop end

//______________________________________________________________
//#### DESIRED POSITION ####
void setDesiredPosition(){
 switch(state){

// Start-Sequence
     case 0:  SetpointX = x0;
              SetpointY = y0;
              p = ts.getPoint();
              if (p.x > 0)
              {
                state = 1;
              } // if ball is on plate
              else if (p.x <= 0)
              {
                state = 0;
                setDesiredPosition();
               } // if no ball is on plate
              break;

// Center-Position
      case 1:  SetpointX = x0;
               SetpointY = y0;
               state = 1;
               break;

    default : state = 0; break;

 }  //end of switch state
}   //end of setDesiredPosition()

//______________________________________________________________
```

body: Yes, you can use the PID library with `Ki=0;` to get a PD controller.


message:
CPP Function param use function with multi params

I want to specify a function with parameters for a function parameter, but it doesn't come together.

```
////////////////////////////////////////////////////////////////////////

// Example funch...
void fileLoad(String path, String type) {
  file = SD.open(path.c_str(), FILE_READ);
  server.streamFile(file, type) != file.size();
  file.close();
}

// This is how I want to use it, but it's not possible:
server.on("/homepage", fileLoad("app/homepage.html", "text/html") );

////////////////////////////////////////////////////////////////////////

// Currently, as it works, you need 1 extra funch...:
void homepage() {
  fileLoad("app/homepage.html", "text/html");
}
server.on("/homepage", homepage);

```

body:
You can find [examples of this sort of thing][1] in the library's examples.

The `on()` function [does support][2] [std::function][3] as a parameter, which in turn, means you can use a C++11-onwards [lambda expression][4] (which [Dave Newton][5] mentioned in comments) to proxy your two-argument function call through a no-argument function:

```c++
server.on("/homepage", [] () {
    fileLoad("app/homepage.html", "text/html");
});
```

The [] ("capture list") is something that would be used if you wanted to copy or refer to things within the scope of the `on` function call.  Since you're not doing that you could also just write a no-argument function which turns around and calls `fileLoad` with your two compile-time-known values.  But it is common for people using this webserver library to need to make references things in scope.

---

As as side note, I'd consider *not* using `String` as your received parameter type in `void fileLoad(String path, String type)`.  When passing in a string literal, you're just causing dynamic allocation for no particularly good reason.

  [1]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino
  [2]: https://github.com/esp8266/Arduino/blob/2.7.4/libraries/ESP8266WebServer/src/ESP8266WebServer.h#L94
  [3]: https://en.cppreference.com/w/cpp/utility/functional/function
  [4]: https://en.cppreference.com/w/cpp/language/lambda
  [5]: https://arduino.stackexchange.com/users/8583/dave-newton


message:
ESP32 Partition size and maximum program size

From an ESP32 example code, I extracted the following part, that just prints the flash partition list to the console.

```cpp
#include <string.h>
#include <assert.h>
#include "esp_partition.h"
#include "esp_log.h"

static const char *TAG = "example";

void setup(void)
{
    Serial.begin(115200);
    delay(200); // Otherwise, the first log entries get lost
    ESP_LOGI(TAG, "Start test");
    esp_partition_iterator_t iter = esp_partition_find(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_ANY, NULL);
    ESP_LOGI(TAG, "Name, type, subtype, offset, length");
    while (iter != nullptr)
    {
      const esp_partition_t *partition = esp_partition_get(iter);
      ESP_LOGI(TAG, "%s, app, %d, 0x%x, 0x%x (%d)", partition->label, partition->subtype, partition->address, partition->size, partition->size);
      iter = esp_partition_next(iter);
    }

    esp_partition_iterator_release(iter);
    iter = esp_partition_find(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, NULL);
    while (iter != nullptr)
    {
      const esp_partition_t *partition = esp_partition_get(iter);
      ESP_LOGI(TAG, "%s, data, %d, 0x%x, 0x%x (%d)", partition->label, partition->subtype, partition->address, partition->size, partition->size);
      iter = esp_partition_next(iter);
    }

    esp_partition_iterator_release(iter);

}

void loop()
{
}
```

In the project folder, I also have a custom `partitions.csv` file as follows:
```
nvs,        data, nvs,      0x9000,  0x6000,
phy_init,   data, phy,      0xf000,  0x1000,
factory,    app,  factory,  0x10000, 512k,
storage,    data, ,         ,        0x40000,
```

If I run the code, it correctly shows the custom partitions with the above sizes, everything like it should be.

**However**, the build output says the program uses 207278 Bytes from a maximum of 1310720. If I change the partition scheme selection in the tools menu, the second number changes. I would expect the maximum size to be equal to the size of the `factory` partition from the custom partition scheme.

If I change the factory partition to be only 100k in size, the ESP32 fails to boot and enters a core-dump-restart-loop.

Is this a compiler bug or am I overlooking something?

body:
This appears to be a limitation of the toolchain. The output of processing the `partitions.csv` file doesn't make it back to the compiler to generate the correct message. The different partition schemes available in the menu come from `boards.txt` of the ESP32 package. They can be updated, but would be overwritten when the toolchain is updated. For the compiler input, the setting in the menu is relevant, but the actual size of the partitions comes from the `partitions.csv` file (if it exists).

This means that one has to manually make sure that the size of the `factory` partition in the csv file is larger or equal to the actual code size. Ideally, it is also equal to the selected partition size from the menu (to get the correct message and eventually error if the binary size exceeds the allocated space).

Some testing shows that if the actual size of the `factory` partition is smaller than the code size (and smaller than the compiler size limit) the application will successfully build and upload, but fail to run. The chip will enter a startup-reboot-forever loop and not execute any user code. However, whether that is always the case is not guaranteed.


message:
Get time as 24 hour format from RTC

I have a DS3231 RTC module.

I would like to get the time from the RTC as 24 hour format not 12 hour. The library that I'm using requires that I pass in 2 Boolean values into ```Clock.getHour()```, however changing these values does not change the returned time format.

Code;
```
/*
DS3231_test.pde
Eric Ayars
4/11

Test/demo of read routines for a DS3231 RTC.

Turn on the serial monitor after loading this to check if things are
working as they should.

*/

#include <DS3231.h>
#include <Wire.h>

DS3231 clock;
bool century = false;
bool h12Flag;
bool pmFlag;
byte alarmDay, alarmHour, alarmMinute, alarmSecond, alarmBits;
bool alarmDy, alarmH12Flag, alarmPmFlag;

void setup() {
 // Start the I2C interface
 Wire.begin();

 // Start the serial interface
 Serial.begin(57600);
}

void loop() {
 // send what's going on to the serial monitor.

 // Start with the year
 Serial.print("2");
 if (century) {   // Won't need this for 89 years.
  Serial.print("1");
 } else {
  Serial.print("0");
 }
 Serial.print(clock.getYear(), DEC);
 Serial.print(' ');

 // then the month
 Serial.print(clock.getMonth(century), DEC);
 Serial.print(" ");

 // then the date
 Serial.print(clock.getDate(), DEC);
 Serial.print(" ");

 // and the day of the week
 Serial.print(clock.getDoW(), DEC);
 Serial.print(" ");

 // Finally the hour, minute, and second
 Serial.print(clock.getHour(h12Flag, pmFlag), DEC);
 Serial.print(" ");
 Serial.print(clock.getMinute(), DEC);
 Serial.print(" ");
 Serial.print(clock.getSecond(), DEC);

 // Add AM/PM indicator
 if (h12Flag) {
  if (pmFlag) {
   Serial.print(" PM ");
  } else {
   Serial.print(" AM ");
  }
 } else {
  Serial.print(" 24h ");
 }

 // Display the temperature
 Serial.print("T=");
 Serial.print(clock.getTemperature(), 2);

 // Tell whether the time is (likely to be) valid
 if (clock.oscillatorCheck()) {
  Serial.print(" O+");
 } else {
  Serial.print(" O-");
 }

 // Indicate whether an alarm went off
 if (clock.checkIfAlarm(1)) {
  Serial.print(" A1!");
 }

 if (clock.checkIfAlarm(2)) {
  Serial.print(" A2!");
 }

 // New line on display
 Serial.println();

 // Display Alarm 1 information
 Serial.print("Alarm 1: ");
 clock.getA1Time(alarmDay, alarmHour, alarmMinute, alarmSecond, alarmBits, alarmDy, alarmH12Flag, alarmPmFlag);
 Serial.print(alarmDay, DEC);
 if (alarmDy) {
  Serial.print(" DoW");
 } else {
  Serial.print(" Date");
 }
 Serial.print(' ');
 Serial.print(alarmHour, DEC);
 Serial.print(' ');
 Serial.print(alarmMinute, DEC);
 Serial.print(' ');
 Serial.print(alarmSecond, DEC);
 Serial.print(' ');
 if (alarmH12Flag) {
  if (alarmPmFlag) {
   Serial.print("pm ");
  } else {
   Serial.print("am ");
  }
 }
 if (clock.checkAlarmEnabled(1)) {
  Serial.print("enabled");
 }
 Serial.println();

 // Display Alarm 2 information
 Serial.print("Alarm 2: ");
 clock.getA2Time(alarmDay, alarmHour, alarmMinute, alarmBits, alarmDy, alarmH12Flag, alarmPmFlag);
 Serial.print(alarmDay, DEC);
 if (alarmDy) {
  Serial.print(" DoW");
 } else {
  Serial.print(" Date");
 }
 Serial.print(" ");
 Serial.print(alarmHour, DEC);
 Serial.print(" ");
 Serial.print(alarmMinute, DEC);
 Serial.print(" ");
 if (alarmH12Flag) {
  if (alarmPmFlag) {
   Serial.print("pm");
  } else {
   Serial.print("am");
  }
 }
 if (clock.checkAlarmEnabled(2)) {
  Serial.print("enabled");
 }

 // display alarm bits
  Serial.println();
 Serial.print("Alarm bits: ");
 Serial.println(alarmBits, BIN);

 Serial.println();
 delay(1000);
}
```

How do I make this happen?

body:
> The library that I'm using requires that I pass in 2 Boolean values
> into Clock.getHour(), however changing these values does not change
> the returned time format.

You appear to be talking about the parameters [here][1], which the second is for getting the current state of the AM/PM flag and configuration and not altering the kind of value you get in the return.

There's a [setClockMode function][2] you can call which will configure the chip to report in 24-hour mode.  If you call that passing in `false`, `getHour` should begin returning 24-hour time.

  [1]: https://github.com/NorthernWidget/DS3231/blob/v1.0.7/DS3231.h#L73
  [2]: https://github.com/NorthernWidget/DS3231/blob/v1.0.7/DS3231.h#L102/DS3231.h#L106