# Question
Title: Why can't I use Jeelib Sleepy on the Teensy 2 along with Serial
I have been using the Jeelib Sleepy functionality for several years now to achieve low power states on the Arduino ATmega328/1280/2560 boards, specifically the LoseSomeTime functionality.

I want to get my Teensy 2 to go into a similar low power state, so I tried a very simple sketch that simply put the device to sleep, flashed an LED, and posted some Serial messages. I did need to comment out a few lines in Jeelib:

```
// adjust the milli ticks, since we will have missed several
#if defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny85__) || defined (__AVR_ATtiny44__) || defined (__AVR_ATtiny45__)
    extern volatile unsigned long millis_timer_millis;
    millis_timer_millis += msecs - msleft;
#else
    extern volatile unsigned long timer0_millis;
    timer0_millis += msecs - msleft;
#endif

```

This had to be done as the delay() and millis() functions on the Teensy use different variable names for the adjustment, and it was the quickest way of solving the problem. LoseSomeTime works on the ATmega328 hardware with this change.

I found that although the LoseSomeTime function did sleep for a period, the Serial functionality stopped working entirely - no messages were being printed at all. I have encountered this before on ATmega328 hardware because the microcontroller has gone to sleep before the serial buffer was flushed. I added a number of delay()s after the Serial.writes and also tried using Serial.flush() to make sure the buffer was empty.

LoseSomeTime requires setting an interrupt on the watchdog timer, but I can't see how this would impact Serial operation.

# Answer
> 1 votes
This is a problem with the Teensy boards - or more correctly that the Jeelib Sleepy library does not support the Teensy boards.

You will need to modify the library to make it work for Teensy boards. Or you could use another low power/sleep library.

---
Tags: serial, power, library, teensy
---


# Question
Title: Reading three signals sent serially on Simulink from Arduino
I am sending three signals from one Arduino mega to another using xbees. On the receiving end I am using these signals in a Simulink code to control servo motors. Currently it is set up to read from analog pins without the wireless set up. With the wireless technology the signals are all being sent and received through one serial port. I believe I would need to change the inputs in Simulink to a serial receive block instead of an analog pin block. The problem is the documentation for the serial receive block says you can not assign more than one serial receive block to the same serial port. If anyone has a solution to this it would be greatly appreciated!

receiving code

```
int received1;
int received2;
int received3;
void setup() {
  Serial.begin(9600);
}
void loop() {
  if(Serial.available() )
  {
    received1, received2, received3 = Serial.read();
  }
}

```

transmitting code:

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

void loop() {
  int sensorValue1 = analogRead(A0);
  int sensorValue2 = analogRead(A1);
  int sensorValue3 = analogRead(A2);
  Serial.write(sensorValue1, sensorValue2, sensorValue3);
  delay(1);
}

```

# Answer
> 1 votes
You need to put your data into a packet and then send the packet to Simulink.

You have tried this by this line in your transmitting code:

```
Serial.write(sensorValue1, sensorValue2, sensorValue3);

```

However, as you can see from the Serial Write documentation it does not work like that. The function cannot accept 3 arguments.

Try this instead:

```
Serial.write(sensorValue1);
Serial.write(sensorValue2);
Serial.write(sensorValue3);

```

---
Tags: serial, arduino-mega, xbee
---


# Question
Title: 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:

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):

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

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!

# Answer
> 1 votes
(Just to illustrate what Majenko is saying.)

This is the inside of a breadboard:

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

---
Tags: arduino-uno, led, current, resistor, shift-register
---


# Question
Title: 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:

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:

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:

```
#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!

# Answer
> 5 votes
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 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.

---
Tags: i2c, arduino-nano-33-iot
---


# Question
Title: How can I read the Timer direction in phase correct PWM?
I have had to use Timer0 with phase correct PWM and a prescaler of 1. This results in a 32khz PWM frequency and obviously impacts millis, delay and micros. (Timer1 and Timer 2 are also in use so changing to those is not an option)

millis() is trivial to work around - multiply by 32 as the TOV0 interrupt handler is called 32 times more frequently (subject to overflow of course)

micros() is somewhat trickier - as normally it is the Timer0 overflow count (as used in millis() though shifted in this case) plus the current value of TCNT0. That works great when TCNT0 is increasing only and resetting to 0 after MAX - but in phase correct PWM it could be going upwards or downwards.

