message:
How to address arbitray leds (WS2812B) in an already defined leds array?

I want to address the first and last three pixels of a 9 pixel strip and apply a gradient to them using FastLED.  I can successfully address them but the colors displayed are not correct.  Is there something I'm overlooking or misunderstand about the way FastLED works?

    #include <FastLED.h>

    // the whole strip
    #define NUM_LEDS 9

    #define LED_PIN 6

    CRGB leds[NUM_LEDS];

    // Define the indexes of the first and last 3 indexes of a 9 pixel strip
    int customLeds[6] = {0,1,2,6,7,8};

    // My Palette
    DEFINE_GRADIENT_PALETTE (heatmap) {
      0, 255, 0, 0,      // Red
      128, 0, 255, 0,    // Green
      255, 0, 0, 255     // Blue
    };

    CRGBPalette16 myPalette1 = heatmap;

    void setup() {
      FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
      FastLED.setBrightness(20);
    }

    void loop() {

      for (int i = 0; i < (sizeof(customLeds)); i++) {
       // Each i led get the correct color given their place in the array  - 0, 42.5, 85, 127.5, 170, 212.5, 255
        leds[customLeds[i]] = ColorFromPalette(myPalette1, (i * (255 / sizeof(customLeds))), 255, LINEARBLEND);
      }

      FastLED.show();

    }

body:
So here is the answer I came up with:

    #include <FastLED.h>

    // the whole strip
    #define NUM_LEDS 9

    #define LED_PIN 6

    CRGB leds[NUM_LEDS];

    // Define the indexes of the first and last 3 indexes of a 9 pixel strip
    bool customLeds[9] = {1, 1, 1, 0, 0, 0, 1, 1, 1};
    int customLeds_num = 6;

    // My Palette
    DEFINE_GRADIENT_PALETTE (heatmap) {
      0, 255, 0, 0,      // Red
      128, 0, 255, 0,    // Green
      255, 0, 0, 255     // Blue
    };

    CRGBPalette16 myPalette1 = heatmap;

    void setup() {
      FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
      FastLED.setBrightness(5);

    }

    void loop() {

      FastLED.clear();

      //  Keep track of how many leds have been lit
      int customLedIndex1 = 0;

      for (int i = 0; i < NUM_LEDS; i++) {
        // Each i led get the correct color given their place in the array  - 0, 42.5, 85, 127.5, 170, 212.5, 255

        //lights a specific pixel only if it's in the customLeds truth table
        if (customLeds[i]) {
          // works out where on the gradient a specific pixel is
          leds[i] = ColorFromPalette(myPalette1, (customLedIndex1 * (255 / 5)), 255, LINEARBLEND);

          //increments the index for the next pixels value on the gradient
          customLedIndex1++;

        }

      }

      FastLED.show();

      customLedIndex1 = 0;

    }

The solution involved using a boolean array that indicates which leds needed to be on (true / 1) and which off (false / 0) and then create a separate index (customLedIndex) which counted how many of the leds where lit so they could receive the correct color corresponding to their 'place' in the palette


sender: user

message:
Initializing an object as class member resulting in linking error?

I'm a little dumbfounded as to why this isn't working. I keep getting the following linker error:
``` cpp
In file included from src\ac.cpp:1:0:
src/ac.h:9:21: error: expected identifier before numeric constant
 #define RECEIVE_PIN 0
                     ^
src/ac.h:14:26: note: in expansion of macro 'RECEIVE_PIN'
     static IRrecv irrecv(RECEIVE_PIN);
                          ^
src/ac.h:9:21: error: expected ',' or '...' before numeric constant
 #define RECEIVE_PIN 0
                     ^
src/ac.h:14:26: note: in expansion of macro 'RECEIVE_PIN'
     static IRrecv irrecv(RECEIVE_PIN);
                          ^
*** [.pio\build\esp32cam\src\ac.cpp.o] Error 1
*** [.pio\build\esp32cam\src\main.cpp.o] Error 1
```

I am simply trying to initialize the IR receiver with `static IRrecv irrecv(RECEIVE_PIN);`, but the compiler is refusing to link it together.

``` cpp
#ifndef _AC_H_
#define _AC_H_

#include <Arduino.h>
#include <IRremoteESP8266.h>
#include <IRrecv.h>
#include <IRutils.h>

#define RECEIVE_PIN 0

class IR
{
public:
    static IRrecv irrecv(RECEIVE_PIN);
    static decode_results results;
    void initRecv();
    bool waitForIR();
};

extern IR ir;

#endif
```

If I do `static IRrecv irrecv;` it successfully compiles, but I'm unsure if I can pass the pin variable after the fact.

sender: assistant

body:
Static data members have to be defined _outside_ the class declaration.
The initialization happens at the point where the members are defined:

**file ac.h:**

```c++
//...

class IR
{
public:
    // Static data members are declared only:
    static IRrecv irrecv;
    static decode_results results;
    void initRecv();
    bool waitForIR();
};
```

**file ac.cpp:**

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

#define RECEIVE_PIN 0

// Definitions and initializations of static data members:
IRrecv IR::irrecv(RECEIVE_PIN);
decode_results IR::results;
```


message:
passing variable to function

I have the following code to turn on or off led. I would like to modify the function to pass the pin as well. what should X be substituted with?

    #define BIN_LED 2
    #define PIN_LED 3

    void led(uint8_t x, bool on) {
  digitalWrite(x, on ? LOW : HIGH);
    }

    void setup() {}

    void loop() {
     led(BIN_LED, true);
     delay(1000);
     led(BIN_LED, false);
     delay(1000);
    }

body: You've done it. All that's left is to specify a data-type 'X' in the function declaration, just as you've already done for 'on'. 'uint8_t' would be a reasonable choice.


message:
On a custom ESP32-based PCB, I can' flash anymore after the first successful firmware flash

I have designed and manufactured a custom PCB, with an ESP32 chip on it.
I use my FTDI cable to upload my firmware.
I have no problem to flash my firmware, and it runs with no problem. So far so good.
But then, any successive attempts to flash again is a dead end as it results into a timeout (of course I still press the boot button on my PCB).

If I take a new PCB, the first flash is OK but I cannot do it again.

Note: to make thing as simple as possible, I simply use the Arduino IDE and my do-nothing code as my firmware replacement:

```C

void setup() {
  Serial.begin(115200);
  //Serial.setDebugOutput(true);
  Serial.println("Yo from SDL!");
}

// the loop function runs over and over again forever
int _loop = 1;

void loop() {
  Serial.print("Loop #");
  Serial.println(_loop++);
  Serial.println();
  delay(3000);
}
```

[UPDATED] Here is the schematic regarding the ESP32 and the GPIO0, GPIO2:

[The schematic of the PCB regarding the boot loader](https://i.stack.imgur.com/3mDkP.jpg)

Do you have any clue?!

body:
IO2 needs to be connected to a pulldown resistor (your buzzer FET has a pulldown on its input which does the job, which is fortunate). I would consider moving the buzzer elsewhere and keeping IO2 just for the pulldown resistor if possible.

IO0 needs a pullup resistor.

You need some way of resetting the ESP32 through pulling the EN pin low when you want to reprogram it.

Both IO0 and the EN pin are usually controlled through a combination of the DTR and RTS pins of the USB to UART adapter to do the resetting automatically. Without that you will have to manually hold IO0 LOW while briefly pulling EN low to reset the chip.


message:
Send same telemetry data to two different serial ports?

I'm using a Teensy 3.5 to control a wall-following robot. The robot sends telemetry to my PC via two independent ports - Serial1 & Serial.  Serial is the normal USB port, used when I direct-connect to the robot for troubleshooting, etc. Serial1 is tied to an HC-05 Bluetooth transceiver and it is used to acquire telemetry remotely.

I have to send telemetry to both ports, because I never know which (or either, or both) port(s) are actually active at any one time, so I wind up with lines like the following all over my code:

    Serial.printf("\nChecking for MPU6050 IMU at I2C Addr 0x%x\n", MPU6050_I2C_ADDR);
    Serial1.printf("\nChecking for MPU6050 IMU at I2C Addr 0x%x\n", MPU6050_I2C_ADDR);

needless to say this gets old after a while, and is error prone (I might edit one line and forget to copy/paste it to the other one).  What I would really like to do is create a function that would accept a printf-style string and send it to both ports, but I'm having trouble figuring out how to do that.

I have tried playing around with strcpy and strcat without much success:

      char quotestr[] = "\"";
      char hellostr[] = "hello";
      char instr[] = "%s\n, hellostr";
      char deststr[40];
      memset(deststr, 0, sizeof(deststr));
      strcat(deststr, quotestr);
      strcat(deststr, instr);
      strcat(deststr, quotestr);
      Serial.printf("quotestr = %s\n", quotestr);
      Serial.printf("instr = %s\n", instr);
      Serial.printf("deststr = %s\n", deststr);
      Serial.printf(deststr);

But the output is wrong because the '\n' gets interpreted as a CRLF pair even though it is in a string with double-quotes.

    quotestr = "
    instr = %s
    , hellostr
    deststr = "%s
    , hellostr"
    "
    , hellostr"

It seems like there ought to be a way to do this easily, but I can't figure it out.  Any help would be appreciated.

TIA,

Frank

body:
you can write a simple T output using the base class `Print`. The standard Arduino `Print` class doesn't have `printf` but from your code it looks like the Teense core has `printf` in `Print`.

```
class TeePrint: public Print {

  Print &out1;
  Print &out2;

public:

  TeePrint(Print &_out1, Print &_out2) : out1(_out1), out2(_out2) {}

  virtual size_t write(uint8_t b) {
    out1.write(b);
    out2.write(b);
    return 1;
  }

};

TeePrint log(Serial, Serial1);

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

  log.printf("abcd %d %s", 1234, "xyz");
}

void loop() {

}
```


body:
The simplest method is a variadic macro:

```c++
#define PRINTF(...) do { Serial.printf(__VA_ARGS__); Serial1.printf(__VA_ARGS__); } while(0)
```

Then you can just use `PRINTF("foo: %d", bar);` and it will expand it out to the two printfs for you.


message:
Serial hangs on Arduino-Uno

I'm having issues with Arduino and RPI3 serial communication, it'll become unresponsive after a little time. Tried increasing BAUD rate and same issue, also happens on Windows as well so RPI is not at fault, and even after increasing the `delay` the hang still happens.

RPI3 python code

<!-- language: python -->
```
import serial
import time

if __name__ == '__main__':
  ser = serial.Serial('/dev/ttyACM0', 115200, timeout=1, writeTimeout=0)
  ser.flush()
  last = "on\n"

  while True:
    last = "on\n" if last == "off\n" else "off\n"
    ser.write(last.encode())
    print(last)
    time.sleep(0.5)
```

Arduino code

<!-- language: c++ -->
```
#define BAUD_RATE 115200
const int LED_PIN = 8;
String command;

void setup() {
  Serial.begin(BAUD_RATE);
  pinMode(LED_PIN, OUTPUT);
  delay(100);
}