I think what I need to do is find the direction the Timer is currently using - but pouring over the datasheet for the ATmega328P I can't seem to find a way to do so...

Is there a way of reading this, eg from a register I can interrogate for it?

Alternatively can anyone else think of a way to get microsecond (or close - 10 microsecond would be good enough) resolution when all timers are in phase correct mode?

I'm considering a fall-back of reading TCNT0 twice and deriving it from that - with a prescaler of 1I am assuming it is not possible to read it twice faster than it could change - however I'd prefer a neater solution if there is one.

# Answer
> 1 votes
I decided to go with the inspect method and modified wiring.c accordingly - may not fit everyone's use case but solves mine (along with a couple of tweaks changing the #define's to volatile variables and adding a setter for them.

micros updated to:

```
unsigned long micros() {
  unsigned long m;
  uint8_t oldSREG = SREG, t1, t2;

  cli();
  m = timer0_overflow_count;
#if defined(TCNT0)
  t1 = TCNT0;
  t2 = TCNT0;
#elif defined(TCNT0L)
  t1 = TCNT0L;
  t2 = TCNT0L;
#else
  #error TIMER 0 not defined
#endif

#ifdef TIFR0
  if ((TIFR0 & _BV(TOV0)) && (t1 == timer0_phase_correct ? 0 : 255))
    m++;
#else
  if ((TIFR & _BV(TOV0)) && (t1 == timer0_phase_correct ? 0 : 255))
    m++;
#endif

  SREG = oldSREG;

  if (timer0_phase_correct && t1 > t2){
    t2 = 510 - t2;
  }

  return (m * us_per_timer0_overflow) + (clockCyclesToMicroseconds(timer0_prescale * t2));
}

```

---
Tags: pwm, timers, timing
---


# Question
Title: Regulate Water Pumps flow by DC Stepper Motor Driver
I'm an Arduino beginner. I've got 2 x 12V DC water pumps

https://www.ebay.co.uk/itm/224461221015

plus 12V, 2A AC/DC adapter to feed them.

I would like to regulate the speed (flow) of the pumps programmatically by Arduino. My first idea was to use 2 channel Relay, however, it only supports two states - on/off. Then I discovered this DC Stepper Motor Driver:

https://www.ebay.co.uk/itm/274521887403

That seems to be a good fit in terms of specifications, but I'm not sure whether it will work with the pumps? It makes me think of whether the DC Stepper Motor Driver may work with only specific motors?

Thanks for any advice!

# Answer
> 1 votes
Yes, it will work.

You can control the speed of the water pumps with a PWM signal by using:

```
analogWrite(PWM_pin, value)

```

Or you can use a cheap transistor like a P2N2222A; here is a full tutorial.

# Answer
> 1 votes
Unfortunately after trying it does not work as expected. It has been mentioned that it must be a **BRUSHED** motor and most of these pumps on eBay are **Brushless**.

---
Tags: arduino-uno, stepper-motor
---


title: Is there anything wrong with this code

text:
# Question
Title: 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

```
    /** 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;
    };

```

# Answer
> 3 votes
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:

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

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

```

# Answer
> 3 votes
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

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

```

than

```
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:

```
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.

```
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:

```
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);
}

```

# Answer
> 1 votes
Ok so if anyone is interested here is what I ended up with

```
/*
  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

```
#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

# Answer
> 0 votes
It's hard to answer without any description of the actual problem.

On the top of my head, with that much code i'd consider starting off by creating a separate class declaration, and write your member definitions outside. It will make the code way more manageable, and easier to troubleshoot.

https://www.learncpp.com/cpp-tutorial/class-code-and-header-files/

Also, you have several include statements in at least two different places. They usually go first in a file, along with include guards. If your code consists of separate files, please make that clear to readers.

---
Tags: isr, cpp
---


# Question
Title: Custom assert() implementation: not printing the error message
I am writing my own assert() macro on Arduino as shown below.
When I run it **from the main() it always works correctly** (prints the message and gets into an infinite loop), however when I call it within a class function it gets stuck without printing anything. Why is that?

assert.cpp/.h

```
#ifndef _ASSERT_H_
#define _ASSERT_H_

void assertion_failure(const char* expr, const char* file, int linenum);

#define assert(expr) \
    if (expr) ; \
    else assertion_failure(#expr, __FILE__, __LINE__)

#endif /* _ASSERT_H_ */

```

```
#include "assert.h"
#include "Arduino.h"

void assertion_failure(const char* expr, const char* file, int linenum)
{
    Serial.print("Assertion failed in '");
    Serial.print(file);
    Serial.print("' on line ");
    Serial.print(linenum);
    Serial.print(": ");
    Serial.println(expr);
    Serial.flush();

    while (1);
}

```

And the context in which the assert gets stuck below (it works well when I call it in main() however):

```
int ADS1256::assert_debug()
{
    uint8_t id = read_register(STATUS) >> 4;
    assert(false);    // Gets stuck here without printing anything to screen
    return id;
}

```

---

EDIT: looks like it has something to do with build configuration. I am using PlatformIO build system. It does not work when I use this file structure:

```
├── include
│   └── assert.h
├── lib
│   ├── ADS1256
│      ├── ads1256.cpp
│      ├── ads1256.h
│      └── ads1256_regmap.h
├── src
    ├── assert.cpp
    └── main.cpp

```

However, if I move assert.cpp/.h into a dedicated directory within lib/ it works fine. What is the reason behind this? How can I investigate why this happened?

It works with this layout (again, using PlatformIO default build configuration):

```
├── include
├── lib
│   ├── ADS1256/
│   ├── Assert/
│       ├── assert.cpp
│       └── assert.h
├── src
    └── main.cpp

```

# Answer
> 0 votes
As per comment on question, this is not as finished as I'd like, but it's a start.

I deeply suspect what you're running into is a conflict between the name of your header and the standard `assert.h` header. You're using the same header name and same macro names as is used in the standard c header, that is part of both c++ and "Arduino.". The standard `assert()` with the way things are normally set up on the AVR Arduino core does basically just go into a tight loop and do nothing.

I would consider naming your macro something other than `assert` and naming your header something other than `assert.h`. If you want to get into the precise details why, we need to see things like your include path order, and the include directives themselves. Even then, the advice would be about the same.

## Diagnostics

#### `--save-temps`

In platform.io you should be able to add `--save-temps` to the `avr-gcc` command-line to get it to produce (or keep) the output of the preprocessing stage. GCC annotates these showing where each section of the entire output came from, so you can see which headers each `#include` directive actually included and in what order all of this happened.

#### NDEBUG

Something else you can try, as a diagnostic measure, is to define `NDEBUG` in your project settings. This is usually defined by IDEs for "release mode". It basically makes `assert()` into a NOP, which in turn means that it will not do the usual avr-libc thing of locking up. If you're seeing the avr-libc assert being expanded instead of your own, then the behaviour will change to just not locking up, but also not doing what your own `assert` would do.

## AVR-based Arduino `assert()` support

avr-libc's `assert()` tries to print its assertion message on stderr, which is not configured on AVR based Arduinos to do anything. So the outward behaviour is that it locks up. However, you can complete avr-libc's implementation of stderr in terms of the Arduino's `Serial.write` function, in which case the normal avr-libc `assert` will work just fine. Here's one example of completing avr-libc's stdio printing in terms of `Serial`.

## `__FILE__` Caveat and SRAM

Something you should be aware of in using `__FILE__`, and therefore `assert` (whether it be avr-libc's or yours) is that `__FILE__` expands to a string literal which is the full path of the source filename, which can be quite long. On the UNO (you have tagged) these go into SRAM. So if you use `assert` in a couple different files, you can very quickly eat up the available SRAM on the AVR.

For this reason, in my own little assert-type macros, I've taken to not reporting the file but instead a custom tag, which is often just a single letter or number. Besides, often my asserts are blinking the `__LINE__` number on an LED, where `__FILE__` is impractical in my typical use case anyway.

---
Tags: arduino-uno, serial, debugging
---


# Question
Title: 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();
  }

}

```

# Answer
> 1 votes
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`.)