void loop() {
  Serial.println("I was written in RPI");

  if (Serial.available()) {
    command = Serial.readStringUntil('\n');

    if (command.equals("on")) {
      digitalWrite(LED_PIN, HIGH);
    } else if (command.equals("off")) {
      digitalWrite(LED_PIN, LOW);
    }
  }

  delay(50);
}
```

after less than a minute I'll get this exception from python

`BlockingIOError: [Errno 11] Resource temporarily unavailable`

The Arduino TX and RX led's stay on when it becomes unresponsive rather than flashing like it normally does.

body:
You are flooding the RPi/PC with `"I was written in RPI"` and don't read it. It will work if you read `ser` regularly.

On the delays: A message over a serial line has a transmission time, in your case 20 characters at 115200 baud from Arduino to RPi/PC. With the common 8n1 protocol, characters are sent at 11520 per second. With 20 characters this will take nearly 0.002 seconds, or 2 ms. The receiver needs a smaller delay than the sender to avoid overflows.

If the Arduino were using the USB directly (AFAIK it does not, between its USB interface and the actual AVR is a "real" serial line), the baudrate does not matter. A virtual serial line over USB is always really fast, independent of the announced baudrate. I once used 921600 baud with success. ;-) The baudrate is only used if a real serial line is involved.


message:
Continuous servo motor won't stop rotating

I want to use Bluetooth to control my continuous servo motor to rotate 360° once, and I used MIT app inventor for the UI to control it.

My continuous servo motor won't stop rotating even though I tried `myservo.write(90)`.

I was wondering if anything is wrong with my hardware, or whether the problem is in my code as I am a beginner at coding and I put different functions together that I found on the internet (I was trying to make the MIT to send letters to the Arduino code where the letter would activate a command to the servo).

Here's my code:

    #include <SoftwareSerial.h> // TX RX software library for bluetooth

    #include <Servo.h> // servo library
    Servo myservo; // servo name

    int bluetoothTx = 10; // bluetooth tx to 10 pin
    int bluetoothRx = 11; // bluetooth rx to 11 pin

    SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

    void setup() {
      myservo.attach(9); // attach servo signal wire to pin 9
      // Setup usb serial connection to computer
      Serial.begin(9600);
      myservo.write(90);  // set servo to mid-point

      // Setup Bluetooth serial connection to android
      bluetooth.begin(9600);
    }

    void loop() {
      // Read from bluetooth and write to usb serial
      if (bluetooth.available() > 0 ) { // receive number from bluetooth
        int servopos = bluetooth.read(); // save the received number to servopos
        Serial.println(servopos); // serial print servopos current number received from bluetooth

        char c = Serial.read();
        if (c == 'a') {
          myservo.write(180);
          delay(1000);
          myservo.write(90);
        }
        else if (c == 'b') {
          myservo.write(90);
        }
      }
    }

[![Here's how i set my arduino board][1]][1]

[![And the MIT App inventor code][2]][2]

  [1]: https://i.stack.imgur.com/xekK6.jpg
  [2]: https://i.stack.imgur.com/AZKU1.png

Would be really great if you could help

body:
A "[continuous servo][1]" is one in which it stops rotating when the angle is set to 90 degrees, rotates forward when the angle is more than 90 degrees and rotates in reverse when the angle is less than 90 degrees.  The further from the angle of 90 degrees, the faster the continuous servo will rotate.

You can not control the angle of a continuous servo.  There is no feed back to know when it has rotated, say, 360 degrees.

You can only guess at the timing and send a command like "go to angle 100" to start rotating a continuous servo slowly forward then send a command like "go to to angle 90" to stop it after your "guessed at" time of how log it took to travel, say, a quarter the way around has elapsed.

[Here is a similar Stack Exchange question][2] where continuous servos are discussed as well.

  [1]: https://en.wikipedia.org/wiki/Servo_(radio_control)#Continuous-rotation_servos
  [2]: https://arduino.stackexchange.com/questions/1321/servo-wont-stop-rotating


message:
strcpy_P increases IROM usage by 400%

Using ESP8266 (NodeMcu 1) in Arduino IDE:

I can't upload my sketch because a single call to **strcpy_P** seems to increase the IROM usage by about 400%: 25% total usage without the call, 100+% with the call.

And even more strange, it depends on the second parameter of strcpy_P (the source):
If a pointer to a char array is provided, the usage increases dramatically

      char * ptr = (char *) pgm_read_word (&myArrays[index]);
      char buffer [1500];

      strcpy_P (buffer, ptr); // can't upload, uses 100+% of available IROM

Whereas with PSTR as parameter (just to test) total size of sketch is just 25% of IROM, leaving everything else unchanged:

      char * ptr = (char *) pgm_read_word (&myArrays[index]);
      char buffer [1500];

      strcpy_P(buffer, PSTR("Test")); // Ok, does not increase sketch size /IROM  usage

 What's going on here ?

body: I guess the problem is not the `strcpy_P` function, but your array. Without that function call, the entire array can be removed by the compiler (I presume it's not used anywhere else). As soon as you add code that definitely accesses it, it is included in the code and therefore increases the size of the program so much.


message:
Arduino pro mini sampling rate

what are the possible sampling rate the user can set in Arduino pro mini using ADCSRA registers.
I want to set  my desired sampling rate through registers, is it possible?

body:
The previous responders are correct; but, maybe some clarification may help. The data conversion rate determined by the ADCSRA register is the conversion rate of the hardware. There is no need to sample data readings faster than conversions are performed. Faster conversions show more jitter than slow ones. Your actual sample rate will usually depend more on the time it takes to run through your loops than on the conversion rate. Arduino library code is usually not the optimum choice for speed.

When you change the conversion rate in the ADCSRA, be sure to avoid clobbering the other bits:

ADCSRA = (ADCSRA & 0xF8) | (newRate & 7);

If you are getting the hang of writing the control registers, you might want to use the ADC's operation complete interrupt to retrieve each reading. That eliminates loop times.


message:
Controlling Arduino through python

How to set the registers of Arduino through python code to vary the sampling rate of Arduino?
Can we control Arduino through python?

body:
If you mean can you run a python script on a "PC" and send messages to an Arduino then yes but you would need to write code that ran on the Arduino to receive messages from the "PC" and turn those into actions on the Arduino.

If you mean can you run a python script on an Arduino directly, well yes you can there are python implementations for Arduinos, but if you go down this route you need to remember you only have a small amount of memory and you are going off piste where there will be little or no help.

Honestly I would learn how to program the arduino in C++ and stick to that.


message:
Why do I get different times when using analogRead() inside while loop?

I have the following code which checks the latency of another board.

```c++
    int triggerPin = 13;
    int dataPin = 9;
    int ejectorPin = A0;
    unsigned long t_start = 0;
    unsigned long t_end = 0;
    unsigned long t_total = 0;
    int value = 0;

    void setup() {
      // put your setup code here, to run once:
      pinMode(triggerPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(ejectorPin, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      t_start = micros();
      while (value < 10 ) {
        digitalWrite(triggerPin, HIGH);
        digitalWrite(dataPin, HIGH);
        delay(5.0);
        digitalWrite(dataPin, LOW);
        digitalWrite(triggerPin, LOW);
        delay(1.0);
        value = analogRead(ejectorPin);
      }
      t_end = micros();

      t_total = (t_end - t_start);
      Serial.println(double(t_total) / 1000);
```

Note that I'm using `analogRead()` inside the while loop. With this method I get **18.3 msec**. However, if I use the `analogRead()` in the while condition:

```c++
    void loop() {
      t_start = micros();
      while (analogRead() < 10 ) {
        .
        .
        .
```

then I get **30.2 msec**. I thought assigning value of `analogRead()` to a variable would take longer but here it's the opposite.

**Can someone please explain the reason behind this behaviour?**

body:
Both of your examples use a while loop, so the while loop is not the issue.

An analogue read, with the prescalers unchanged, takes 104 µs. So, what you are really measuring is your 6 ms delays, plus a slight amount extra for the other code.

Since your first while loop necessarily takes 6+ ms, then you will naturally get a result which is a multiple of 6 ms. This appears to be happening, so you are getting two loops (18 ms). This doesn't prove a huge amount.

---

You need to read up on the [Nyquist frequency](https://en.wikipedia.org/wiki/Nyquist_frequency)

To get accurate sampling results you need to sample at twice the rate at which things change. Your first results may merely be the results of aliasing. Your 6 ms delays may cause you to take one sample on one transition, and another sample (maybe) a couple of transitions later. Thus your results are meaningless.


message:
A strange bug in my Arduino ALU

I have discovered a strange error in my Arduino. It's not in the code. I think it's a hardware bug in the ALU of the microcontroller, maybe in clone only.
So there is a variable called `feedLimit` and its value is 30, which doesn't really matter.
When I print the answer of feedLimit*30*1000 using this command `Serial.println(feedLimit*30*1000)`
The answer printed on the serial monitor is 30528, which is obviously incorrect. But when I print feedLimit*30000, the answer is correct (300000). The answer should be the same in both cases but it's not. I have attached the code as well as a screenshot of the output.
Can somebody please let me know if this is a bug in Arduino or something else? I have never experienced this kind of bug at the hardware level.
Thanks.

    int interval, interval2;

    int feedingTime = 3; //Must feed once every 3 minutes
    int feedLimit = 30;  //If fed 10 times or more within feedingTime span, the fiesh dies
    int dieAfter = 30;   //Will die if its not fed in 10 minutes
    int feedCounter = 0; //Counts how many time fed in feedingTime span

    void setup() {
      Serial.begin(9600);
      pinMode(btnPin, INPUT_PULLUP);
      pinMode(ledPin, OUTPUT);

      Serial.println(feedLimit);
      Serial.println(feedLimit*60*1000);
      Serial.println(feedLimit*60000);
    }

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

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

body:
This is not a bug. It's just that you are working with signed 16 bit integers on an 8 bit microcontroller. The maximum an `int` can store is 32767, and literals are 16 bit signed by default.

Your three prints are:

```c++
  Serial.println(feedLimit);
```

Print 30.

```c++
  Serial.println(feedLimit*60*1000);
```

Multiply  `feedLimit` by 60 = 1800. Multuply 1800 by 1000 = 1800000. Fit 1800000 into 16 bit signed = 30538. Also works the other way: preprocessor multiplies two 16 bit ints to create a new 16 bit int constant: 60 * 1000 = 60000, which is too big to fit in an int and truncates to 27232. Multiply by 30 = 30538 when truncated to 16 bits.1

```c++
  Serial.println(feedLimit*60000);
```

Multiply 30 by 60000. 60000 is too big to store in an int so it is implicitly promoted to a long. 30 * 60000 = 1800000. The result is a long because you have an implicit long in your calculation.

You have to take care with big numbers on small microcontrollers and keep in mind the limits of each variable type, along with what the default data type for literals is.

* char: -128 to +127
* unsigned char / byte: 0 to 255
* int: -32,768 to +32,767
* unsigned int: 0 to 65,535
* long: -2,147,483,648 to 2,147,483,647
* unsigned long: 0 to 4,294,967,295

You can force literals to be a specific data type by adding a suffix to them:

* L: Long
* UL: Unsigned long

(There are others too but less often used).

So your first (failed) calculation can be fixed by forcing one of the values to be a long:

```c++
  Serial.println(feedLimit*60*1000L);
```

----

1: It seems avr-gcc isn't clever enough to do this, instead it's always treating each operation separately, and each time it works from int-to-int using two 8-bit registers to represent each value or result.


message:
How does Arduino board separate USB traffic (uploading code vs. communication)?

A beginner in Arduino programming here (learning Arduino programming while waiting for my board to arrive).

I am trying to understand how Arduino board is able do these two things using only one USB port it has:
1. receive compiled code from a PC (from Arduino IDE: Sketch > Upload)
2. serial communication between a PC application and the Arduino board (e.g. our own Windows application communicates with the Arduino board)

I just cannot wrap my mind around how does it distinguish between these two cases. I have used boards which have 2 USB ports: one is for programming (uploading your code) and the other one is for serial communication between any PC application and the board.

In my opinion there has to be some way for Arduino to detect when is it being flashed, and when is it being used as a regular serial port.

body:
It doesn't distinguish anything. It's all down to what code is running on the board at any moment.

When you reset or power up the bootloader runs. It listens for uploaded code. If it doesn't get an upload signal from the pc after a short timeout it starts executing your code instead.


message:
Arduino as Multiplexer

[![enter image description here][1]][1]This is a kind of an experiment, I just have a question on how Arduino ports work. Consider this sample: there is this target device that I'm trying to control with Arduino. The device uses a typical scanned keyboard (8 output columns and 5 input rows which make contact whenever a user presses a key). I am trying to emulate that keyboard with Arduino. Of course, a standard way to do it would be to read 8 columns and produce appropriate output on the 5 rows. However, Arduino is not fast enough to make it work. So, I am going with multiplexer idea. 8 Arduino's digital pins are connected to columns and 5 Arduino digital pins are connected to rows. GND rail is NOT connected.

So the idea is this. By default all Arduino pins are set to INPUT in init() routine. Whenever I need to emulate a key press, I just set a corresponding row pin to OUTPUT and LOW, same for the column pin. So, that should work as some kind of a multiplexer, since Arduino pins are driven by Mosfets and input state is high impedance, and during output state both pins would be tied to Arduino's GND which makes a hardlink connection between them (setting to HIGH should work to, there's no difference).

Here is the test code which should make a keypress every 5 seconds:

    pinMode(ROW0_PIN,OUTPUT);
    digitalWrite(ROW0_PIN,LOW);
    pinMode(COLUMN0_PIN,OUTPUT);
    digitalWrite(COLUMN0_PIN,LOW);
    Sleep(5000);

    pinMode(ROW0_PIN,INPUT);
    pinMode(COLUMN0_PIN,INPUT);
    Sleep(5000);

Now, the thing IS working. However, it only works if *one* column pin is connected. When I connect any two pins, the target device stops responding. What I found is that actually, when I do

`pinMode(COLUMN0_PIN,OUTPUT);digitalWrite(COLUMN0_PIN,LOW);`,

the neighboring pins somehow get activated too, which results in all column outputs connected together and sending signal to row inputs.

If all pins are set to INPUT, it works fine, meaning, no connection between rows and columns.

My qustion is: why is it happening? Let me rephraze it: somehow setting a digital pin to OUTPUT makes other digital pins lose their high impedance state, although all of them are set to input. I haven't checked if this is happening within a hardware port or not, just consider schematics, please.

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

body:
I have no certainty about what is happening, but I suspect you are
seeing the effects of the input clamping diodes. Each digital pin has
clamping diodes that keep its potential between GND and Vcc, ±the diode
threshold.

* As long as all pins are set to `INPUT`, they can freely float with
  respect to one another, provided the potential differences stay within
  Vcc+2×diode\_threshold.

* When you set one pin to `OUPUT` `LOW`, you are tying to to GND. The
  other pins can still float _above_ this one, but only very slightly
  _below_ it. The clamping diodes provide unidirectional current paths
  from this pin (which is now GND) to every other pin.


message:
Why is the IR transmitter tied to one pin

I'm using IRremote.h  (https://github.com/Arduino-IRremote/Arduino-IRremote).  The receiver allows you to change the pin it is connected to but the transmitter does not.  Is there any reason why this is hardcoded in IRremoteInt.h.  If it just a PWM pin, can't any PWM pin be used?

    #if defined(CORE_OC2B_PIN)
    #define TIMER_PWM_PIN        CORE_OC2B_PIN  /* Teensy */
    #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    #define TIMER_PWM_PIN        9  /* Arduino Mega */
    #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
    #define TIMER_PWM_PIN        14 /* Sanguino */
    #else
    #define TIMER_PWM_PIN        3  /* Arduino Duemilanove, Diecimila, LilyPad, etc */
    #endif

There is not much documentation on this.

body:
Got to the bottom of it.  As mentioned in the comments, this is tied to the timers.  The list is given in [Secrets of Arduino PWM][1].  The code can be changed to use a different timer but it will still be tied to a specific pin.

  [1]: https://docs.arduino.cc/tutorials/generic/secrets-of-arduino-pwm


message:
No SPIFFS data upload in Arduino IDE 2.0.0-rc3 (ESP32 & TTGO) - Ubuntu

I tried adding ***esp32fs.jar*** to ***/home/myname/Arduino/tools/ESP32FS/tool*** (and a few other places as it looked likely that the jar file wasn't loading).  I've definitely got the correct board selected, and can upload Sketches.  I can also run the demo that writes to SPIFFS.

But the Tools menu doesn't have an option for ***ESP32 Sketch data upload***.

Is SPIFFS data upload not available so far in V2?

body:
FS upload plugins for ESP are not available in IDE 2 yet (2022-01-07).

IDE 2.0 doesn't run on Java so it can't use the java plugins of the IDE 1. You have to use IDE 1 for FS upload and exception decoder until new plugins are written for IDE 2.

It is tracked here: [https://github.com/arduino/arduino-ide/issues/58][1]

  [1]: https://github.com/arduino/arduino-ide/issues/58


body:
I've created a utility that provides a web-based ESP32 interface for

* OTA
* File system formatting
* FS directory listing
* File uploading
* File editing
* File deletion

It can be found at https://github.com/palmerr23/ESP32-OTA-and-File-Manager


message:
Why is my SPI clock voltage lower at higher frequencies?

I measured that the SPI-Clock of my Arduino Nano in my project didn't reach near 5V. So I quickly tested with a new one, nothing attached except a (mydaq) scope.

I measured the SPI clock:
2.5 V @ 8 Mhz;
3.6 V @ 4 Mhz;
5 V @ 1 Mhz.

I think the graph looks like that because the low max sample of the mydaq, so I dont worry to much about that. The MISO could reach about 5V but why is the clock voltage lower at higher frequencies? And how to reach 5V?

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

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

    #include <SPI.h>

    void setup() {
      SPI.begin();
      SPI.beginTransaction(SPISettings(8000000, MSBFIRST, SPI_MODE0));
    }

    void loop() {
      SPI.transfer(1);
    }

I also tried SPI mode 2 or 3 @8Mhz, idle state was 4,7 V but Vp-p again only 1,9 V.

body:
This is the second time the [Nyquist frequency](https://en.wikipedia.org/wiki/Nyquist_frequency) has come up in the last couple of days.

In order to accurately measure a changing signal, like you are doing, you need to sample at, at least, twice the frequency of the signal. If you don't your samples may give incorrect results because you are sampling partway up or down the curve.

To measure an 8 MHz signal, you therefore need to sample at 16 MHz, which you don't appear to be doing.


body:
According to the MyDAQ specifications the analogue input has a pass-band filter of "DC to 400kHz". That means that at 400kHz the signal will be reduced by -3dB, and anything above that will be reduced even further, and the higher the frequency the more it will be reduced.

Further to that the MyDAQ samples at up to 200ksps, which means it can only capture a maximum frequency component of 100kHz.

The MyDAQ is little more than an educational toy. It's just a glorified sound card and really not worth wasting your time with.


message:
Arduino Pro Mini doesn't align nor connect in fritzing

When using fritzing (0.9.6) I notice that the Arduino Pro Mini 3.3 V component doesn't align nor connect to breadboard pins like other components.

Is this a bug or a feature?

I've tried to wiggle the board/component, disable/enable 'Align to Grid', but this doesn't help.

For comparison, a PIC or M1 blue pill aligns/connects fine, even after rotating both the board and components.

**Update:** To illustrate the issue:

[![fritzing screenshot][1]][1]

Note on the left how the Arduino Mini Pro doesn't connect and doesn't align, i.e. its pins are between the rows.
For comparison, on the right a blue pill whose pins do align and auto-connect.

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

body:
The Pro Mini component you try to use in Fritzing has a bug in alignment possibly because of position units not specified.

You can fix it by editing the source code of the component as mentioned in this Fritzing forum thread: [https://forum.fritzing.org/t/pins-not-aligning-with-board/9142/4][1]

  [1]: https://forum.fritzing.org/t/pins-not-aligning-with-board/9142/4


body:
**Short Answer...**

I’m not an expert on the [Fritzing][1] sketch tool, however I’ll guess that the graphical anchor point on the board component shown in your question has been specified incorrectly and that if that bug was corrected, the long edge pins would snap to a breadboard component the same way as your comparative example. Noting that this would almost certainly leave some internal or short edge pins out of alignment with the breadboard grid (depending on the component PCB layout).

**More information ...**

(I'm pretty sure OP already knows this, but adding for a more generally usable answer)

[Arduino Pro-mini][2] was designed for “installations where space is premium and projects are made as **permanent set ups**”. *Some* of the design choices can be somewhat incompatible with [breadboard][3] which has a 0.1” (2.54mm) pitched square grid either side of a 0.3” (7.6mm) centre notch.

The open-source Pro-mini board has been immensely popular and there are many versions of PCB layout in circulation. Just three examples are shown below. There are many more.

[![Generic, two pins inboard][4]][4]
[![Sparkfun, four pins inboard][5]][5]
[![Generic, no inboard pins, all edges polulated][6]][6]

When [attaching headers][7] for breadboard use, various configurations of pin headers placed above or below the PCB are used to bring out (predominantly) the long edge connections for the breadboard, while allowing the others to be accessible by leads.
[![Example header configuration from instructables link][8]][8]

  [1]: https://fritzing.org/download/
  [2]: https://www.arduino.cc/en/pmwiki.php?n=Main/ArduinoBoardProMini
  [3]: https://en.wikipedia.org/wiki/Breadboard
  [4]: https://i.stack.imgur.com/mOUVf.png
  [5]: https://i.stack.imgur.com/sDB2U.jpg
  [6]: https://i.stack.imgur.com/KpHTb.png
  [7]: https://www.instructables.com/Pro-Mini-Assembly-Guide/
  [8]: https://i.stack.imgur.com/EoIAu.jpg


body:
Fritzing parts only auto-connect if some pins are declared as male. This can be checked by looking at the part's XML file (search for `<connector.*type=`) or by opening the part in the 'new parts editor' (i.e. right-click->edit).

Note that it's ok for a part to have heterogeneous connector types. For example, male ones on the long sides and female ones on the short side. Which is what's used commonly with these parts, in reality. This is how for example the M1 Blue Pill or even the Arduino Pro Mini Rev13 (5V) Fritzing parts are defined, which thus auto-connect fine, as expected.

One can only speculate why the Arduino Pro Mini Rev14 (8 MHz/3.3 V and 16 MHz/5 V) parts were defined differently. Might be a bug or a deliberate design choice. However, for being a deliberate choice it would be only consequential to also draw female up-facing headers on the underlying SVG (cf. the Arduino UNO part, where this is done).

---

To work around this, one can edit the part, change all the connector types on the long sides from female to male and save it as new part - say - using the 'new parts editor', directly inside Fritzing. After that change the new part shows up under the 'MINE' parts category.

After that change the part auto-connects to the bread-board. However, the alignment is still broken, thus, for auto-connection one has to disable View->'Align to Grid'.

---

So to also fix the alignment some more sophisticated part editing is necessary.


body:
There is a mostly corrected part available here:

https://forum.fritzing.org/t/arduino-mino-pro-3-3-v-doesnt-align-connect/15221/2

as noted it needs more corrections before being added to core parts (which will also require obsoleting the current part.)


message:
'PinStatus' does not name a type

I bought an "off-brand" [ESP32 board][1]. I can upload blinky without a problem using platformio with the following `platformio.ini` file:

```ini
[env:humidious]
platform = espressif32
board = nodemcu-32s
framework = arduino
```

However, as soon as I add `lib_deps = grafana/PrometheusArduino@^0.3.0` the compiler throws the following errors:

```log
In file included from .pio/libdeps/humidious/WiFiNINA/src/WiFiStorage.h:23:0,
                 from .pio/libdeps/humidious/WiFiNINA/src/WiFi.h:38,
                 from .pio/libdeps/humidious/PromLokiTransport/src/clients/ESP32Client.h:7,
                 from .pio/libdeps/humidious/PromLokiTransport/src/PromLokiTransport.h:8,
                 from .pio/libdeps/humidious/PrometheusArduino/src/PromClient.h:4,
                 from .pio/libdeps/humidious/PrometheusArduino/src/PrometheusArduino.h:5,
                 from src/main.cpp:4:
.pio/libdeps/humidious/WiFiNINA/src/utility/wifi_drv.h:293:12: error: 'PinStatus' does not name a type
     static PinStatus digitalRead(uint8_t pin);
```

It was suggested on another thread that the board was out of date, but updating this didn't help.

Adding `typedef int PinStatus` before `#include <PrometheusArduino.h>` didn't help either.

  [1]: https://www.amazon.co.uk/gp/product/B07VJ34N2Q/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&th=1

body:
The problem here is that PlatformIO is picking up the wrong WiFi library. It has decided that the WiFi.h provided by WiFiNINA is the correct one to use, rather than the WiFi.h provided by the ESP32's bundled WiFi library.

You could try removing all traces of the WiFiNINA library from your PlatformIO installation, or maybe you need to manually specify which WiFi library should be used to preempt the autoselection routine.

I don't know how you do that in PlatformIO.


body:
What Majeko said was correct. PIO was using WifiNINA instead of the ESP32's WiFi library. To solve this, I added `lib_ignore = WiFiNINA` to `platformio.ini` and `#include <WiFi.h>` before including the prometheus libraries in `main.ino`.

I tested this by pointing PrometheusArduino at my desktop with [this example](https://github.com/grafana/prometheus-arduino/blob/main/examples/prom_01_local/prom_01_local.ino):

```
$ ncat -l 9090
POST /api/prom/push HTTP/1.1
Host: 192.168.0.45
Content-Type: application/x-protobuf
Content-Encoding: snappy
User-Agent: prom-arduino/0.2.2
Content-Length: 209

F

%
__name__uptime_milliseconds_total

job
esp32-test

hostD   @/@%@<@@/

heap_free_bytes
0

foobar
        0xA6..(0xA/
```


message:
Atmega2560 PWM on PH4

I am trying to convert the following code to output to pin 7 (PH4, OC4B) on an Arduino Mega. The code outputs to pin 6. This code is from a GitHub for the GRBL on the Mega "https://github.com/fra589/grbl-Mega-5X" out of the cpu_map.h It is clear that PH6 and PH7 are on the same PORTH but I just do not know what bits need changing to get GRBL to output on pin 7.Any help would be welcome.

~~~lang-cpp
#elif defined (SPINDLE_PWM_ON_D6)

    // Set Timer up to use TIMER4C which is attached to Digital Pin 6 - Ramps Servo 2
    #define SPINDLE_PWM_MAX_VALUE     255.0 // Translates to about 1.9 kHz PWM frequency at 1/8 prescaler
    #ifndef SPINDLE_PWM_MIN_VALUE
      #define SPINDLE_PWM_MIN_VALUE   1   // Must be greater than zero.
    #endif
    #define SPINDLE_PWM_OFF_VALUE     0
    #define SPINDLE_PWM_RANGE         (SPINDLE_PWM_MAX_VALUE-SPINDLE_PWM_MIN_VALUE)

    //Control Digital Pin 6 which is Servo 2 signal pin on Ramps 1.4 board
    #define SPINDLE_TCCRA_REGISTER    TCCR4A
    #define SPINDLE_TCCRB_REGISTER    TCCR4B
    #define SPINDLE_OCR_REGISTER      OCR4A
    #define SPINDLE_COMB_BIT          COM4A1

    // 1/8 Prescaler, 16-bit Fast PWM mode
    #define SPINDLE_TCCRA_INIT_MASK (1<<WGM41)
    #define SPINDLE_TCCRB_INIT_MASK ((1<<WGM42) | (1<<WGM43) | (1<<CS41))
    #define SPINDLE_OCRA_REGISTER   ICR4 // 8-bit Fast PWM mode requires top reset value stored here.
    #define SPINDLE_OCRA_TOP_VALUE  0xFF // PWM counter reset value. Should be the same as PWM_MAX_VALUE in hex.

    // Define spindle output pins.
    #define SPINDLE_PWM_DDR   DDRH
    #define SPINDLE_PWM_PORT  PORTH
    #define SPINDLE_PWM_BIT   3 // MEGA2560 Digital Pin 6
~~~

body:
You want to replace pin 6 (PH3, OC4A) with pin 7 (PH4, OC4B). There are
three things you have to change. First, the output compare register,
which is OCR4A for pin OC4A and OCR4B for pin OC4B. Thus:

```diff
-#define SPINDLE_OCR_REGISTER      OCR4A
+#define SPINDLE_OCR_REGISTER      OCR4B
```

Then, the configuration bit that enables the output:

```diff
-#define SPINDLE_COMB_BIT          COM4A1
+#define SPINDLE_COMB_BIT          COM4B1
```

Last, the bit to set in the data direction register, which is 3 for PH3
and 4 for PH4:

```diff
-#define SPINDLE_PWM_BIT   3 // MEGA2560 Digital Pin 6
+#define SPINDLE_PWM_BIT   4 // MEGA2560 Digital Pin 7
```

Note: as in _diff -u_ format, the prefix `-` means “remove this”, the
prefix `+` means “add this”.


message:
Having issues Connecting to a web server and pulling the data back

I have some arduino code where I am trying to pull information from four different locations.  Three are working great and the fourth I am not getting any response.

These two strings work perfect in a browser and I get the proper data response.
http ://10.196.1.163:8086/query?db=Garden&q=SELECT * FROM "Station" WHERE station = 61 ORDER BY DESC LIMIT 1
Or
http://10.197.1.57:8086/query?db=Garden&q=SELECT * FROM "Station" WHERE station = 91 ORDER BY DESC LIMIT 1

> {"results":[{"statement_id":0,"series":[{"name":"Station","columns":["time","altitude","humid","moist","press","rainfall","soiltemp","station","temp","type","vbat","winddir","windspeed"],"values":[["2022-01-08T21:13:58Z",1269,29.2,0,28.5,0,0,91,73.4,9,4.32,0,0]]}]}]}

The code below is what I am trying to use.  It appears to make the connection but brings nothing back.

What I see in the console is:

      19:55:42.024 -> Starting connection to server: 10.196.1.163 InfluxDB Garden DB...
      19:55:42.024 -> connected to server
      19:55:42.024 ->

The next line is starting to connect to the next server which brings back the JSON data fine.
I have been assuming that I was having issues because of the alternate port 8086 I was connecting to, but I am not sure.  I have been looking and finding examples similar to what I am doing.

I must be just missing something, but I am not sure what. I have been working off and on for this issue for a couple of months.

    void getLocalDataQuery2() {
   Serial.println("\nStarting connection to server: 10.196.1.163 InfluxDB Garden DB...");
   if (client.connect(server2, 8086)) {
  Serial.println("connected to server");
  client.print("GET /query?");
  client.print("db=Garden");
  client.println("&q=SELECT * FROM "Station" WHERE station = 91 ORDER BY DESC LIMIT 1");
  client.println("Host: 10.196.1.163");
  client.println("Connection: close");
  client.println();
   } else {
  Serial.println("unable to connect");
  while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
    // unsuccessful, retry in 4 seconds
    Serial.print("failed ... ");
    delay(4000);
    Serial.print("retrying ... ");
  }
   }
   String line = "";

   while(client.available())
   {
  line = client.readStringUntil('\n');

  Serial.print("Line : ");
  Serial.println(line);
   }
 }

body:
A client doesn't receive data immediately after sending a request. So client.available() returns 0 at first and your `while` loop is skipped.

The `readStringUntil` is one of the functions which wait for the next byte until timeout (1 second by default). So you can call readStringUntil first and it will wait for the data to arrive.

One way would be to replace the `while` loop with a `do while` loop, but the `do while` loop is strange and even experienced programmers don't like to use it.

In real application the first line of a HTTP response is important, because it contains the response status. The rest of the response header lines can be skipped.

So why not add reading of the first line before the `while` loop? This way `readStringUntil` will wait for the response and read the first line.

```
  String line = client.readStringUntil('\n');
  line.trim();
  Serial.print("Status line : ");
  Serial.println(line);

  while (client.available())
  {
    line = client.readStringUntil('\n');
    line.trim();
    Serial.print("Line : ");
    Serial.println(line);
  }
```


body: My solution to this was to setup a webserver running php code in a Docker container. The php code ran the influxdb query and sends the results


message:
ESP32 stack error when reading from BLE device

I'm using this code [here](https://gist.github.com/fffonion/72ba4996020f51d80c5915514d68ad0d) to read data from a BLE thermometer using an ESP32.

The code sometimes works fine and i can get the data:

    + Connect : a4:c1:38:69:0c:ff
     * Connected a4:c1:38:69:0c:ff
     + Found our service
     + Found our characteristic
     + Notify callback for characteristic ebe0ccc1-7a0a-4b0c-8a1a-6ff2997da3a6
    temp = 21.8 C ; humidity = 48.0 % ; voltage = 2.564 V
     * Disconnected a4:c1:38:69:0c:ff

Other times i get a CPU panic, related to a stack error:

    + Connect : a4:c1:38:69:0c:ff
     * Connected a4:c1:38:69:0c:ff
     + Found our service
     + Found our characteristic
     + Notify callback for characteristic ebe0ccc1-7a0a-4b0c-8a1a-6ff2997da3a6
    temp = 21.8 C ; humidity = 47.0 % ; voltage = 2.564 V
    Guru Meditation Error: Core  0 panic'ed (Unhandled debug exception)
    Debug exception reason: Stack canary watchpoint triggered (btuT)
    Core 0 register dump:
    PC      : 0x4000c472  PS      : 0x00060a36  A0      : 0x8012b791  A1      : 0x3ffcf7e0
    A2      : 0x3ffcf7f4  A3      : 0x00000000  A4      : 0x00000268  A5      : 0x3ffcfa14
    A6      : 0x3ffde1ad  A7      : 0x00000026  A8      : 0x8012987e  A9      : 0x3ffd0270
    A10     : 0x3ffdb99c  A11     : 0x3ffddca8  A12     : 0x3ffd050a  A13     : 0x00000001
    A14     : 0x00000004  A15     : 0x00000000  SAR     : 0x00000010  EXCCAUSE: 0x00000001
    EXCVADDR: 0x00000000  LBEG    : 0x4000c46c  LEND    : 0x4000c477  LCOUNT  : 0x00000003

    ELF file SHA256: 0000000000000000

    Backtrace: 0x4000c472:0x3ffcf7e0 0x4012b78e:0x3ffcf7f0 0x40129815:0x3ffcfa80 0x40125e62:0x3ffcfd10 0x401286e8:0x3ffcfd30 0x4012987b:0x3ffcffc0 0x40125e62:0x3ffd0250 0x401286e8:0x3ffd0270 0x4012987b:0x3ffd0500 0x40125e62:0x3ffd0790 0x401286e8:0x3ffd07b0 0x4012940a:0x3ffd0a40 0x40125e62:0x3ffd0a60 0x40129621:0x3ffd0a80 0x40125e62:0x3ffd0aa0 0x4012933d:0x3ffd0ac0 0x40129359:0x3ffd0ae0 0x40125e62:0x3ffd0b00 0x40125fa1:0x3ffd0b20 0x4012fb36:0x3ffd0b40 0x401042a6:0x3ffd0b60 0x4008ff9e:0x3ffd0b90

    Rebooting...

I'm using an ESP-WROOM-32 with PlatformIO, what could be the issue?

body: To help others. I resolved this issue by using the ArduinoBLE lib instead of the ESP32_BLE one I was using.


message:
Power saving configuration of unconnected pins

By default, all Arduino (ATmega328P) pins are [configured for input without the internal pull-up enabled][1]. This default seems to come from the AVR microcontroller itself.

When it comes to saving power - is this an optimal configuration for unused (and thus unconnected) pins?

Section 14.2.6 Unconnected Pins of the [ATmega328P datasheet][2] (page 88) recommends to configure pull-ups in order to save power:

> If some pins are unused, it is recommended to ensure that these pins have a defined level. Even though most of
the digital inputs are disabled in the deep sleep modes as described above, floating inputs should be avoided to
reduce current consumption in all other modes where the digital inputs are enabled (Reset, Active mode and
Idle mode).

> The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. In this case,
the pull-up will be disabled during reset. If low power consumption during reset is important, it is recommended
to use an external pull-up or pull-down.

So I'm tempted to call something like

```
for (uint8_t i = first_unused_pin; i < 20; ++i)
    pinMode(i, INPUT_PULLUP);
```

during setup.

Although, I don't understand where an increased power-consumption would come from when the INPUT pin is unconnected and no pull-up is active. I mean, since the pull-up is connected to VCC, there definitely is some current flowing, whereas without the pull-up I don't see where current would flow, since the pin is unconnected ...

However, Nick Gammon reports in his [extensive article on power saving techniques][3] (Section Configuring pins as inputs/outputs, Sketch D) an _increased_ power consumption when 6 unused pins are configured as inputs with internal pull-ups attached:

> All pins as inputs, and LOW (in other words, internal pull-ups disabled): 0.35 µA (same as before).
>
> All pins as inputs, and HIGH (in other words, internal pull-ups enabled): 1.25 µA.

So the datasheet's statements seem to conflict with these results.

Is this an error in the datasheet are am I missing something?

[1]: https://arduino.stackexchange.com/a/66655/13174
[2]: https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf
[3]: http://gammon.com.au/power

body:
Current is consumed when an input pin switches from HIGH to LOW or from LOW to HIGH. An unconnected "floating" input pin can change randomly depending on the local environment (EMI, noise, etc). That is unpredictable. The "it will consume more" is erroneous - it should be "it could consume more". The *could* is important, as I mentioned, it is unpredictable. By pulling up or down it is no longer unpredictable, as you have a defined steady state, and the input pin will not switch randomly.

Yes, you will get some leakage current through the pullup and the low-side MOSFET, but it is a defined predictable amount which you can incorporate into your design. If you want to reduce it then use larger external pullups (or pulldowns) to reduce the leakage current (note: using too large will start to encroach on the "floating" teritory again).

But when you're dealing with such small currents you're usually below the self-discharge equivalent current of your battery anyway, so saving a few nA isn't going to actually make the slightest bit of difference.


body:
The theory here is that an pin without a pull-up will probably float somewhere around the switching voltage. A bit of noise from the surroundings or whatever might push the pin up or down slightly, which will cause the internal circuitry to "flip" from high to low (or vice versa). All that flipping consumes quite a lot of power. The little tiny trickle from a pull-up resistor is so much smaller than the "flip cost" that it's worth using them.

I should also mention that it's very hard to test for a floating pin's consumption of power. Whenever you test it, you'll find it behaving very nicely, but as soon as you put it into a proper application it'll go crazy and won't work anywhere near your expectation. Putting in pull ups avoids this uncertainty, and lets you work with whatever the power consumption is when they're present.

I don't have the results any longer, but a while back I tried measuring the power consumption of the Arduino in various "idle" modes. The theory and practice did't match up terribly well.

It's possibly worth doing some tests, but IIRC, the lowest power setup was to set all pins as inputs and pull them low. In practice that's a lot of work to arrange, so setting them as inputs and using the internal pull-ups works nearly as well.

What you'll also find is that almost anything else will save far more power than the little trickle in the internal pull-ups. Here are some guides which might help:

* https://learn.sparkfun.com/tutorials/reducing-arduino-power-consumption/all
* https://www.makeuseof.com/tag/arduino-power-saving-tips/
* https://docs.arduino.cc/learn/electronics/low-power
* https://arduino.stackexchange.com/a/50734/26212


body:
> Although, I don't understand where an increased power-consumption would come from when the INPUT pin is unconnected and no pull-up is active.

This part of your question already has 2 answers, so I'll just answer the "power saving part".

The data sheet says "If some pins are unused, it is recommended to ensure that these pins have a defined level.". Configuring them with `pinMode()` to `OUTPUT`, then driving them `LOW` using `digitalWrite()` is perfectly acceptable, and MAY offer the greatest power saving / noise immunity of all.

If you look at "14.3 Alternate Port Functions" on page 89, you get a glimpse of the internal digital logic circuitry. When set to `OUTPUT`, the internal circuits provides a low impedance path to ground to sink current. What ever part of the internal circuitry that was "oscillating due to a floating input pin", causing the extra power consumption, is now connected to ground, or it's input is ignored, or how ever Microchip did it.

When you follow the I/O pin on Figure 14-2, it shows the `INPUT_PULLUP` circuitry at the top of the diagram, followed by the tri-state control lower down, then the `SLEEP` circuitry comprised of an analogue switch OR transmission gate if you prefer, inverter gate and N channel FET. When the Arduino is in some sleep modes, it "disconnects" the pin with the analog switch, and also grounds the Schmitt trigger input at the same time. What would be cool is if you could write "Arduino code" in the IDE to toggle this ON/OFF programmatically.

[![Figure 14-2][1]][1]

From the data sheet:

> 14.2.5 Digital Input Enable and Sleep Modes
>
> As shown in Figure 14-2, the digital input signal can be clamped to ground at the input of the Schmitt Trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller in Power-down mode, Power-save mode, and Standby mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to VCC/2.

The bottom line is, you don't want unused pins set as `INPUT` (Tri-state (Hi-Z) mode). See "Table 14-1. Port Pin Configurations".

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


message:
How many bits long,at most, is the seed in the randomSeed() function?

I can not find a concrete reference to how many bits long the (input) seed for the  randomSeed() function is for Arduino given here

https://www.arduino.cc/reference/en/language/functions/random-numbers/randomseed/

In the above webpage , though it is the official Arduino document for randomSeed(), it does not concretely say if the maximum bit length of the seed is 8,16 or 32 bits.

I think it is 16 bits long (in other words the seed is in the
range of integers 0 and 65535). So for example the maximum input to randomSeed would be expressed as randomSeed(65535).

But I do not know for sure if the seed input is 16 bits at most.
So my question is the seed used in randomSeed() 16 bit length at most  (thus having a maximum value of 65535).
32 bits is comparable to a 32bit windows desktop computers so I think 32 bits is too large for the input seed to randomSeed(). I am also using an Arduino Uno with Arduino IDE version 1.6.7 (if that matters regarding the input bit length of the seed).

body:
As stated on the page you link to:

> `seed`: number to initialize the pseudo-random sequence. Allowed data types: `unsigned long`.

Therefore it's 32 bits, since that is what `unsigned long` is.


message:
How to prevent an alarm which checks minutes from going off many times within one minute?

### How do I prevent an alarm, which checks if the current time matches an alarm time in hours and minutes, from going more than once within one minute?

I am using the DS3231 RTC module and RTClib from adafruit. I want to check if the current time equals to the alarm time, then set the `alarmFlag` variable. I want to clear `alarmFlag` when a button on pin D5 is pressed.

The code below works fine as long as I don't press the button within about a minute from the start of the alarm. If I press the button within about a minute from the start of the alarm, the alarmFlag will be 0 for one `loop()` cycle, but then (almost immediately, I don't have much in `loop()`) will be back to 1. I want for the button to stop the alarm completely, so it fires again only on the next day.

```
uint8_t alarm[2] = {19, 30}; // hour (24), minute

// other code ...

void loop() {

  currTime = rtc.now();

  // check if current time matches alarm time
  // if it matches, it matches for a whole minute, which is the problem here
  if (!alarmFlag && alarm[0] == currTime.hour() && alarm[1] == currTime.minute()) {
    alarmFlag = true;
  }

  // clear alarmFlag on button press (this is a shortened version, excuse the lack of debouncing/other stuff)
  if (digitalRead(5) == HIGH) {
    alarmFlag = false;
  }

}
```

Notes:
1. I can not use the RTC's built-in alarms because I need them elsewhere.
2. I don't want to just add `currTime.seconds() == 0` to the first `if` statement, because that would skip the alarm if the `loop()` cycle takes more than a second.
3. I know that the way I detect a button press in the example code is suboptimal, I wrote a better way to deal with this in my main code, but I don't want to clutter up this question.

body:
As suggested by the busybee, this is a textbook application of the
concept of [finite state machine][FSM]. Below is a state diagram that
hopefully captures the desired behavior. Its meaning is hopefully
obvious at first sight.

[![State diagram][1]][1]

Here your `alarmFlag` is replaced by the `TRIGGERED` state. Please note
that, with this state machine, the only way to turn the alarm off is to
press the button. If nobody is there to press it, is goes on forever.
This kind of issue is quite obvious when looking at the state diagram,
less so when looking at the code. This is why it is advisable to draw a
state diagram before you start coding. If this behavior is a not
desirable, you may add an extra transition out of the `TRIGGERED` state,
which would happen on a timeout.

It is also worth noting that, with this state machine, pressing the
button multiple times in quick succession has the same effect as
pressing it once. In other words, there is no point in debouncing the
button.

For implementing this in C++, I suggest you follow the steps of [this
tutorial on finite state machines][Majenko].

[FSM]: https://en.wikipedia.org/wiki/Finite-state_machine
[Majenko]: https://majenko.co.uk/blog/finite-state-machine

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


message:
Arduino diagrams

I would like to document some of the experiments I have been doing with the arduino.
 In many of the internet posts on Arduino projects, they have a similar diagram of the Uno or Mega with breadboards and resistors.  Some with more detail than others.  I've been looking at many of these articles to see if they mention what drawing package they are using but nobody seems to do so.

I could take one of them and just colour out the wires but I can't get the right shade of grey or green.

[![Arduino Uno][1]][1]

1) What diagramming tool can be used for drawing these diagrams?
2) Where can I get hold of a blank Arduino Mega/Uno/Nano template.

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

body:
As Juraj commented, those kinds of pictorial diagram are often made using a program called Fritzing.

You should also try producing a more traditional and useful diagram called a schematic. Fritzing can do that at the same time. There are also free programs that are better. See KiCAD, Eagle, EasyEDA etc.

You might find online emulators like Wokwa to be usefull.

---

Related:

Many of the [Rules and guidelines for drawing good schematics](https://electronics.stackexchange.com/q/28251/2191) also apply to Fritzing's pictorial diagrams.


message:
servo motor and l298n motor driver doesn't work together with esp32

so basically I am using 4 servo motors for our robotic arm and 1 l298n motor driver for 2 motor drive for base of the arm. when I individually tested robotic arm and controlled 4 servo motors, it worked perfectly fine, at the same time when i tested linear motion with motor driver individually it also worked fine. But when I combined them only servos are working but l298n doesn't. when I comment out servos.attach() line, then again motor driver works. Pins are different. That's why even I couldn't figure out why am i getting this issue.

    #include <WiFi.h>
    #include <WebServer.h>
    #include <Robojax_L298N_DC_motor.h>
    #include<Servo.h>

    WebServer server(80);
    Servo myservo,shoulder,elbow,wrist;
    int grippos=0,shoulderpos=0,elbowpos=0,wristpos=0;

    // motor 1 settings
    #define CHA 0
    #define ENA 19 // this pin must be PWM enabled pin if Arduino board is used
    #define IN1 18
    #define IN2 5

    // motor 2 settings
    #define IN3 15
    #define IN4 2
    #define ENB 4// this pin must be PWM enabled pin if Arduino board is used
    #define CHB 1

    const int CCW = 2; // do not change
    const int CW  = 1; // do not change

    #define motor1 1 // do not change
    #define motor2 2 // do not change

    String prev="";

    Robojax_L298N_DC_motor robot(IN1, IN2, ENA, CHA,  IN3, IN4, ENB, CHB);

    void gripopen()
    {
      Serial.println("open");
      grippos+=30;
      if(grippos>180)
      {
        grippos=180;
      }
      myservo.write(grippos);

    }

    void gripclose()
    {
      grippos-=30;
      Serial.println("close");

      if(grippos<0)
      {
        grippos=0;
      }
      myservo.write(grippos);

    }

    void wristleft()
    {
      wristpos-=30;
      Serial.println("wristleft");
      if(wristpos<0)
      {
        wristpos=0;
      }
      wrist.write(wristpos);
    }

    void wristright()
    {
      Serial.println("wristright");
      wristpos+=30;
      if(wristpos>180)
      {
        wristpos=180;
      }
      wrist.write(wristpos);
    }

    void elbowup()
    {
      Serial.println("elbow up");
      elbowpos+=15;
      if(elbowpos>180)
      {
        elbowpos=180;
      }
      elbow.write(elbowpos);
    }

    void elbowdown()
    {
      Serial.println("elbow down");
      elbowpos-=15;
      if(elbowpos<0)
      {
        elbowpos=0;
      }
      elbow.write(elbowpos);
    }

    void shoulderup()
    {
      Serial.println("shoulder up");
      shoulderpos+=15;
      if(shoulderpos>180)
      {
        shoulderpos=180;
      }
      shoulder.write(shoulderpos);
    }

    void shoulderdown()
    {
      Serial.println("shoulder down");
      shoulderpos-=15;
      if(shoulderpos<0)
      {
        shoulderpos=180;
      }
      shoulder.write(shoulderpos);
    }

    void forward()
    {
        Serial.println("forward");
        robot.rotate(motor1,100,CW);
        robot.rotate(motor2,100,CCW);

    Serial.println("end reached");

    }

    void backward()
    {
        Serial.println("backward");
            robot.rotate(motor1,100,CCW);
        robot.rotate(motor2,100,CW);
      Serial.println("end reached");

    }

    void left()
    {
        Serial.println("left");
            robot.rotate(motor1,100,CW);
        robot.rotate(motor2,100,CW);
    Serial.println("end reached");

    }

    void right()
    {
        Serial.println("right");
          robot.rotate(motor1,100,CCW);
        robot.rotate(motor2,100,CCW);
    Serial.println("end reached");

    }

    void stopbot()
    {
      Serial.println("stopbot");
      robot.brake(1);
      robot.brake(2);
      prev="";
      Serial.println("end reached");
    }

    void reset()
    {
      myservo.write(0);
      shoulder.write(0);
      elbow.write(0);
      wrist.write(0);
    }

    void handleRoot() {
      server.send(200, "text/plain", "Ready");
    }

    void handleGet() {
      if (server.hasArg("data")) {
        String data = server.arg("data");
        if(data=="gripper_open")
        {
          gripopen();
        }
        else if(data=="reset")
        {
          Serial.println("Reset");
        }
        else if(data=="Stop")
        {
          stopbot();
        }
        else if(data=="Forward")
        {
         // forward();
          if(prev!=data)
          {
            forward();
            prev=data;
          }
        }
        else if(data=="Backward")
        {
         // backward();
          if(prev!=data)
          {
            backward();
            prev=data;
          }
        }
        else if(data=="Left")
        {
          //left();
          if(prev!=data)
          {
            left();
            prev=data;
          }
        }
        else if(data=="Right")
        {
          //right();
          if(prev!=data)
          {
            right();
            prev=data;
          }
        }
        else if(data=="gripper_close")
        {
          gripclose();
        }
        else if(data=="elbow_up")
        {
          elbowup();
        }
        else if(data=="elbow_down")
        {
          elbowdown();
        }
        else if(data=="shoulder_up")
        {
          shoulderup();
        }
        else if(data=="shoulder_down")
        {
          shoulderdown();
        }
        else if(data=="Wrist_left")
        {
          wristleft();
        }
        else if(data=="Wrist_right")
        {
          wristright();
        }
        Serial.println("Data: " + data);

      }
      server.send(200, "text/plain", "Data Received");
    }

    void handlePost() {
        if (server.hasArg("data")) {
        String data = server.arg("data");
        Serial.println("Data: " + data);
      }
     // server.send(200, "text/plain", "Data Received");
      server.send(200, "text/plain", "Processing Data");
    }

    void handleUpload() {
      HTTPUpload& upload = server.upload();
      if (upload.status == UPLOAD_FILE_START) {
        Serial.println("Receiving data:");
      } else if (upload.status == UPLOAD_FILE_WRITE) {
        Serial.write(upload.buf, upload.currentSize);
      } else if (upload.status == UPLOAD_FILE_END) {
        server.send(200, "text/plain", "Data: ");
      }
    }

    void setup() {
      Serial.begin(9600);
      WiFi.softAP("ESP32");
      myservo.attach(13);
      shoulder.attach(12);
      elbow.attach(14);
      wrist.attach(27);

      myservo.write(0);
      shoulder.write(0);
      elbow.write(0);
      wrist.write(0);

      // motordriver pins
      robot.begin();

      server.on("/", handleRoot);
      server.on("/get", HTTP_GET, handleGet);
      server.on("/pot", HTTP_POST,handlePost);
      server.begin();
    }

    void loop() {
      server.handleClient();
    }

I am receiving correct data from the app. That also I had cross-checked. If anyone can help with this or guide me how can i solve this issue.

body:
Hi I have the same problem here, and everything is pointing the issue could be related with the channels shared for PWM. In the Robojax lib there is control of channels want to assign for each motor, but in the ESP32Servo the channels are assigned automatically by the library in consecutive order (see ESP32PWM.cpp). I would try use different channel when calling Robojax that doesn't make conflict with the amount of Servo controlled, maybe could help. For instance in my case I have one servo and 2 DC motors controlled by LN98. So the servo is using channel 0 for PWM, the other two motors on Robojax I will try CHA= 2 and CHB = 3. Maybe this could help.

There are timers shared is explained on the ESP32PWM.cpp, line 259, but I believe the channels conflicts is what is causing this issue.

I will try and let you know. Thanks

I already finished, and for me it is working now. Just need to change CHA and CHB to different PWM channel number (0-15), but > than the amount of servo you have. thanks


message:
Arduino not rebooting with watchdog enabled

I have a custom board that is switching an inductive load through a 10A@230V ac relay.
Due to a poor design, voltage spikes are causing the board to reboot from time to time (brown-out, watchdog and "unknown reason")

The problem here is that from time to time, the microcontroller freezes and no longer executes code (or at least, it seems so), even if the watchdog should be running.
I programmed the WDTON and BROWN-OUT fuses, so the watchdog should be always on.

Once the microcontroller is frozen, an external reset makes it work again.

My questions:

Is there any SOFTWARE fix to guarantee that the device never freezes. Am I using the watchdog incorrectly?

I read in the Atmega 328P datasheet about the 4 cycle restriction between the WDE writing and the prescaler bits writing (page 44), but It´s not clear to me if this restriction applies when WDON fuse is programmed.
Also, I couldn´t find what the "wdt_enable (WDTO_2S);" instruction is doing under the hood.

Is it possible that the watchdog oscillator stops due to a voltage spike?

This is my code (the part to illustrate the watchdog problem)

Hardware: Custom board

microcontroller: ATmega 328P

Brown-out fuse: programmed

WDTON fuse: programmed

```lang-cpp

#include <avr/wdt.h>

#define R0          3 // Relay output 16A @ 230Vac (10A @ 230Vac)
#define R1          4 // Relay output 10A @ 230Vac (10A @ 230Vac)
#define R2          5 // Relay output 10A @ 230Vac (10A @ 230Vac)

byte outputs;

//-------------------------------------------------------------------------

void test() {

#define TEST_SWITCHING_INTERVAL  500

  static unsigned long previousMillisTest;
  static int count;

  unsigned long actualTemp = millis();
  if ((actualTemp - previousMillisTest) >= TEST_SWITCHING_INTERVAL) {
    bitWrite (outputs, 0, !bitRead (outputs, 0)); Serial.print ("R0 = ");    Serial.print (bitRead (outputs, 0));
    bitWrite (outputs, 1, !bitRead (outputs, 1)); Serial.print ("   R1 = "); Serial.print (bitRead (outputs, 1));
    bitWrite (outputs, 2, !bitRead (outputs, 2)); Serial.print ("   R2 = "); Serial.print (bitRead (outputs, 2));
    Serial.print ("   count: "); Serial.print (count++);
    Serial.print ("  millis: "); Serial.println (previousMillisTest);
    previousMillisTest = actualTemp;
  }
  digitalWrite (R0, bitRead (outputs, 0));
  digitalWrite (R1, bitRead (outputs, 1));
  digitalWrite (R2, bitRead (outputs, 2));
}

//-----------------------------------------------------------------------

void setup() {

  uint8_t MCUSR_save;

  MCUSR_save = MCUSR;
  MCUSR = 0;
  wdt_enable (WDTO_2S);

  Serial.begin (9600);

  if      (MCUSR_save & 0x01)  Serial.println ("*********Restarting . Power-on Reset*********");
  else if (MCUSR_save & 0x02)  Serial.println ("*********Restarting . External Reset*********");
  else if (MCUSR_save & 0x04)  Serial.println ("*********Restarting . Brown-out Reset*********");
  else if (MCUSR_save & 0x08)  Serial.println ("*********Restarting . Watchdog Reset*********");
  else if (MCUSR_save & 0x10)  Serial.println ("*********Restarting . JTAG Reset*********");
  else                         Serial.println ("*********Restarting . Unknown reason*********");
  Serial.print ("MCUSR = 0x"); Serial.println (MCUSR_save, HEX);

  initPins();
  initDevice();

  if (DEBUG) showConfig();

  // prevents flooding the RS485 bus if the device is continuously restarting
  delay (100);

  sendFrame (RESTARTED, 0); // sends the "restarted" event through the RS485 port

}

//---------------------------------------------------------------------------

void loop() {
  wdt_reset();
  test();
}

```

body:
You can choose to either reset the processor or execute an interrupt routine. Example code:

<!-- language: c++ -->

    #include <avr/wdt.h>

    // watchdog intervals
    // sleep bit patterns for WDTCSR
    enum
    {
      WDT_16_MS  =  0b000000,
      WDT_32_MS  =  0b000001,
      WDT_64_MS  =  0b000010,
      WDT_128_MS =  0b000011,
      WDT_256_MS =  0b000100,
      WDT_512_MS =  0b000101,
      WDT_1_SEC  =  0b000110,
      WDT_2_SEC  =  0b000111,
      WDT_4_SEC  =  0b100000,
      WDT_8_SEC  =  0b100001,
     };  // end of WDT intervals enum

    void setup()
      {
      wdt_disable ();
      Serial.begin(115200);
      Serial.println ();
      Serial.println("After reset");
      watchdogSetup(WDT_4_SEC);
      }

    volatile bool watchdogFired = false;

    ISR(WDT_vect) // Watchdog timer interrupt.
      {
      watchdogFired = true;
      }

    void watchdogSetup(byte interval)
      {
      cli(); // disable all interrupts

      // Enter Watchdog Configuration mode:
      WDTCSR = bit (WDCE) | bit (WDE);
      // Set Watchdog settings:
      //  WDTCSR = bit (WDIE) | interval;   // set WDIE, and requested delay - for an INTERRUPT
      WDTCSR = bit (WDE) | interval;    // set WDIE, and requested delay - for a RESET
      wdt_reset(); // reset the WDT timer
      sei();  // enable interrupts again
      }

    void loop()
      {

      if (watchdogFired)
        {
        watchdogFired = false;
        Serial.println ("Watchdog fired.");
        }

      // wdt_reset();  // if you want to reset the watchdog

      } // end of loop

This example resets the processor, however if you uncomment the line `WDTCSR = bit (WDIE) | interval;` and comment the one below `WDTCSR = bit (WDE) | interval;` then it interrupts instead. You can see that in the example output.

If you want an interrupt then you have to supply an interrupt routine (ISR).

---

Responding to comments:

> But there´s little documentation about how to adequately recover from a reset when the fuse is programmed.

The processor resets, which is what you want, right? You don't need to "recover" from a reset. It's like saying how do you recover from powering it on.

> Do I still need to re-enable the watchdog, even if it should be enabled by the fuse?.

I doubt it. In my code the watchdog keeps firing, even after you get the message the first time (the interrupt one).

However you might want to change the interval to the one you want. And you might want to reset the watchdog (wdt_reset ()) if things are going OK.

> Also, with the WDTON fuse enabled, the ISR mode is not valid (only the reset mode).

Well, there is not necessarily an ISR for the ISR mode (yet, if ever). The datasheet specifically says that you get the reset mode and not the ISR mode.

It is unclear from the datasheet what the time interval is, with the WDTON fuse programmed.


message:
Why analogRead's value decreases when I decrease the value of resistor?(I use digitalWrite(high) to positive terminal of resistor)

Basically, my circuit contains only 1 resistor(like the basic LED circuit).[![This is my circuit and my code][1]][1]

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

I tried to know what is the actual voltage of digitalWrite(High). I don't understand why the value of analogRead does not fix to 1023 but instead decreases when I decrease the value of the resistor. Moreover, the value comes to zero when my resistor value comes to 1 ohm. Really appreciate any helps here.

body:
A digital output pin can only provide a specific current: 20mA max recommended, 40mA absolute max. When you get near and over that these values the voltage will go down, as the internal driver hardware cannot provide enough current to hold the voltage.

With the resistor you are providing a direct current path to ground. For high values of R it doesn't make much different (as the current through the resistor to ground is lower than the max current of the digital pin drivers max current). When you lower R the current through it to ground gets bigger. Thus the digital pin driver has to provide more current to hold the voltage. When it gets too low the driver cannot provide enough current, the voltage will fall.

With R at 1Ohm you are basically shorting the digital output pin to ground as 1Ohm really isn't much resistance. At 5V (which is the output voltage of the Uno) you will get `U/R = 5V / 1 Ohm = 5A` current through it. The driver cannot provide this. In real life the pin driver would most likely be killed by this current draw.


body:
As a complement to chrisl's answer, it is worth noting that the
datasheet of the microcontroller (here the ATmega328P), under a section
named “Typical characteristics”, has a subsection named “Pin Driver
Strength”. This subsection has some typical voltage-vs-current curves
showing that:

* the curves are not quite linear, although the non-linearity is small
  at 5 V supply voltage
* they depend strongly on temperature
* near ambient temperature, the pin behavior is close to an ideal
  voltage source in series with a 25 Ω resistor.

The curves go only up to 20 mA, as the behavior for higher currents
is not characterized.

From this, you can guess the voltage reading you expect. For example, if
you use a 470 Ω resistor (which is safe), the output pin resistance
and the external resistor make a voltage divider. The expected voltage
you read is

(5 V) × (470 Ω) / (470 Ω + 25 Ω) = 4.747 V


message:
How to transmit DTMF signal to Arduino

I'm trying to read an incoming DTMF signal through the A0 input pin. I want to do this programmatically and not with the MT8870 module. This library (https://github.com/Adrianotiger/phoneDTMF) is supposed to do just that but I can't figure out how to connect my incoming DTMF signal to Arduino's A0 pin to receive the signal. Basically, my laptop produces the DTMF signal and I want to attach the line out, which is two wires, the positive and ground, to Arduino.  None of the configurations I've tried work.  I've tried to attach the positive to A0 and the ground to ground, but A0 doesn't seem to be detecting anything.  I also don't want to use a microphone on the A0 pin to detect the DTMF. A simple Fritzing type diagram showing how to connect the incoming DTMF signal to A0 would be helpful. Thanks.

body:
Your problem is that you think there's a "positive" signal. In audio there isn't a "positive" signal, there is just a signal that swings around 0V.

You have to convert said signal to a "positive" signal by adding a DC offset to it.

The simplest way is with one capacitor and two resistors:

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

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

<!-- End schematic -->

That schematic will remove any DC offset that your laptop may add ("AC couple") and then add a 2.5V DC offset of your own to the signal.  The audio signal will then be alternating around 2.5V.

You may need to boost the audio signal's volume with an op-amp (note: do *not* use a "power" amplifier like the LM386, it is not suitable; use an op-amp) to increase the sensitivity of the input.  You could do this with a simple inverting amplifier arrangement with the DC offset being injected into the non-inverting input:

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

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

<!-- End schematic -->

Here the gain of the amplifier is the ratio between R3 and R4 - in this case a 10:22 ratio (or a 2.2x gain).

From a software point of view you now remove 512 from each analog read value to give you a range of +/-511 for your sampled values. You then probably (maybe with the library you link to) take a block of samples at a defined frequency and perform an FFT analysis to find what dominant frequency components are present.


message:
How to execute programs based on received bluetooth value - wake-up-light (ESP32)

I'm trying to execute programs on my arduino based on values received via bluetooth. Although I've experimented a lot, I'm unable to get the code to  work.

I have build a simple android app with three buttons that sends either value "11", "21" or "31" to the arduino over bluetooth, which should trigger the code to operate a DIY wake-up-light (ESP32 + NeoPixels). Can anyone tell me what I'm doing wrong? Thanks in advance!

    #include "BluetoothSerial.h"
    #include <Adafruit_GFX.h>
    #include <Adafruit_NeoMatrix.h>
    #include <Adafruit_NeoPixel.h>

    // init Class:
    BluetoothSerial ESP_BT;

    #define LED_PIN    5
    #define LED_COUNT 7

    Adafruit_NeoPixel matrix = Adafruit_NeoPixel(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

    void setup() {
      matrix.begin();
      matrix.show(); // Initialize all pixels to 'off'

      Serial.begin(19200);
      ESP_BT.begin("Wake_Up_Light"); //Name of Bluetooth interface
    }

    int led_pin_1 = 5;
    int incoming;

    void loop() {

    // ------------ call wakeup program or gotosleep program ----------------
      if (ESP_BT.available())
      {
        incoming = ESP_BT.read(); //Read what we receive

        int rnumber = incoming;

        switch (rnumber) {
          case 1:
            Serial.print("11"); //----- Activate wake-up light after 6 hours -----
              6hours();
              wakeup();
              ledsoff();
            break;

          case 2:
            Serial.print("21"); //----- Activate go-to-sleep mode -----
              gotosleep();
            break;

          case 3:
            Serial.print("31"); //----- Activate powernap mode -----
              gotosleep();
              wakeupdelay();
              wakeup();
              ledsoff();
            break;
          }
      }
    }

    void wakeup() {

        uint16_t i, j;

      for (j = 1; j < 10; j++) {
        for (i = 0; i <LED_COUNT; i++) {
          matrix.setBrightness(255);
          matrix.setPixelColor(i, 3, j, j);
        }
        matrix.show();
        delay(18000); //-------- 180.000ms (3 minutes) / 10 steps = 18.000 ---------
      }
    }

    void gotosleep() {

        uint16_t i, j;
      for (j = 10; j > 0; j--) {
        for (i = 0; i <LED_COUNT; i++) {
          matrix.setBrightness(255);
          matrix.setPixelColor(i, 3, j, j);
        }
        matrix.show();
        delay(16363); // ---- 180000ms (3 minutes) / 11 steps = 16363 --------
      }
      matrix.setBrightness(0);
      delay(40000); // ---- 40 seconds delay
      }

    void wakeupdelay() {
      delay(1200000);
    }

    void ledsoff() {
        matrix.setBrightness(0);
    }

    void 6hours() {
      delay(21600000)
    }

body:
Thanks for the replies. I've taken another aproach and was able to get the code to work. I'll post it here. Not yet 100% finished, but mostly doing what I wanted.

    #include "esp_bt_main.h"
    #include "esp_bt_device.h"
    #include "BluetoothSerial.h"
    #include <Adafruit_GFX.h>
    #include <Adafruit_NeoMatrix.h>
    #include <Adafruit_NeoPixel.h>

    #define LED_PIN    5
    #define LED_COUNT 7

    Adafruit_NeoPixel matrix = Adafruit_NeoPixel(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

    String  Recvd;
    #if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
    #error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
    #endif

    BluetoothSerial ESP_BT;
    void printDeviceAddress() {

    const uint8_t* point = esp_bt_dev_get_address();

    for (int i = 0; i < 6; i++) {
       char str[3];
       sprintf(str, "X", (int)point[i]);
       Serial.print(str);
       if (i < 5){
       Serial.print(":");}
    }
    Serial.println();
    }

    void setup()
    {
    Recvd = "";

    Serial.begin(19200);

      ESP_BT.begin("Wake_Up_Light");
      Serial.println("Address:");
      printDeviceAddress();

    }

    int led_pin_1 = 5;
    int incoming;

    void loop()
    {
    matrix.setBrightness(0);
    matrix.show();
        if (ESP_BT.available()) {
          Recvd = (ESP_BT.read());
          Serial.println("Received value:");
          Serial.println(Recvd);
          if (Recvd == "11") {
            Serial.println("Running wake-up>6hr mode");
            sixhours();
            wakeup();
            ledsoff();

          }
          if (Recvd == "21") {
            Serial.println("Running go-to-sleep mode");
            gotosleep();

          }
          if (Recvd == "31") {
            Serial.println("Running powernap mode");
            gotosleep();
            wakeupdelay();
            wakeup();
            ledsoff();

          }

        }

    }

    void wakeup() {

        uint16_t i, j;

      for (j = 1; j < 10; j++) {
        for (i = 0; i <LED_COUNT; i++) {
          matrix.setBrightness(255);
          matrix.setPixelColor(i, 3, j, j);
        }
        matrix.show();
        delay(18000); //-------- 180.000ms (3 minutes) / 10 steps = 18.000 ---------
      }
    }

    void gotosleep() {

        uint16_t i, j;
      for (j = 10; j > 0; j--) {
        for (i = 0; i <LED_COUNT; i++) {
          matrix.setBrightness(255);
          matrix.setPixelColor(i, 3, j, j);
        }
        matrix.show();
        delay(16363); // ---- 180000ms (3 minutes) / 11 steps = 16363 --------
      }
      matrix.setBrightness(0);
      delay(40000); // ---- 40 seconds delay
      }

    void wakeupdelay() {
      delay(1200000); // (20 minutes)
    }

    void ledsoff() {
        matrix.setBrightness(0);
    }

    void sixhours() {
      delay(21600000); // (6 hours)
    }


message:
Arduino nano standalone - pcb to be manufactured

Using EasyEDA I've designed a standalone Arduino nano and plan to have a small PCB manufactured by jlcpcb. I've used the [Nano's user manual][1] as a reference for the PCB; within this scope I've used the same microcontroller (ATMEGA168-20AU) and kept close to the original design.

The circuit is modestly basic and will use a blank target ATMEGA168 placed by jlcpcb - my question is - From a programmer Arduino, do I flash the bootloader and program the target micro through the ICSP (left hand side) or is something else required for bootloader plus program? Is the circuit schematic sufficient to work? (could be opening a can of worms here in asking that)

Thanks

[![ATMEGA168-20AU][2]][2]

  [1]: https://www.arduino.cc/en/uploads/Main/ArduinoNanoManual23.pdf
  [2]: https://i.stack.imgur.com/ikjm9.png

body:
You program the chip through ICSP, yes.  Whether or not you include a bootloader is optional - you don't need a bootloader to program through ICSP, that is only for if you want to program through the UART pins and a USB to UART adapter.

Your circuit doesn't appear to include any "bypass" capacitors. These are small capacitors (usually 100nF) placed close to each power (VCC) pin on all chips. These are not optional and are required for the proper running of the chip.


message:
how to change a const char*

At the top of my arduino sketch, I have the following :
```
// softAp
const char *softApSsid = "abcdefg";
const char *softApPassword = "123456";
```

Those are the DEFAULT ssid and password to connect to the soft AP. The soft AP is start in the setup() such as :
```
WiFi.softAP(softApSsid, softApPassword);
```

according to the github repo, that function indeed requires "const char*" as parameters (source: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiAP.cpp#L97)

Further in my sketch, I want to let the user edit the ssid and password. I wrote a function that reads the first byte of the eeprom. If it equals 255, we use the default credentials, if it equals to 1, it means the user set custom credentials, so we will use those to spawn the soft AP.

I wrote this :
```
void getSoftApAuth() {
  bool isDefaultSoftApAuth = 255 == EEPROM.read(0);

  if (! isDefaultSoftApAuth) {
    softApSsid = "";
    softApPassword = "";

    int i = 1;
    while ('\0' != EEPROM.read(i)) {
      softApSsid += char(EEPROM.read(i));
      i++;
    }

    i = 65;
    while ('\0' != EEPROM.read(i)) {
      softApPassword += char(EEPROM.read(i));
      i++;
    }
  }
}

void setSoftApAuth(const char* ssid, const char* passphrase) {
  EEPROM.write(0, 1);

  // ssid
  int positionOfSsid = 1;
  int lengthOfSsid = strlen(ssid);
  for (int i = 0; i < lengthOfSsid; i++) {
    EEPROM.write(positionOfSsid + i, ssid[i]);
  }
  EEPROM.write(positionOfSsid + lengthOfSsid, '\0');

  // passphrase
  int positionOfPassphrase = 65;
  int lengthOfPassphrase = strlen(passphrase);
  for (int i = 0; i < lengthOfPassphrase; i++) {
    EEPROM.write(positionOfPassphrase + i, passphrase[i]);
  }
  EEPROM.write(positionOfPassphrase + lengthOfPassphrase, '\0');

  if (EEPROM.commit()) {
    Serial.println("Successful EEPROM write");
  } else {
    Serial.println("Failed EEPROM write");
  }
}

void resetSoftApAuth() {
  EEPROM.write(0, 255);

  if (EEPROM.commit()) {
    Serial.println("Successful EEPROM reset");
  } else {
    Serial.println("Failed EEPROM reset");
  }
}
```

this does compile but crashes and throws exceptions when I run the chip. I believe the issue is in getSoftApAuth() where i try to concatenate the string such as ```softApSsid += char(EEPROM.read(i));```. I print the value of softApSsid in the Serial Monitor and it outputs garbage. I replaced everything with "String" type, and this time it outputs correct username/password stored in the eeprom, but it wont start the soft AP, I believe because I am now trying to pass String instead of const char* to the ```WiFi.softAP()``` function as I said earlier (it starts the soft AP with factory default SSID like ESP-AABBCCDDEE appending the MAC address and without any password).

So, basically, how can I modify my ```softApSsid``` down in my code, while i declared it at the top as a ```const char*```, knowing it feeds a function that takes (exclusively?) a ```const char*``` (WiFi.softAP())

Or is there an other approach / design pattern to achieve this? That is to say: having default credentials hard-coded, but allowing the user to define custom credentials (and storing/retrieving them from the eeprom).

Thanks. Please be indulgent as I am mostly a webdev and not yet comfortable with the strongly typed languages (let alone pointers / references ...)

body: Always remember that a variable that is defined as a char array will not automatically grow if you concatenate something to it. Its size is fixed. When you used String, that did fix that problem. You can use the c_str() function of String to access the string itself. String operations will change that string, perhaps even allocating it at a different address. It might be wise just to define fixed sized char arrays for passing to the WIFI functions. I'd have to look inside the WIFI library to determine if the strings are copied for use internally. Make those fixed sizes large enough to take some editing, but do protect from over-filling by the editor.


body:
> that function indeed requires "const char\*" as parameters

There seems to be a misunderstanding here. The method signature is:

```c++
bool ESP8266WiFiAPClass::softAP(const char* ssid, const char* psk,
    int channel, int ssid_hidden, int max_connection);
```

Within this signature, the word `const` means the method makes the
promise not to modify the `ssid` nor the `psk` strings. If you were
implementing the method, you would indeed be _required_ to honor the
constness of these strings. As a user of the method, however, you are
perfectly allowed to provide a modifiable string. You are not bound by
any constness requirement. And indeed, you have to use modifiable
strings if you want your user to be able to change them.

The simplest way to handle this situation is:

```c++
char softApSsid[MAX_SSID_LENGTH] = "abcdefg";
char softApPassword[MAX_PWD_LENGTH] = "123456";
```

Note that you have to allocate enough room to store the longest strings
you may need. Whereas 8 bytes would be enough to store `"abcdefg"`,
it may not suffice for other ssids.

Also note that C strings cannot be grown with the `+=` operator. They
are just arrays of characters and should be written to as such:

```c++
i = 0;
do {
    char c = EEPROM.read(1+i);
    softApSsid[i++] = c;
} while (c != '\0');
```

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

**Edit**: answering this comment:
> Some research on SO also suggested the following:
> `const char *password = myString.c_str();`
> where `myString` is of `String` type.

Indeed. The `c_str()` method of the `String` class lets you directly
access the C string buried within a `String` object, if you promise not
to modify it (hence the `const`). Growing a `String` is easy, as the
`+=` operator takes care of handling the memory.

I would, however, advice against any unnecessary use of the `String`
class, as it involves lots of heap memory allocation, especially if you
build a string one character at a time with `+=`. This is not really
friendly to your device's memory. See [The Evils of Arduino
Strings][majenko] for details.

[majenko]: https://majenko.co.uk/blog/our-blog-1/the-evils-of-arduino-strings-32


message:
How to limit backlight LED current in 16x2 LCD

I'm getting the error "**Current through backlight led is 23.7 kA, while maximum is 20.0 mA**". What am I doing wrong?

[![][1]][1]

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

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

    void setup()
    {
      lcd.begin(16,2);
    }

    void loop()
    {
      lcd.print("Arduino");
      delay(3000);
    }

body:
The two pins on the LCD which are marked "LED" are directly connected to the backlight LED. If you drive an LED over its forward voltage the current is rising exponential in relation to the voltage. Thus every LED needs a current limiting circuit, like a simple resistor in series. Otherwise the current through the LED will be so high, that it gets fried.

So to solve the problem you should place a resistor in series with the backlight LED (so for example between Vcc and the positive LED pin). The needed resistor value depends on the LED. The error message states 20mA max (just like a digital output pin on an Arduino), thus a value above R = U/I = 5V/20mA = 250 Ohm will be enough to hold the current below the maximum. To have a safety margin I would start with like 300 Ohm (depending on whats available).


body:
You need to limit the current going to the backlight LED by putting a resistor in series with the LED.

Currently you have the LED wired to 5V and Ground with nothing to limit the current. This will result in the LED failing from over-current.

You will want to install a 330 ohm resistor in series with the LED, like illustrated in the image below. (Note the data lines are not shown to make the circuit simpler.)

[![16x2 LCD with current limiting resistor][1]][1]

  [1]: https://i.stack.imgur.com/otO48.gif