```
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 and when you are editing the question.

---
Tags: arduino-motor-shield, stepper
---


# Question
Title: Measuring the battery level powering the arduino
I would like to power my arduino nano with a 9V battery, but I would also like to measure the voltage of the battery to know its charge level.
Can I use the MAX471 Voltage Current Sensor module by connecting the VIN pin to my battery and VOUT to my arduino ?

# Answer
> 1 votes
If you want measuring a "battery level" in mAh for example, you must measure Voltage AND Current, so INA219 is a better deal (it is a I2C control).

---
Tags: sensors, arduino-nano, power, voltage
---


# Question
Title: Powering the Arduino with a battery and reading the battery voltage
I am trying to display the battery voltage as it is being used to power the Arduino.

I have tried powering the Arduino through the USB and the battery voltage is read accurately when compared to the multimeter reading.

But when the battery is powering the Arduino and being read, it keeps displaying 5.00 V, which it should not be.

Just wondering what might be happening and how I can go about resolving this issue.

I have been trying to research some answers, and came across something about an 1.1 V reference voltage, but I'm not entirely sure what they mean.

Here is my code for reference:

```
#include <SoftwareSerial.h>
SoftwareSerial BTserial(10,11);

int battPin = A1;

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

void loop() {
  int voltReading = analogRead(battPin);
  float volts = (voltReading/204.6);
  BTserial.print(volts);
  BTserial.print(";");
  Serial.println(volts);
}

```

I am using a 3.7 V Li-po battery. It is connected to A1 and also to Vin.

# Answer
AFAIK, Arduinos are set up to use their operating voltage as the `analogRead` reference voltage by default.

So what I think is happening is that you are trying to measure the battery voltage *with the battery itself as a reference voltage*.

This will, of course, always show "full scale".

You could use a voltage divider to bring the measured battery voltage down to about 1 V (max) and use the Arduino's internal reference of about 1.1 V for measuring.

Note that the 1.1 V internal reference is stable, but not necessarily exactly 1.1 V. You will have to measure it first.
> 2 votes

# Answer
You need to divide down the battery voltage into the 1.1V max range, and use the Internal bandgap voltage reference for the ADC conversions.

Connect the Battery to VCC, not Vin, you don't want it going thru the regulator.
> 0 votes

# Answer
If you want measuring a "battery level" in mAh for example, you must measure Voltage AND Current, so INA219 is a better deal (it is a I2C control).
> 0 votes

---
Tags: arduino-uno, battery, adc, voltage, analogreference
---


# Question
Title: is there any archives of melody tones for buzzer used in arduino?
I am using buzzer in my arduino and I read some articles about using array of tones(notes in music) with different frequencies to play play pleasant melodies.however, I do not find any site and archives for tones used in industrial, such as Start,Stop,warning,danger,next level,.... is there any site that collects these things and if not how can I create my own array of tones?

this is notes I have

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

// DURATION OF THE NOTES
#define BPM 480      //you can change this value changing all the others
#define H 2*Q //half 2/4
#define Q 6000U/BPM //quarter 1/4
#define E Q/2   //eighth 1/8
#define S Q/4 // sixteenth 1/16
#define W 4*Q // whole 4/4

```

# Answer
> 1 votes
```
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define REST      0

int piezoPin = 13;
int numTones = 15;
int tempo = 2.5;

//Twinkle Twinkle Little Star:

int tones[] = {NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_G4, NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_C4, REST};

int duration[] = {500, 500, 500, 500, 500, 500, 1000, 500, 500, 500, 500, 500, 500, 1000, 4000};

void setup()
{
  for (int i = 0; i < numTones; i++)
  {
    tone(piezoPin, tones[i], duration[i] / tempo);
    delay(duration[i] / tempo);
  }
  noTone(piezoPin);
}

void loop()
{
} // Reset to play the song again

```

---
Tags: buzzer
---


# Question
Title: 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) 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:

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.

# Answer
> 3 votes
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.

> Why I actually need those delays?

If you read page 6 of ADIS16364 datasheet, 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**

~~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`.~~

**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();

```

---
Tags: spi, imu
---


title: How fast does the Arduino execute code?

text:
# Question
Title: 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.

```
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?

# Answer
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.
> 3 votes

---
Tags: loop, analogwrite, timing
---


title: Simple GET request is failing silently

text:
# Question
Title: 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 library and a cheap ENC28J60 Ethernet Module. 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);
  }
}

```

# Answer
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, you can see how to properly connect this module to Arduino UNO.
> 3 votes

---
Tags: arduino-uno, ethernet, http
---


title: STM32f4 Warning: The core is locked up

text:
# Question
Title: 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

```

# Answer
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
> 3 votes

---
Tags: stm32
---


title: ESP-01 OTA Error uploading

text:
# Question
Title: 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

# Answer
> 3 votes
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.

---
Tags: esp8266, ota
---


# Question
Title: 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 from the Arduino IDE?

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

# Answer
# Modifying/Making a variant

If you wanted to do it in an Arduino-like way it would require editing the Arduino Due variant.cpp 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):

```
  { 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:

```
#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:

```
/*
 * 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 and substitute all of the references that it would have gotten from `g_APinDescription` with hard-coded values.
> 1 votes

---
Tags: pins, pinmode
---


# Question
Title: 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);
  }
}

```

# Answer
> 1 votes
**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**

Observe the onboard LED going HIGH and the buzzer going off. You can find the project link **here** 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*

---
Tags: arduino-uno, arduino-ide
---


title: Recover .ino file from tmp files?

text:
# Question
Title: 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

# Answer
Well, stupidly enough, the missing code was inside of the TMP files... in all of them...
> 6 votes

---
Tags: arduino-ide
---


title: Arduino Uno - Analog Circuit Simulator

text:
# Question
Title: Arduino Uno - Analog Circuit Simulator
I control an analog circuit with Arduino Uno. I want to simulate an Arduino Uno with operational amplifiers (741). Can I simulate Arduino with SPICE?

# Answer
Here is the one which is closest to be useful for your question

**Link**: https://markmegarry.github.io/AVR8js-Falstad/

Try it out for yourself It is very slow though.
> 3 votes

# Answer
You *could* use https://en.wikipedia.org/wiki/Ngspice. From what is written there, the Xspice part could be used for creating a simple model of the Arduino, for checking how the analog part of your circuit interacts with the uC. Unfortunately the main site () is down, atm, as many other projects hosted on SourceForge. But it might be worth having a look, once it's back online.
> 1 votes

---
Tags: arduino-uno, hardware, simulator, analog-sampling, op-amp
---


title: Fader OOP Problem

text:
# Question
Title: 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;
}

```

# Answer
> 1 votes
I don't really know about the

```
// Pins
byte led;
byte buttonpin;

```

but maybe you can try

```
// Pins
int led;
int buttonpin;

```

---
Tags: led, pwm, millis
---


title: Arduino Due SerialUSB Resetting

text:
# Question
Title: Arduino Due SerialUSB Resetting
Having this basic example for using the `SerialUSB` function on the Arduino Due under Windows:

```
// ARDUINO DUE BLINK LED
void setup(){
  pinMode(13,OUTPUT);
  SerialUSB.begin(2000000);
  while(!SerialUSB){
    digitalWrite(13,HIGH);
    delay(100);
    digitalWrite(13,LOW);
    delay(100);
  }
}

void loop(){
  SerialUSB.println("Hello, World!");
  digitalWrite(13,HIGH);
  delay(100);
  digitalWrite(13,LOW);
  delay(900);
}

```

I am having trouble understanding which shall be the operating sequence for this use. Normally I follow these steps:

1. Open Arduino IDE, select Arduino Due (Programming Port) at COM 01, and connect it to PC USB,
2. Compile and Upload the code,
3. Open a Serial Monitor App, with COM 02, 2000000 bps or 9600 bps, 8b data, 1b stop, no parity, RTS|CTS flow control.

If I keep the Arduino connected to the Programming Port after trying the Native USB Port, I have to disconnect and connect everything to program it again (??), or disable it through the windows Device Manager.

Which is the proper sequence (and perhaps the code) for doing this the right way?.

# Answer
> 0 votes
Assume the Arduino is already programmed and energized, i.e. from the Barrel 5V Power Source or from a USB Charger (as minimum) at Programming USB Port.

The following should be the proper steps:

1. If not Programmed: Program the Arduino, either through the Programming USB Port, Native USB Port, etc.
2. If Native USB Cable to PC is Plugged: Unplug Cable, or Reset Arduino,
3. Plug Native USB Cable to PC,
4. Check COM Number for the Native USB Port, i.e. COM01,
5. If Serial Monitor Connected: Disconnect Serial Monitor,
6. Connect through a Serial Monitor App, with COM01, any bps, 8b data, No parity, 1b stop, RTS|CTS flow control.

Done. The data flow should start immediately as soon as you Reset.

Check this for a deeper post with another example for debugging.

---
Tags: serial, usb, communication
---


title: Using External Power Supply Arduino Uno

text:
# Question
Title: 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.

# Answer
> 1 votes
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 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.

---
Tags: arduino-uno, power, battery
---


# Question
Title: 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?

# Answer
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
> 2 votes

---
Tags: serial, arduino-due, bossa, atsam3x8e
---


title: Higher than 12V Arduino Uno

text:
# Question
Title: 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

# Answer
> 1 votes
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 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.

# Answer
> 3 votes
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)

---
Tags: arduino-uno, power, hardware
---


# Question
Title: 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

# Answer
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?
> 3 votes

---
Tags: battery, ws2812
---


# Question
Title: 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.

```
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 {
  }
}

```

# Answer
```
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, 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. This should cause your code to print something around 66.
> 1 votes

---
Tags: ultrasonics
---


# Question
Title: 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

# Answer
> 2 votes
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.

simulate this circuit – Schematic created using CircuitLab

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*:

simulate this circuit

---
Tags: esp32, voltage-level, electronics, electricity, capacitors
---


title: Arduino does not work on battery

text:
# Question
Title: Arduino does not work on battery
The day before I got my used full package arduino uno. I tested it on USB plug. Everything worked fine. I wrote a piece of testing code and uploaded. After I have accomplished with the test I have unpluged arduino from PC and connected to battery and I see that it does not work. I have used a multi-tester to find out the voltage. It showed 4.7V. Now I wonder should I buy a new battery or there is another reason for this. Anybody, please suggest me what to do. **Update** The battery came with arduino set. It is written that it is a 9V battery. I am plugging it to the battery input in my arduino uno. Polarity is ok. The same program working on connection via usb, does not when connected to battery.

# Answer
Did you make sure the battery is charged? Does it have enough voltage to power the board? Remember that Arduino has internal voltage regulator, so you need something little more than 5V in order to get it working okay.

*(Comment by bpinhosilva re-purposed as an answer so this will stop showing up as unanswered).*

> @bpinhosilva you are right, the battery was not supplying enough power to make arduino work.

Please accept this so that the number of unanswered questions goes down. :)
> 2 votes

# Answer
Check the serial number of your board. Some boards were shipped with a defective boot loader, which has the loader stuck in an infinite loop when powered off and on again. Just Google the serial range of possible defective boards, and check if your board is in that range.
> 1 votes

# Answer
Try to use a battery that provides at least 7-12 volts. The voltage regulator will regulate the needed 5 volts for the arduino.
> 1 votes

# Answer
simply you can weld a little electrolytic capacitor eg. 4 or 6 microfarads, 12 or more Volts, with the positive wire on the reset pin and the negative on the GND pin. in this way you can solve the restart without the USB connection. This is what I did Enjoy with Arduino. By Daniele
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Digital Input using a button doesn't work properly when using it to control a relay
I'm trying to control a relay both via Bluetooth and using a switch. The problem is that, when the LED is off, I can turn it on with the switch but then if I turn off the switch the relay will stay on. Is there something wrong with my code? Thanks in advance. The switch is installed as follows:

Here is my code: Switch is connected to pin 3 and the relay is connected to pin 2.

```
//bluetooth hc-06
int ledPin = 2; // usamos un pin de salida al LED
int state = 0; // Variable lectrura serial
int interruptor=3;

void setup() {
    pinMode(ledPin, OUTPUT);   //Declara pin de Salida
    pinMode(interruptor, INPUT);
    digitalWrite(ledPin, LOW); //Normalmente Apagado
    Serial1.begin(9600);
    }

void loop() {
  int valor=digitalRead(interruptor);

  if(Serial1.available() > 0){
       state = Serial1.read();
  } // esta parte del código es para solo 1 Carácter o Unidad.

 if (state == '0'&& valor== LOW) {
    digitalWrite(ledPin, LOW);
    Serial1.println("LED: off");
 }

 else
 if (state == '1' || valor== HIGH) {
     digitalWrite(ledPin, HIGH);
     Serial1.println("LED: on");
 }

}

```

New code:

```
//bluetooth hc-06
int ledPin = 2; // usamos un pin de salida al LED
int state = 1; // Variable lectrura serial
int interruptor=3;

void setup() {
    pinMode(ledPin, OUTPUT);   //Declara pin de Salida
    pinMode(interruptor, INPUT);
    digitalWrite(ledPin, LOW); //Normalmente Apagado
    Serial1.begin(9600);
    }

void loop() {
  int valor=digitalRead(interruptor);
 //si el modulo ha mandado dato, guardarlo en estado.

  if(Serial1.available() > 0){
       state = Serial1.read();
  } // esta parte del código es para solo 1 Carácter o Unidad.

 // si el estado es 0 ese sería Apagado “OFF”
 if (valor== LOW) {
    digitalWrite(ledPin, LOW);
    Serial1.println("LED: off");
 }

 // de lo contrario si el estado es 1 ese sería Encendido “ON”
 else
 if (valor== HIGH) {
     if (state== 1){
     digitalWrite(ledPin, HIGH);
     Serial1.println("LED: on");
     }
     else if (state== 0){
     digitalWrite(ledPin, LOW);
     Serial1.println("LED: off");

     }
 }

}

```

# Answer
Well, there are a couple of problems.

In the original SW, you are checking for `state = '0'` and `state = '1'`, but the initial value of state is `0` (not `'0'`). For this reason both tests always return false.

In addition, avoid setting conditions when not necessary. `else` already mean "all the other options", so if you have one variable that can be only A or B, don't write `if A ... else if B ...`; the second condition is necessary (and meaningful) only if the condition is actually something you care of (so you want to exclude condition C).

I started modifying your sketch from the new version, and here are the things I modified:

* Variables were set to type `uint8_t`; `int` is not efficient on 8-bit platforms, so use 8-bit variables whenever you can
* Instead of using multiple triggers, I used a single variable (`ledState`) to calculate the state in each loop. This way it is much easier to track the modifications
* simplified the input management: now it turns on the led when the input is high, and does nothing (leaves it off) when it is low
* simplified the bluetooth management. With a `'1'` it turns on the led, and all the other chars set it off; if you need only a '0' to turn it off you can easily modify the parentheses to ignore other chars

This is the code I wrote. NOTE: I did not test it, so there may be residual bugs. Let me know if it works as you expect or want some additional clarifications:

```
uint8_t ledPin = 2;
uint8_t interruptor = 3;
uint8_t bluetoothState = '0';

void setup() {
    pinMode(ledPin, OUTPUT);
    pinMode(interruptor, INPUT);
    digitalWrite(ledPin, LOW);
    Serial1.begin(9600);
}

void loop() {
    uint8_t ledState = LOW;

    if (digitalRead(interruptor)) {
        ledState = HIGH;
        Serial1.println("LED: on (switch)");
    }

    if(Serial1.available() > 0){
        bluetoothState = Serial1.read();
    }

    if (bluetoothState == '1') {
        ledState = HIGH;
        Serial1.println("LED: on (BT)");
    }

    digitalWrite(ledPin, ledState);
    if (ledState == LOW) {
        Serial1.println("LED: off");
    }
}

```

Things still to do (IMHO):

* make a robust button handler (for instance using the debounce library)
* get rid of the serial debug outputs
* make a better serial protocol
> 1 votes

# Answer
You have to invalidate the `state` variable when `Serial` is not available, otherwise you will produce strange behaviours.

```
if (Serial1.available() > 0) {
    state = Serial1.read();
} else {
    state = -1; // not valid
}

```

Also, serial values will be characters, not integers, so compare with character values, e.g.,

```
if (state == '1')

```
> 0 votes

---
Tags: bluetooth, relay, switch, arduino-pro-micro
---


# Question
Title: 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:

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.

# Answer
> 3 votes
Hadn't pushed the button all the way in lol

---
Tags: programming, arduino-nano, c++
---


title: Select pin to connect RF receiver

text:
# Question
Title: 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;
    }
  }
}

```

# Answer
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 and it's wiki, especially the site about receiving, 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.
> 3 votes

---
Tags: arduino-uno, library, pins, rf
---


# Question
Title: 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);
       }

```

}

# Answer
> 2 votes
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.

---
Tags: keypad
---


title: Get time as 24 hour format from RTC

text:
# Question
Title: 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?

# Answer
> 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, 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 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.
> 2 votes

---
Tags: esp32, rtc
---


# Question
Title: 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);

```

# Answer
You can find examples of this sort of thing in the library's examples.

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

```
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 votes

---
Tags: functions, cpp
---


# Question
Title: 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?

# Answer
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.
> 1 votes

---
Tags: usb, emulation
---