message:
Do interrupts block other interrupts?

If I have an interrupt attached to two pins and the handler of the first is still executing when the second interrupt fires, does it:

a) queue the second interrupt,

b) ignore the second interrupt (missing it altogether), or

c) pause processing of the first interrupt to execute the second?

I am writing code that logs the exact time the interrupt occurs. Quite lightweight, but have three pins and am logging the rise and fall of each, so there is the potential for collisions. If a) then the second interrupt timestamp will be late, b) there is no timestamp for the later interrupt or c) the timing of the first and second interrupts will be ambiguous.

b) is the worst case, the other two are manageable.

body:
It depends on the architecture.

Assuming AVR (8-bit Arduino) then it will queue the second interrupt until the first is finished.

It works by setting a flag in a register at the moment the interrupt occurs. Then between instructions it checks that flag and executes the associated interrupt routine. If an interrupt is in progress at the time the flag still gets set, but it is unable to check the state of that flag until after the current interrupt is over and normal execution occurs, at which point after the next instruction is completed it checks the interrupt flag statuses and runs the second interrupt routine.


sender: user

sender: assistant

body:
It depends on the specific MCU, not all are exactly the same.

Some have interrupt priority circuitry that you can use.  But in general, an ISR can be interrupted by another incoming IRQ, etc.  What you often do in an ISR is mask IRQ, handle the IRQ, and then unmask to let any pending IRQs be handled.

This is one reason why long-running ISRs should be avoided!


message:
Switch case (millis()) UPDATED

I want to create a sketch that counts the days from the moment the "project" start and send and osc message every two days (or more) for 3 weeks. So:

day zero : osc message -> 0
day two. : osc message -> 1
day four : osc message -> 2

etc.

I'm trying to create a state machine to send the messages when the millis reaches a certain time it should print message and so on for the other times.
I'm giving a small example:

I went with @jsotola's suggestion and tried out the BlinkWithoutDelay approach. It seemingly works because I get serial prints around the correct millis() they are printed in 4fold or 3fold the messages.

EDITED CODE:
```c++
int daytwo = 25920; // for testing purposes other numbers then the actual millis()
int dayfour = 44400;

void loop() {
  unsigned long currentMillis = millis();   // store current time

  if (currentMillis == daytwo) {
    Serial.println("daytwo");
  }

  if (currentMillis == dayfour) {
    Serial.println("dayfour");
  }
}
```

Serial output:

    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.926 -> daytwo
    11:04:58.366 -> dayfour
    11:04:58.366 -> dayfour
    11:04:58.366 -> dayfour
    11:04:58.366 -> dayfour

body:
The following code is not very "clean" but easy to understand. Use a variable to hold the day, you have already printed and check in which interval you are. If you change the 2 day interval print a message and set the actDay variable to the number of the day you have already printed; to avoid repprinting it again.

    int daytwo = 25920;
    int dayfour = 44400;

    int actDay = -1;

    void loop()
    {
      unsigned long currentMillis = millis();
      if (currentMillis < daytwo)
      {
        if ( actDay != 0 )
        {
          actDay = 0;
          Serial.println("dayzero");
        }
      }
      else if (currentMillis < dayfour )
      {
        if ( actDay != 2 )
        {
          actDay = 2;
          Serial.println("daytwo");
        }
      }
      else
      {
        if ( actDay != 4 )
        {
          actDay = 4;
          Serial.println("dayfour");
        }
      }
    }


body:
```lang-cpp
int day = 0;
unsigned long prevMillis = 0;
const unsigned long MILLIS_PER_DAY = 86400000UL;

void setup()
{
  prevMillis = millis();
}

void loop() {
  if( millis() - prevMillis > MILLIS_PER_DAY )
  {
    // one whole day has passed
    day++;
    prevMillis += MILLIS_PER_DAY;

    // do the things you want to do at the beginning of a new day
    if( day==2 ) {
      Serial.println("daytwo");
    }
    else if (day == 4) {
      Serial.println("dayfour");
    }
  }
}
```

This is a more generic version. It checks if `24*60*60*1000` milliseconds have past since the last time the day rolled over. When this occurs, it will increment the current day and update `prevMillis` to have the value of millis() when the day started.

This also has the advantage that is will only run your "daily code" once.

And will also run, when some other task takes a long time. I your old code, you might miss the exact moment millis() is the value you are looking for, if some other code takes more than 1 ms.


message:
PubSubClient: Subscription working, but callback never called

I am using an ESP32 (https://heltec.org/project/wifi-kit-32/) with a AM2302 DHT22 and an LDR, talking to mosquitto on a Linux box.  Publishing data is working fine, other than the "exceeded timeout, disconnecting" lots of people seem to be having.  However, when a message is sent from another client to a topic I am subscribed to, my callback is never called, so I can't consume it.

In my reconnect function, I have
```
    boolean success = mqttClient.subscribe("sensors/basement/led");
    Serial.print("Subscribe returned ");
    Serial.println(success);
```
and it does return 1 which I believe is success (usually success is zero but I don't think that's the case here).  I also see the subscription in my mosquitto logs, which are currently cranked up to debug.
```
1610417274: New client connected from XXX.XXX.XXX.XXX as Basement1 (c1, k15, u'XXXXXXXXX').
1610417274: Sending CONNACK to Basement1 (0, 0)
1610417275: Received SUBSCRIBE from Basement1
1610417275:     sensors/basement/led (QoS 0)
1610417275: Basement1 0 sensors/basement/led
1610417275: Sending SUBACK to Basement1
```
When I send data to sensors/basement/led from the other client (mqttdash), the server receives it, and sends it to mqttdash, as well as Basement1, which is my ESP32:
```
It's definitely sending the message to the ESP32:
1610417546: mqttdash-3785c5ce 0 sensors/basement/led
1610417546: Sending SUBACK to mqttdash-3785c5ce
1610417578: Received PUBLISH from mqttdash-3785c5ce (d0, q0, r0, m0, 'sensors/basement/led', ... (1 bytes))
1610417578: Sending PUBLISH to Basement1 (d0, q0, r0, m0, 'sensors/basement/led', ... (1 bytes))
1610417578: Sending PUBLISH to mqttdash-3785c5ce (d0, q0, r0, m0, 'sensors/basement/led', ... (1 bytes))
```
However, my callback is never called.  Here is the setup of the callback:
```
WiFiClient espClient;
PubSubClient mqttClient(espClient);
...
void setupMQTT()
{
    mqttClient.setServer(MQTT_HOST, MQTT_PORT);
    mqttClient.setCallback(mqttSubHandler);
    mqttConnect();
}
...
void mqttSubHandler(char *topic, byte *message, unsigned int length)
{
    Serial.print("Message arrived on topic: '");
    Serial.print(topic);
    Serial.print("'. Message: ");
    String messageTemp;

    for (int i = 0; i < length; i++)
    {
        Serial.print((char)message[i]);
        messageTemp += (char)message[i];
    }
    Serial.println();
...
```

Full code at https://github.com/djsegfault/arduino/blob/master/basement_monitor/basement_monitor.ino

Does anyone know why the callback is not being called?  Thanks in advance.

body:
nknolleary, the owner of the library, correctly identified the problem:
You need to call mqttClient.loop() in you main loop. Without that, you are never giving the client a chance to check for any incoming messages.


message:
Using same GPIO pins to control multiple stepper drives

I have an Arduino Mega 2560 and I want to control four 23-frame steppers same speed/direction for a conveyor application. I want these to be synchronized exactly as possible for smooth operation.

- Can four TB6600 drivers be daisy chained to the same Arduino GPIO pins?

- Is there a limit to how many number of drivers I can daisy chain?

- I'm wondering about current draw from the 5 volt Arduino GPIO, spread out over many drivers.

Thanks for your help!
Bob

body:
Those devices use opto-isolated inputs. To all intents and purposes they look just like an LED with a resistor in series.

The built-in resistor looks like it sets the current to "between 8mA and 15mA" and typically 10mA, though it's impossible to say what it *actually* is.  So we'll take the worst-case scenario of 15mA.

The Arduino has an absolute maximum of 40mA, and a recommended maximum of 25mA from each IO pin, with a maximum of 200mA in total through all pins.

That means you ideally can't really have more than one TB6600 per IO pin, but you could get away with 2 per pin, certainly no more.

To run lots in parallel you would need a separate set of drivers that can "fan out" the low-current signal to either a single high current signal or a parallel set of low-current signals.

It looks like you provide 5V to one pin of each input (the anode of the opto-isolator) and sink the current through the other pin (the cathode of the opto-isolator) to ground through your IO pins. That means you could use a single large N-channel MOSFET to sink all of the cathodes in parallel and invert your IO logic in software.


message:
USB FT232 driver on M1 mini

I've scored a couple Nanos with FT232RL chips but can't see them on my brand new M1 mini. Can someone point me at how to determine whether v11.1 supports this USB chip?

It appears that the device is being instantiated but the Arduino IDE gets no response to the Get Board Info.
```
FT232R USB UART:

  Product ID: 0x6001
  Vendor ID: 0x0403  (Future Technology Devices International Limited)
  Version: 6.00
  Serial Number: AR0JT9YB
  Speed: Up to 12 Mb/s
  Manufacturer: FTDI
  Location ID: 0x02214000 / 20
  Current Available (mA): 500
  Current Required (mA): 90
  Extra Operating Current (mA): 0
```
Executing the ioreg mentioned by @st2000 gives;
```
+-o Root  <class IORegistryEntry, id 0x100000100, retain 31>
  +-o AppleT8103USBXHCI@00000000  <class AppleT8103USBXHCI, id 0x100000291, registered, matched, active, busy 0 (1676 ms), retain 328>
  | +-o Extreme SSD@00200000  <class IOUSBHostDevice, id 0x10000081d, registered, matched, active, busy 0 (219 ms), retain 132>
  +-o AppleT8103USBXHCI@01000000  <class AppleT8103USBXHCI, id 0x100000295, registered, matched, active, busy 0 (4 ms), retain 39>
  +-o AppleT8103USBXHCIFL1100@02000000  <class AppleT8103USBXHCIFL1100, id 0x1000006eb, registered, matched, active, busy 0 (1220 ms), retain 494>
    +-o Keyboard Hub@02100000  <class IOUSBHostDevice, id 0x10000071c, registered, matched, active, busy 0 (164 ms), retain 30>
    | +-o Apple Keyboard@02120000  <class IOUSBHostDevice, id 0x100000805, registered, matched, active, busy 0 (162 ms), retain 32>
    +-o 4-Port USB 2.0 Hub@02200000  <class IOUSBHostDevice, id 0x100000730, registered, matched, active, busy 0 (826 ms), retain 46>
    | +-o 4-Port USB 2.0 Hub@02230000  <class IOUSBHostDevice, id 0x100000785, registered, matched, active, busy 0 (11 ms), retain 42>
    | +-o 4-Port USB 2.0 Hub@02220000  <class IOUSBHostDevice, id 0x100000791, registered, matched, active, busy 0 (16 ms), retain 43>
    | | +-o Backup+ Hub@02223000  <class IOUSBHostDevice, id 0x1000007dc, registered, matched, active, busy 0 (6 ms), retain 41>
    | +-o 4-Port USB 2.0 Hub@02210000  <class IOUSBHostDevice, id 0x10000079d, registered, matched, active, busy 0 (776 ms), retain 43>
    | | +-o FT232R USB UART@02214000  <class IOUSBHostDevice, id 0x100007622, registered, matched, active, busy 0 (75 ms), retain 23>
    | +-o 4-Port USB 2.0 Hub@02240000  <class IOUSBHostDevice, id 0x1000007b6, registered, matched, active, busy 0 (12 ms), retain 42>
    +-o 4-Port USB 3.0 Hub@02600000  <class IOUSBHostDevice, id 0x100000749, registered, matched, active, busy 0 (231 ms), retain 46>
      +-o 4-Port USB 3.0 Hub@02620000  <class IOUSBHostDevice, id 0x10000075e, registered, matched, active, busy 0 (170 ms), retain 43>
      | +-o Backup+ Hub@02623000  <class IOUSBHostDevice, id 0x1000007c3, registered, matched, active, busy 0 (155 ms), retain 41>
      |   +-o Backup+ Hub BK@02623100  <class IOUSBHostDevice, id 0x1000007ee, registered, matched, active, busy 0 (147 ms), retain 131>
      +-o 4-Port USB 3.0 Hub@02640000  <class IOUSBHostDevice, id 0x100000763, registered, matched, active, busy 0 (15 ms), retain 42>
      +-o 4-Port USB 3.0 Hub@02630000  <class IOUSBHostDevice, id 0x100000775, registered, matched, active, busy 0 (15 ms), retain 42>
      +-o 4-Port USB 3.0 Hub@02610000  <class IOUSBHostDevice, id 0x1000007a9, registered, matched, active, busy 0 (16 ms), retain 42>
```
Which does not appear to contain the device afai can see. Any know if this means a new device for Big Sur is indicated as per Majenko♦ ?

body:
A MAC is usually (unless it is really old) running a derivative of Unix. I would open a console install and use "lsusb" to list out all the USB connected devices.

A (Linux) example of lsusb:

    $ lsusb
    Bus 001 Device 004: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port

I would do this with and with out the Arduino FTDI chip connected and look for the difference. [This stackexchange question/answer][1] contains how to do this on a MAC or use other MAC commands to do the same.  As pointed out in the comments the more native MAC command is:

    ioreg -p IOUSB

Note, if you have fake FTDI chips there was a time when the [FTDI driver that Windows ran would brick the fake FTDI chip][2]. I think it would assign the vendor and device IDs both to zero. You should be able to see this with the "lsusb" command.

  [1]: https://stackoverflow.com/questions/17058134/is-there-an-equivalent-of-lsusb-for-os-x
  [2]: https://hackaday.com/2016/02/01/ftdi-drivers-break-fake-chips-again/


body:
As an addendum to @st2000's answer, it's worth noting that OS X comes with a basic driver for FTDI built in. However if your device uses a non-standard VID or PID it will not work.  At the time of writing this, [according to this forum thread](https://www.ftdicommunity.com/index.php?topic=547.30
), FTDI have not yet written an updated driver for Big Sur, and seem to be struggling to do so (they have been writing one for the past year and still haven't managed it).

This should not apply to an Arduino that uses an FTDI with default settings, but worth noting for some custom devices.


body:
I run macOS Big Sur on M1 silicon (a new machine installed in the last month) and also  FT232RL interfaces (e.g., cheap HW-417-V1.2 unit). I just went back through my downloads used in setting up the machine, as far as I can recall I did *not* have to download the [FTDI driver][1] which I used to on the previous older machine. This supports @Majenko's answer regarding a built in driver. I read a little more about this [here][2]. If anyone can point to more information about the built in driver that would be awesome.

I use `ls /dev/cu.*` in a terminal window to check which USB devices are plugged in. Mine shows up as `/dev/cu.usbserial-A5XK3RJT`

On the macOS desktop, the *[Apple Icon]\About this Mac\System Report\USB* information (which I think is a GUI representation of the ioreg mentioned above?) shows the device as:

    FT232R USB UART:

      Product ID: 0x6001
      Vendor ID: 0x0403  (Future Technology Devices International Limited)
      Version: 6.00
      Serial Number: A5XK3RJT
      Speed: Up to 12 Mb/s
      Manufacturer: FTDI
      Location ID: 0x02240000 / 17
      Current Available (mA): 500
      Current Required (mA): 90
      Extra Operating Current (mA): 0

If non-standard PIDs or VIDs are causing devices to be blocked, then a possibility (which I have not tested) might be just to reflash the config on the FTDI device see: [dangerousprototypes - how to get a nicely named serial device][3].

Use `ls /dev/cu.*` in a terminal window to see if the device is showing as a call-up USB device. Then in Arduino IDE rather than using "Get Board Info", just set Tools/Port to that USB port and try to upload a sketch. The port should show up as `/dev/cu.usbserial-AR0JT9YB` or similar.

The FTDR device is in the `ioreg` output you posted, I believe it's hiding there as:

```
FT232R USB UART@02214000 <class IOUSBHostDevice, id 0x100007622, registered, matched, active, busy 0 (75 ms), retain 23>
```

  [1]: https://www.ftdichip.com/Drivers/VCP.htm
  [2]: https://tips.graphica.com.au/macos-big-sur-rs232/
  [3]: http://dangerousprototypes.com/blog/2010/01/27/pirate-rename-get-a-nicely-named-serial-device/


message:
Mac Big Sur don't recognize generic Wemos D1 MINI PRO based ESP-8266EX

I bought one of theses cheaps & generic Wemos D1 MINI PRO with ESP-8266 to make a system to connect my lamp with google home etc.
But the problem is to upload the code into wemos. The Arduino IDE do not recognize the USB port that is connected.
[![enter image description here][1]][1]

When I connect to my Mac the board flashes the blue LED, so I suppose that it's not dead or something.
I've tried 5 different cables e nothing. I've read some articles about drivers to install but is only for [Sierra or High Sierra][2].
Also, uninstalled and installed the arduino IDE.
I installed the ESP8266 Boards in the Boards Manager.
I tested it out with an Arduino UNO board and it recognized normally.

I have no idea what to do. I don't have a windows PC in my house to test it out, as well.

Here the pics of the board:

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

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

  [1]: https://i.stack.imgur.com/IGQS8.png
  [2]: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver
  [3]: https://i.stack.imgur.com/5sfDu.jpg
  [4]: https://i.stack.imgur.com/bXAt5.jpg

body: You need the CP210x drivers from [here](https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers).


message:
What is the purpose of F() and FPSTR() in ESP8266WebServer -> FSBrowser?

I found this [code sample][1] from the FSBrowser (Flash File System) example in the [ESP8266WebServer][2] library:
```lang-c
replyServerError(FPSTR(FS_INIT_ERROR));
replyBadRequest(F("DIR ARG MISSING"));
```

I was a bit confused at what `F()` and `FPSTR()` do, so I looked up the source (`WString.h`) and found this:
```lang-c
#define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))
#define F(string_literal) (FPSTR(PSTR(string_literal)))
```
Which raised more questions. How does this code work and what does this added complexity gain over just using `char*` or `String` as is?

### EDIT: Added Metrics

Here's the memory usage before and after I removed all 25 instances of F() from a file system class, measured by PlatformIO Project Inspector:

||With F()|Without F()|Difference|
|-|-|-|-|
|RAM Used|29,488 bytes (36.0%)|29,792 bytes (36.4%)|+304 bytes|
|Flash Used|355,312 bytes (34%)|355,188 bytes (34.0%)|-124 bytes|
|Total (uncompressed)|359,472 bytes|359,344 bytes|-128 bytes|

Adding F() decreases RAM usage by 1% and increases Flash by around half that. That's for a single class with 25 instances of F(). For a program containing 20x this code, the difference can be significant. However, you'll run out of RAM before you get there. The space savings will be limited to around 5-8%. Still not nothing.

  [1]: https://github.com/esp8266/Arduino/blob/a4b6003c2e5f27fcce42124f2ffef824fb90339d/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino#L177-L183
  [2]: https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WebServer

body:
The purpose of the `PSTR()` macro is to configure the string to be used directly from flash memory. The string is then not loaded to dynamic memory at runtime as it would be without [PROGMEM][1] specifier set by the macro.

The purpose of the `FPSTR()` macro is to cast a string to 'dummy' FlashStringHelper type to help compiler choose the right overloaded function if dynamic memory and flash memory version of a function is available. An example would be the `print` function.

The `F()` macro combines this two macros. It makes the string a PROGMEM string and casts it to FlashStringHelper.

  [1]: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/


message:
How do I power a linear actuator at different speeds for specified periods of time

I am new to Arduino and wondering if anyone can help me get it programmed correctly. I am using two buttons to control a linear actuator to open and close a barn door. I want it to go a certain speed for a specified period of time... like 3 seconds. Then I want it to slow down and go another 2 seconds. The linear actuator does not have feedback which is fine for the application because it does not have to be precise. Below is the code I copied from the manufacturers website - it works well, but I can’t figure out how to make it go for specified periods of time. Please remember I’ve never used an Arduino before and this is literally a foreign language to me. I’m just hoping someone can tell me what to do. It’s for my house, not for a school project.

*** ADDENDUM - Thanks for the help. Wish I could post a video... Here is the final code:

    /* Firgelli Automations
     * Limited or no support: we do not have the resources for Arduino code support
     *
     * Program enables momentary direction control of actuator using push button
     */

    int RPWM = 10; //connect Arduino pin 10 to IBT-2 pin RPWM
    int LPWM = 11; //connect Arduino pin 11 to IBT-2 pin LPWM
    int RPWM2 = 5; //connect Arduino pin 5 to IBT-2 pin RPWM
    int LPWM2 = 6; //connect Arduino pin 6 to IBT-2 pin LPWM
    int downPin = 12;
    int upPin = 13;
    int speed1 = 0; // Top speed you can change it between [0-255]
    int speed2 = 0; // Low speed you can change it between [0-255]
    int speed3 = 0; // Low speed you can change it between [0-255]

    void setup() {
      pinMode(RPWM, OUTPUT);
      pinMode(LPWM, OUTPUT);
      pinMode(RPWM2, OUTPUT);
      pinMode(LPWM2, OUTPUT);
      pinMode(downPin, INPUT_PULLUP);
      pinMode(upPin, INPUT_PULLUP);
    }

    void loop() {
      if(digitalRead(upPin)==LOW){ //check if extension button is pressed
        analogWrite(RPWM, 0);
        analogWrite(RPWM2, 0);
        analogWrite(LPWM, 255); // rotate motor with top speed (with PWM set to 255)
        analogWrite(LPWM2, 236); // rotate motor with top speed (with PWM set to 255)
        delay(3000);               // wait for x sec
        analogWrite(LPWM, 185); // rotate motor with low speed (with PWM set to 150)
        analogWrite(LPWM2, 181); // rotate motor with low speed (with PWM set to 150)
        delay(1600);               // wait for x sec
        analogWrite(LPWM, 80); // rotate motor with low speed (with PWM set to 150)
        analogWrite(LPWM2, 80); // rotate motor with low speed (with PWM set to 150)
        delay(1400);               // wait for x sec
        analogWrite(LPWM, 0);     // uncomment if you want to stop motor now
        analogWrite(LPWM2, 0);     // uncomment if you want to stop motor now
      }

      else if(digitalRead(downPin)==LOW){ //check if retraction button is pressed
        analogWrite(LPWM, 0);
        analogWrite(LPWM2, 0);
        analogWrite(RPWM, 254); // rotate motor with top speed (with PWM set to 255)
        analogWrite(RPWM2, 255); // rotate motor with top speed (with PWM set to 255)
        delay(3000);               // wait for x sec
        analogWrite(RPWM, 170); // rotate motor with low speed (with PWM set to 150)
        analogWrite(RPWM2, 170); // rotate motor with low speed (with PWM set to 150)
        delay(1500);               // wait for x sec
        analogWrite(RPWM, 80); // rotate motor with low speed (with PWM set to 150)
        analogWrite(RPWM2, 80); // rotate motor with low speed (with PWM set to 150)
        delay(1500);               // wait for x sec
        analogWrite(RPWM, 0);     // uncomment if you want to stop motor now
        analogWrite(RPWM2, 0);     // uncomment if you want to stop motor now
      }

      else{ //if no button is pushed, remain stationary
        analogWrite(RPWM, 0);
        analogWrite(LPWM, 0);
        analogWrite(RPWM2, 0);
        analogWrite(LPWM2, 0);
      }
    }

body:
You can do this easily by using Arduino built-in PWM function and using delay function. But remember that using delay in your code will block your code so if your program just want to sit and wait for 3 seconds at some speed then delay is ok for you else you need to implement Millis function.

first you need to define different speeds as per your requirement remember PWM function has value from 0-255 where 0 in min speed and 255 is top speed.
So here I will define speed1 for top speed and speed2 for low speed
So now your program will look like this

```
int RPWM = 10; //connect Arduino pin 10 to IBT-2 pin RPWM
int LPWM = 11; //connect Arduino pin 11 to IBT-2 pin LPWM
int downPin = 12;
int upPin = 13;
int speed1 = 255; // Top speed you can change it between [0-255]
int speed2 = 150; // Low speed you can change it between [0-255]

void setup() {
  pinMode(RPWM, OUTPUT);
  pinMode(LPWM, OUTPUT);
  pinMode(downPin, INPUT_PULLUP);
  pinMode(upPin, INPUT_PULLUP);
}

void loop() {
  if(digitalRead(upPin)==LOW){ //check if extension button is pressed
    analogWrite(RPWM, 0);
    analogWrite(LPWM, speed1); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for 3 sec
    analogWrite(LPWM, speed2); // rotate motor with low speed (with PWM set to 150)
    delay(2000);               // wait for 2 sec
   // analogWrite(LPWM,0);     // uncomment if you want to stop motor now
  }

  else if(digitalRead(downPin)==LOW){ //check if retraction button is pressed
    analogWrite(LPWM, 0);
    analogWrite(RPWM, speed1); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for 3 sec
    analogWrite(RPWM, speed2); // rotate motor with low speed (with PWM set to 150)
    delay(2000);               // wait for 2 sec
    // analogWrite(RPWM,0);     // uncomment if you want to stop motor now
  }

  else{ //if no button is pushed, remain stationary
    analogWrite(RPWM, 0);
    analogWrite(LPWM, 0);
  }
}
```


message:
Resolved: ESP8266 works when arduino UNO reset pin is grounded

I'm setting up PIR and esp8266 with arduino UNO.
First my esp8266 doesn't work after alot of research my esp8266 start working when I put arduino UNO reset pin to ground.
But now my arduino UNO does not run any program and I'm not able to use PIR with this wifi module.
Any help will be appreciated
[![enter image description here][1]][1]

Only one extra thing is that reset pin is set to GND pin.

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

body:
The RESET of the UNO puts the ATMega328P (the MCU of the UNO) into an electrically inert state when it is connected to GND.  It is not *supposed* to be running your sketch when it is being held in reset.  It is, roughly speaking, electrically disconnected from everything else on the board.  This allows you to use the UNO as though it were a USB to TTL serial cable.

If you want to be able to run a sketch on the UNO while it uses the ESP8266, you'll need to **not** hold reset to GND and you'll also, practically speaking, need to choose a different set of pins for communicating with it, as D0 and D1 on the UNO are the same signals used to for the ATMega328P to talk to the host and used for programming the UNO via its bootloader.  On the UNO, you'd instead need to use SoftwareSerial (or something similar) and pins other than D0 and D1.  **[Update: see the [original poster's own answer][1] containing the guide they ultimately used, making use of SoftwareSerial on pins 10 and 11]**

The ESP-01 can run Arduino sketches using the [ESP8266 Arduino][2] core and it may make a great deal more sense to not involve the UNO at all, and instead connect the distance sensor more or less directly to the ESP8266.

  [1]: https://arduino.stackexchange.com/a/80883/70020
  [2]: https://github.com/esp8266/Arduino


body:
So, I got it working with this information on this blog
Few things, my serial.begin(115200) where as in blog its 9600
Thanks @timemage for moving me in right direction
  [1]: https://medium.com/@cgrant/using-the-esp8266-wifi-module-with-arduino-uno-publishing-to-thingspeak-99fc77122e82


message:
DigiSpark attiny85 computer not detecting

I purchased a DigiSpark attiny85 off of ebay. Over the weekend I tried to get my computer to recognize the DigisSpark, but it won't recongnize it. When I plug the device in, the 'Device Connection' Sound alerts me and then a second or two the 'Device Disconnection' Sound alerts, then 'Device Connection' Sound, then the 'Device Disconnection' sound. This happens until I unplug the device. The light does turn on, but Windows (10) doesn't recognize the device, it just loops the sounds.

I am trying on a Windows 10 machine.
I installed the drivers from the DigiStump Github: https://github.com/digistump/DigistumpArduino/releases/download/1.6.7/Digistump.Drivers.zip

I do see 'Digispark Bootloader' in my device manager for a couple of seconds in my device manager.

I tried different cables. I tried to install the drivers on another computer and the same thing happens.

What should I try next? Am I missing other drivers?

body:
Unless, during the short time it shows in device manager, you see that it is missing a driver, it would seem you don't need to do anything further with drivers.  You didn't mention it saying it was missing a driver or as an "unrecognized" device, so I'm guessing you mean it doesn't *stay* recognised or that it isn't recognized as a *serial* device.  If I'm incorrect in that, do say. The fact that it is showing in device manager for any length of time suggests that your cables are fine.

I'm not a Digispark user, but as far I can understand what you're saying, the connecting and disconnecting (once at least) is [expected behaviour][1]:

> In addition remember the Digispark only shows up as a programmable
> device for **5 seconds**, after that it will start running its code (when
> it is new and un-programmed this means it will blink) and disappear or
> act like the USB device you programmed it to act like.

If anything in the sketch (or lack thereof) causes the board to reset or jump to the bootloader, it *would* continually reconnect for 5 second intervals.  They documentation suggests should blink, as in run a blink sketch that was put on the board before you received it.  But then you got this from ebay, so who knows what they did or did not put on it.  I haven't studied the [micronucleous bootloader][2] enough to know, but it wouldn't surprise me if it jumps to the sketch area irrespective of whether or not it's unprogrammed.  If it *is* unprogrammed then it is probably [nop-sliding][3], for lack of a more appropriate term, right back into the bootloader.

You're not going to see it recognized as a serial port device like a typical Arduino.  The bootloader uses a vendor specific protocol that will not list as a COM# (or /dev/ttyXYZ#) device.

Indications are that if you compile the blink sketch and "upload", the IDE will run the micronucleus programming tool which gives you a 60 second window for you to plug the board in, at which point it will load the board with the blink sketch.  After which it should blink the LED.  If unplugged and replugged, you can expect it to show up for 5 seconds on USB and if left alone should disconnect (electrically) from USB and begin blinking.

  [1]: http://digistump.com/wiki/digispark/tutorials/connecting
  [2]: https://github.com/micronucleus/micronucleus/tree/master/firmware
  [3]: https://en.wikipedia.org/wiki/NOP_slide


message:
ESP32 preferences. One error returned, all others work. SOLVED

I am using the Preferences.h library in my Arduino code. I initialize some values. I save them with the preference library. I then modify all the values, then read back the original saved values.

All the values, **except one**, are restored with the associated get instruction. The one still shows the modified value. I can't see why it is wrong.

Can someone point out my error with calibratedWeight? And if you see some other general errors with the code, please point them out. (I'm not a programmer)

```
#include <Preferences.h>

Preferences preferences;

int currentFile = 1;
int outputRate = 10;           // milliSeconds
float outputGain = 1.23;
int zeroWeight = 900;          // dac value to produce Zero on scale
int calibratedWeight = 2800;   // dac value equal to 100lb calibration weight.
float DACmultiplier = 20.1;

//---------------------------------------
void savePreferences() {
    preferences.begin("ScaleSetup", false);      // false for read/write
    preferences.putInt("currentFile", currentFile);
    preferences.putInt("outputRate", outputRate);
    preferences.putFloat("outputGain", outputGain);
    preferences.putInt("zeroWeight", zeroWeight);
    preferences.putInt("calibratedWeight", calibratedWeight);  // ???
    preferences.putFloat("DACmultiplier", DACmultiplier);
    preferences.end();
}

//---------------------------------------
void getPreferences() {
    preferences.begin("ScaleSetup", false);        // false for read/write

    currentFile = preferences.getInt("currentFile", currentFile);
    outputRate = preferences.getInt("outputRate", outputRate);
    outputGain = preferences.getFloat("outputGain", outputGain);
    zeroWeight = preferences.getInt("zeroWeight", zeroWeight);
    calibratedWeight = preferences.getInt("calibratedWeight", calibratedWeight);  // ???
    DACmultiplier = preferences.getFloat("DACmultiplier", DACmultiplier);
    preferences.end();
}

//============================================
void setup() {
  Serial.begin(115200);
  Serial.println();

  preferences.begin("ScaleSetup", false);        // false for read/write
  preferences.clear();
  preferences.end();
  delay(90);

  savePreferences();
  Serial.println("\n save preferences");
  Serial.println("\n Original asigned values. \n");

  Serial.printf("currentFile: %i\n", currentFile);
  Serial.printf("outputRate: %i\n", outputRate);
  Serial.printf("outputGain: %f\n", outputGain);
  Serial.printf("zeroWeight: %i\n", zeroWeight);
  Serial.printf("calibratedWeight: %i\n", calibratedWeight);  // ???
  Serial.printf("DACmultiplier: %f\n", DACmultiplier);

  Serial.println("\n modify values. \n");

  currentFile = 5;
  outputRate = 50;           // milliSeconds
  outputGain = 0.45;
  zeroWeight = 1333;         // dac value to produce Zero on scale
  calibratedWeight = 2200;   // dac value equal to 100lb calibration weight.
  DACmultiplier = 12.34;

  Serial.printf("currentFile: %i\n", currentFile);
  Serial.printf("outputRate: %i\n", outputRate);
  Serial.printf("outputGain: %f\n", outputGain);
  Serial.printf("zeroWeight: %i\n", zeroWeight);
  Serial.printf("calibratedWeight: %i\n", calibratedWeight);  // ???
  Serial.printf("DACmultiplier: %f\n", DACmultiplier);

  Serial.println("\n Get original saved preferences. \n");
  getPreferences();

  Serial.printf("currentFile: %i\n", currentFile);
  Serial.printf("outputRate: %i\n", outputRate);
  Serial.printf("outputGain: %f\n", outputGain);
  Serial.printf("zeroWeight: %i\n", zeroWeight);
  Serial.printf("calibratedWeight: %i\n", calibratedWeight);  // ???
  Serial.printf("DACmultiplier: %f\n", DACmultiplier);

//  Serial.println("Restarting in 10 seconds...");
  delay(10000);
//  ESP.restart();
}

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

The following is the result.

```
 save preferences

 Original asigned values.

currentFile: 1
outputRate: 10
outputGain: 1.230000
zeroWeight: 900
calibratedWeight: 2800
DACmultiplier: 20.100000

 modify values.

currentFile: 5
outputRate: 50
outputGain: 0.450000
zeroWeight: 1333
calibratedWeight: 2200
DACmultiplier: 12.340000

 Get original saved preferences.

currentFile: 1
outputRate: 10
outputGain: 1.230000
zeroWeight: 900
calibratedWeight: 2200
DACmultiplier: 20.100000
```

body:
At the end of the comments above I said I thought the problem was with the variable name length.

Today I tried the debug option and then ran the code. And the following error message was included in the com output.

[E][Preferences.cpp:163] putInt(): nvs_set_i32 fail: calibratedWeight **KEY_TOO_LONG**

So I guess I was right. I didn't know anything about the debug option before.


message:
How to control speed of 28BYJ-48 stepper motor without using library?

Iam using 28byj-48 stepper motor and I want to know how to control its speed without using any library. I got to know that we need to add delays in between steps but I don't know how much delay I need to add and how delay effects the rpm. It is very much helpful if anyone suggest me how to do this.

body:
A stepper motor always needs a driver. As the ULN2003 (or similar) driver is normally shipped together with the 28byj-48 motor, I will assume, that you have this driver.

The ULN2003 has 6 pins:
- Vcc and ground need to be connected to your power source. Note, that it is risky to connect Vcc to the 5V pin of the Arduino. While that might work, when there is no load on the motor, a loaded stepper motor can draw rather high currents. Letting these current run through the Arduino might fry the voltage regulator or the power switching diode. High currents should always flow past the Arduino, not through it.

- The other 4 pins (which are marked as IN1 to IN4 on my ULN2003 driver board) are for controlling the phases. You need to connect these 4 pins to 4 individual digital outputs on your Arduino. As these are the phases of the stepper motor, you need to activate them in the correct order. You have this pattern

        1000
        0100
        0010
        0001

    for full steps, and this pattern

        1000
        1100
        0100
        0110
        0010
        0011
        0001
        1001

    for half steps. Each digit of each number represents the status of the corresponding phase; 1 means activated/HIGH, 0 means deactivated/LOW. To move the stepper motor forward, you move in the list of phases down. To move backwards, you move up in the list.

When using a stepper motor, the speed is determined by the number of steps per time interval. Let's assume, we want to use `delay()`, which is really easy, though not recommended (see explanation below), we can do steps and `delay()` inbetween:

    void loop(){
        step();
        delay(10);
    }

This code would do a step and then delay for 10ms. Thus we have about 1 step every 10ms. With `64*64=4096` steps per revolution (the motor itself seems to have 64 steps; additionally there is a gear with ratio 64 mounted on it; this might be different for you) we get a full revolution every 4.096s. When you use half the `delay()`, the speed will be double: with 5ms delay we get a full rotation every 2.048s. So you can use the `delay()` to set the speed of the motor.

Now we need the `step()` function, that I used above. There are multiple ways of writing this in code. I would propose to put the pins and phases into arrays and iterate through them with a static variable, which holds the current position in our phase pattern. Something like this:

    //in global scope defining the pins for the phases
    int stepper_pins[4] = {2, 3, 4, 5};

    void step(bool forward){
        const uint8_t phase_pattern[][4] = {
            {1,0,0,0},
            {0,1,0,0},
            ...
        };
        static uint8_t current_step = 0;
        if(forward){
            current_step = (current_step + 1) % 4;
        } else {
            current_step = (current_step - 1) % 4;
        }
        for(uint8_t i=0;i<4;i++){
            digitalWrite(stepper_pins[i], phase_pattern[current_step][i]);
        }
    }

We hold the phase pattern in a 2-dimensional array. The variable `current_step` is declared `static`, so it will keeps its value between the executions of the function. Then - depending on the parameter `forward` - we increment or decrement the current step and take that value modulo 4 (the number of phase patterns). That ensures, that `current_step` stays in the index range of our phase pattern array and will wrap around from the end of the pattern to the start and vice versa. After that, we loop through the 4 stepper pins and set them according to the current element in the `phase_pattern` array. You can easily adept that code for half steps.

Note, that this code is totally untested. Also this can be reached with way less code (at least for full steps), but I think this code is better understandable.

Now: Why not using `delay()`? This function will block the execution of other code. In that time the Arduino is just fiddling thumbs. In general that is considered bad practice. It is good, when you only need that one functionality and no responsiveness. But lets assume, you want to add a button, so that the motor reacts to your button presses. Long `delay()` calls will impact the responsiveness of your code. So instead you could use a non-blocking coding style. In the Arduino world this is easily done with the `millis()` function, which returns the number of milliseconds since startup and thus acts like a clock. Refer to the `BlinkWithoutDelay` example, that comes with the Arduino IDE, and to the many tutorials on the web, that you can find with search terms like "Arduino millis tutorial" or something like that.

---
EDIT:

> how your code controlling the motor speed?

The `delay()` call is determining the motor speed. If you want to change the speed, you need to change the value of the delay. You didn't mention any input device, so I just leave the speed constant. But of course you can define a variable for the delay and change that delay based on some input device. How exactly that is done depends on your requirements, mainly what type of input you want to use.

> if we didn't specify any delays in between steps, will it spin at its max rpm?

When you don't use any delay, then most likely your code will run too fast for the motor. The driver will set the motor phases very very fast. So fast, that the motor cannot follow that (because it has a specific inertia). (Much like the wheels of your car can loose the grip on the street and spin without moving the car, the stator of the motor can loose the magnetic grip on the rotor, which leads to further rotating phases, but a rotor, that is standing still) So you reach the maximum speed before that and it depends on the motor, the driver, how much load is on the motors and how much current your power source can give you (I once tried to provide 3 of these motors with a 1A power supply, but they moved very weak, until I upgraded to a bigger power supply, that can provide about 5A, I think). You need to test yourself, how fast you can drive your motors. So try to lower the delays step by step, until the motor cannot move in your setup anymore. Then you have the minimum delay, and the maximum speed.

Note: The `delay()` function won't be accurate for very low delays in the single digit milliseconds. In that case you might wanna use `delayMicroseconds()`, which is more accurate in that range and also can get in you in the microsecond range.


message:
Public variable in class not incrementing

I'm not sure what is wrong with my code, but whenever I call `addNewLine`, the `linesInserted` variable is not updating correctly. When I print the value of `linesInserted` inside of the `addNewLine` method, it shows as incrementing, but when I print the value inside of the `draw` method, it shows that it is 0.

I have tried different increment operators (`linesInserted += 1` and `linesInserted = linesInserted + 1`). Oddly enough, when I do `linesInserted = 99` instead of `linesInserted++`, it sets the value correctly. I'm wondering if I am possibly messing up a reference somewhere?

```
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1331.h>
#include <SPI.h>

class Character {
  public:
    char** lines; // using char for 8 bit integer
    int sizeOfLines;
    char symbol;
    Adafruit_SSD1331* display;
    int width;
    draw(int x, int y, int color);
    addNewLine(char startX, char startY, char endX, char endY);
    int linesInserted = 0;
};

Character::draw(int x, int y, int color) {
  if (linesInserted < sizeOfLines) {
    display->setCursor(0, 39);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "SYMBOL %c\nWASTED MEMORY", symbol);
    Serial.println(symbol);
    Serial.print(linesInserted);
    Serial.print(" ");
    Serial.println(sizeOfLines);
    display->print(buf);
  }
  for (int i = 0; i < sizeOfLines; i++) {
    char* line = lines[i];
    display->drawLine(line[0] + x, line[1] + y, line[2] + x, line[3] + y, color);
  }
};

Character::addNewLine(char startX, char startY, char endX, char endY)  {
  linesInserted++;
  if (linesInserted > sizeOfLines) {
    display->setCursor(0, 15);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "ERROR\nSYMBOL %c\nTOO MANY LINES", symbol);
    display->print(buf);
  } else {
    lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};
  }
};
```

EDIT: Git repo to the project is added - https://github.com/Pyrodron/charger-destination-board

body:
It would be good to see how this is used rather than just having a class with no context.
But I'd start by removing unnecessary parts, like the display pointer, and you could always use a simple program, like ideone.com to compile quickly and check for errors.

As I read through it I see 2 flaws with memory management.
This block is using the size of a char pointer instead of a character. I don't understand what you want this code to do.

    (char**) malloc(sizeof(char*) * Char.sizeOfLines);
Try something more like:

    (char**) malloc(sizeof(char) * <numberOfCharsPerLine> * Char.sizeOfLines);

But then even though you're allocating memory for a whole block of lines, then each time you add a new one, you're allocating memory for a new line.

    lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};

Instead try something like:

    lines[linesInserted - 1][0] = startX;
    lines[linesInserted - 1][1] = startY;
    ...


body:
It's difficult to pin down the exact details as to why the problem it's manifesting exactly the way it is. But, in short, it's fair to say you're running out of memory.

First, just a note:  The code I'm testing with (because it compiles) is the code out of your github repo, which used a `char` type variable for `linesInserted` and had a commented-out `println(linesInserted);`, so it kind of seems like at one point you'd been trying to print the count as character, specifically non-printable control characters.  So that might may have been confusing you.  I uncommented it and added a `, DEC)` parameter to it (rather than casting) to coerce println into treating it as an int.

I tested your code without the display library in a PC environment to allow me to run valgrind on it.  It didn't find anything; I wasn't necessarily expecting it to.  But, I did crudely instrument your code in this enviroment to see that you're calling `malloc()`/`new` 124 times, for a total of 500 bytes, but importantly this does not include the structure heap overhead, which is significant because you're `new`-ing tiny four-character chunks.

Then I ran your code as compiled for an AVR.  Because I don't have your display, and wanted to match your environment as closely as possible, I left the display code in but NOPed out a few function calls that would have screwed up my test rig.

The primary finding is that you're dangerously close to "running out" of memory:

000005e0 | 01 00 02 04  00 01 00 02 - 00 04 00 03  01 03 05 04 | ........ ........
000005f0 | 00 01 03 02  03 04 00 01 - 06 02 06 04  00 00 00 00 | ........ ........
00000600 | 00 04 00 02  00 02 00 04 - 00 01 01 01  01 04 00 00 | ........ ........
00000610 | 02 00 02 04  00 02 02 02 - 02 04 00 01  03 01 03 04 | ........ ........
00000620 | 00 00 04 00  04 04 00 02 - 04 02 04 04  00 01 05 01 | ........ ........
00000630 | 05 04 00 00  06 00 06 04 - 00 02 06 02  06 00 00 00 | ........ ........
                                                      ^^
                                              [__brkval]

                          [SP]
                           VV
000006b0 | 00 00 00 00  00 00 b7 09 - 03 01 01 06  02 a5 02 00 | ........ ........
000006c0 | 00 00 00 01  00 57 05 06 - cc 00 03 8f  0f 01 00 00 | .....W.. ........
000006d0 | 00 01 00 00  03 00 03 00 - 00 00 07 02  a4 00 01 00 | ........ ........
000006e0 | 03 02 a4 00  05 f8 0d 06 - f6 00 03 00  00 08 c3 08 | ........ ........
000006f0 | de 00 01 00  01 80 1a ed - 02 04 00 41  a4 02 04 00 | ........ ...A....

There's 120 byte separation between the edge of the heap and the stack pointer.  The implementation of the `malloc` that I ran this under checks to see whether or the the stack pointer is within `128` (`__malloc_margin`) bytes.  As your code was building in my environment, without the counter-printing in, this managed to not-fail to allocate.  However adding a single additional call to `addNewLine` was enough to cause `malloc()` via `new` to fail.  So you are indeed right on the edge.  And you have **no** checks to see if `malloc` or `new` returning `nullptr`.

You're making one allocation after another without deallocation anything, which is resulting in a fairly simple pattern of the heap edge advancing by the requested size of your allocation plus 2 bytes each time.  So that's about 248 bytes waste in just heap structure.

I'm not sure on the exact cause of your counter being overwritten, assuming that's what's actually happening.  In fact I was having a hard time finding an case where it would overwrite anything in memory with the code as you have it, but here's a good candidate:

```c++
lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};
```

With generated code looking like:

0x24c6 [addNewLine+244] ldi    r25, 0x00       ; 0
0x24c8 [addNewLine+246] call   0x3830  ;  0x3830 [malloc]
0x24cc [addNewLine+250] movw   r30, r24
0x24ce [addNewLine+252] st     Z, r10
0x24d0 [addNewLine+254] std    Z+1, r11        ; 0x01
0x24d2 [addNewLine+256] std    Z+2, r17        ; 0x02
0x24d4 [addNewLine+258] std    Z+3, r16        ; 0x03

So, if `malloc()` fails, apparently the `new` statement will just assume that it didn't and goes ahead and writes into the memory at 0x0000 (nullptr) anyway, ugh.  I think this is because technically you're calling the normal new that is supposed to throw an exception on failure.  But there are no exceptions with the way avr-g++ is set up for Arduino.  [As it exists in ArduinoCore-avr version 1.8.3][1], the new code just returns what malloc returns and the compiler thinks an exception will be in progress if it fails.  Normally you would call the std::nothrow version of new[] that returns nullptr on failure, as in:
```c++
lines[linesInserted - 1] = new(std::nothrow) char[4]{startX, startY, endX, endY};
// check lines[linesInserted - 1] against nullptr here
```

However, there's no facility to do that in 1.8.3.  The master as of writing [appears to have addressed this][2], but that's not shipping yet.

---

The short answer to this is basically: **Don't do that.** That is:

* Avoid dynamic allocation altogether where possible.

* This was mentioned in the comments, but it's worth repeating, use flash where you can.  Besides getting your character data into `PROGMEM`, you also have some string literals that can be moved into flash by way of `F()`.

* To the extent that you're doing dynamic allocation requests:

  * Check to see that they're actually succeeding

  * Make as few requests as possible.

   * Do them up-front at the beginning of the code.  The "up-front" part you're more or less already doing, so that much is good.

   * It seems if you're going to dynamically allocate under core version 1.8.3 and you're at all in danger of having an allocation failure, it is important that you *not* use new, since doing so may cause it to overwrite memory for the initialization/construction part after the allocation proper has failed.  Alternately, seriously consider modifying your Arduino core's new.cpp file to do something like call `abort()` if `malloc()` returns `nullptr`, at a minimum, if not something more sensible.  Otherwise, this could drive you insane.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/cores/arduino/new.cpp#L25
  [2]: https://github.com/arduino/ArduinoCore-avr/blob/6d29250/cores/arduino/new.cpp#L68


message:
I Can't Connect to my MQTT server via arduino

I have mosquitto MQTT installed on my VPS server which I can subscribe and publish to it using paho client thorugh websockets. However when I tried to connect to it through Arduino, I get the following error:

    Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
    Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
    Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

I uploaded the following code to arduino:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>

    // Update these with values suitable for your network.

    const char* ssid = "IOT";
    const char* password = "11112222";
    const char* mqtt_server = "burooq.com";

    WiFiClient espClient;
    PubSubClient client(espClient);
    unsigned long lastMsg = 0;
    #define MSG_BUFFER_SIZE (50)
    char msg[MSG_BUFFER_SIZE];
    int value = 0;

    void setup_wifi() {

      delay(10);
      // We start by connecting to a WiFi network
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

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

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

      randomSeed(micros());

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }

    void callback(char* topic, byte* payload, unsigned int length) {
      Serial.print("Message arrived [");
      Serial.print(topic);
      Serial.print("] ");
      for (int i = 0; i < length; i++) {
        Serial.print((char)payload[i]);
      }
      Serial.println();

      // Switch on the LED if an 1 was received as first character
      if ((char)payload[0] == '1') {
        digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
        // but actually the LED is on; this is because
        // it is active low on the ESP-01)
      } else {
        digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
      }

    }

    void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Create a random client ID
        String clientId = "ESP8266Client-";
        clientId += String(random(0xffff), HEX);
        // Attempt to connect
        if (client.connect(clientId.c_str())) {
          Serial.println("connected");
          // Once connected, publish an announcement...
          client.publish("test", "hello world");
          // ... and resubscribe
          client.subscribe("test");
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 5 seconds");
          // Wait 5 seconds before retrying
          delay(5000);
        }
      }
    }

    void setup() {
      pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
      Serial.begin(115200);
      setup_wifi();
      client.setServer(mqtt_server, 1883);
      client.setCallback(callback);
    }

    void loop() {

      if (!client.connected()) {
        reconnect();
      }
      client.loop();

      unsigned long now = millis();
      if (now - lastMsg > 2000) {
        lastMsg = now;
        ++value;
        snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
        Serial.print("Publish message: ");
        Serial.println(msg);
        client.publish("test", msg);
      }
    }

<!-- end snippet -->

i checked my server mosquitto ports which shows

    mosquitto 10436       mosquitto    4u  IPv4   46043      0t0  TCP 127.0.0.1:1883 (LISTEN)

I checked my conf file and it has

    listener 1883 localhost

so how what's wrong within my code or settings that prevents me from connecting to my server?`

body:
This is the problem:

> mosquitto 10436       mosquitto    4u  IPv4   46043      0t0  TCP
> ***127.0.0.1***:1883 (LISTEN)

Your MQTT server is listening only on port 127.0.0.1.  That will accept ***local*** incoming connections only but nothing from another IP address.

The IP 127.0.0.1 is the LOCAL ONLY IP address.  You need to reconfigure your MQTT server to listen on either IP 0.0.0.0 or whatever that server's actual IP address is.

Check your mosquitto.conf file and look for the line that begins with "bind_address":

    listener 1883 localhost

change this to:

    listener 1883 0.0.0.0

and restart your MQTT server.


message:
How can a DC motor (toy) be run with only an Arduino and transistor without an external power source?

I'm trying to understand this circuit found [here][1].
[![enter image description here][2]][2]

  [1]: https://www.instructables.com/How-to-drive-a-DC-Motor-with-Transistor-Arduino-Tu/
  [2]: https://i.stack.imgur.com/1j0ti.png

I understand that the Arduino cannot directly run a DC motor because it can only supply 40mA of current and also due to the back EMF which can damage it. I can also understand this circuit if they used an external power supply and used the transistor as a switch to drive the DC motor. But, I do not understand this configuration shown in the pic where the power supply is the arduino itself.

body:
Your confusion lies in *what* can "supply" power.

Your assumptions are all correct *for an IO pin*. However the Arduino has *more* than just IO pins. It has power pins.

These power pins are not controlled in any way by the microcontroller - they are merely connections into the power supply circuit that also powers the microcontroller.

So in that circuit the Arduino's power supply is shared between the Arduino (the MCU) and the motor.

The 5V pin of the Arduino can supply up to 450mA (when powered from USB - 500mA less about 50mA for the MCU) or up to 800mA when supplied with about 6.5V into the barrel jack (any more than that will cause excess heat to be dissipated which will reduce the maximum current the 5V regulator can handle before shutting down).


message:
Weak Arduino output pins

I've been learning Arduino for a while, and for my next project I'm attempting to build a drone. When I tested the motors that I purchased before, they seemed to work fine using the PWM pins and I saw no need for a motor driver.

However, now, a week later, the PWM pins are much too weak. I've set them to OUTPUT mode and HIGH.

Should the basic digital output pins be able to run fairly small drone motors like mine?

body:
The Absolute Maximum is 40 mA per pin, but you shouldn't go even close to that; max. 20 mA per pin is about where you want to be. Total current (all pins) shouldn't exceed 200 mA.

Only you know what current your "fairly small" motors pull, but you may have fried a few IO pins.

Also, you need flyback (or maybe bidirectional TVS) diodes and a few capacitors on your motors to keep noise and inductive kick-back away from your pins. Motor driver modules often have these installed, but your Arduino pins don't. Inductive kick-back can easily kill IO pins also.


body: Time to purchase another Arduino or use the other pins. Before you connect the new one you need to get a method of driving the motors. Keep in mind they are inductive and will reverse polarity and kick back a voltage that will keep rising until adsorbed. If you will be reversing them pick a MOSFET bridge to drive them. If just on/off/PWM pick a Logic rated avalanche rated N-Channel MOSFET with a high enough voltage and current rating. If your Arduino is 3V3 you need to be sure the gate will be on at about 2.5V. Connect all the grounds together and connect the source of the MOSFET to ground as well. Place something in the 25-50 Ohm resistor from the Arduino pin to the Gate of the MOSFET. Then connect the motor to the drain and the appropriate + supply. No diodes need as it has one built into the MOSFET designed for this. If you want the MOSFET off place something like a 10K resistor from the Arduino pin to ground. Remember a Power Supply the Arduino is NOT! While you are waiting on the parts go through several tutorials on the arduino and motors. There are some good ones and some not so good.


message:
How can I execute two functions at the same time?

```c++
#include <Servo.h>

Servo myservo;
int pos = 0;
int servo_pin = 3;
int led_pin = 4;

void setup() {
  myservo.attach(servo_pin);
  Serial.begin(9600);
  pinMode(led_pin,OUTPUT);
}

void loop() {
  if (Serial.available()) {
    char serial = Serial.read();
    if (serial == '2') {
      servo();
    }
    if (serial == '1') {
      digitalWrite(led_pin,HIGH);
    } else if (serial == '0') {
      digitalWrite(led_pin,LOW);
    }
  }
  delay(100);
}

void servo() {
  for (pos = 0; pos <= 180; pos += 1) {
    myservo.write(pos);
    delay(5);
  }
  delay(5000);  // problem is here
  for (pos = 180; pos >= 0; pos -= 1)
    myservo.write(pos);
  delay(5);
}
```

When I run this code and send '2', the `servo()` functions start, but it includes a delay function.

Now I want to send '2' and then send '1'. When I do this, the first servo starts, but the LED starts **after** the servo function. I want to start this at the same time.

body:
Make little task using `millis` function.

    // GLOBAL VARIABLE
    uint32_t taskMillis = 0;

    ....

    // IN LOOP
    if (taskMillis && millis() - taskMillis >= 5000)
    { /* SWITCHES DIRECTION */ }

With that code you can make two tasks(one to switch direction, second to move Servo by X deg).
Here is video about this topic.

https://www.youtube.com/watch?v=v5SpPXMmHJE

I hope this anwser will help you.


body:
The short answer is no. Delay causes your Arduino to stop dead in its tracks, and do NOTHING else until the specified time has passed. (You can still service interrupt service routines, but ignore that.)

The answer is to rewrite your code to use `millis()` instead of delay. You record the current `millis()` value, and compare the new time to `millis()` to see if enough time has passed.

For the most part you should stop using the `delay()` function and forget exists. It will get you into trouble.

Do a Google search on "Arduino blink without delay" and study the project that comes up to learn this approach.


message:
How to power Arduino Uno from L298N motor driver's 5v terminal?

I am trying to setup L298N motor driver controller with my Arduino. Different online schematics about how to connect them are mostly similar - but they differ in powering the Arduino from the drive controller's 5v pin.

I am connecting 7.5v to the Vin and Gnd to the motor driver controller screw terminal , and I wish the power the Arduino from the 5v screw terminal. Since I am planning to use the 5v screw terminal as output I am choosing to leave the 5v jumper on.

Here are 3 of the schematics I've found online,

 1. Source [Homemade-circuits](https://www.homemade-circuits.com/l298n-dc-motor-driver-module-explained/):
[![enter image description here][2]][2]

This is what I was expecting to see. But from [Arduino Uno Rev3 Faq](https://store.arduino.cc/usa/arduino-uno-rev3),

```
Vin -- The input voltage to the Arduino board when it's using an external power source (as opposed to 5
volts from the USB connection or other regulated power source). You can supply voltage through this pin,
or, if supplying voltage via the power jack, access it through this pin.

5V -- This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power
either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V).
Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.
```

*This one looks wrong to me.* I am under the assumption that Vin pin is expecting 7-12V because it's connected to voltage regulator which will cause a 2v drop. Which mean I should not connect 5v from the motor controller to Vin - making this schematic incorrect. Is my analysis correct? [Here](https://arduino.stackexchange.com/a/4460/34157) is an answer that says I can not use the 5v pin to power an Arduino since it an input pin and not an output pin.

 2. Source [teachmemicro](https://www.teachmemicro.com/use-l298n-motor-driver/):
[![enter image description here][3]][3]

*This one looks ok to me* since the 5v source at motor controller is a regulated source and that's what exactly Arduino is expecting on 5v pin based on aforementioned FAQ. Can I implement is safely?

 3. Source [Instructables](https://www.instructables.com/L298N-MOTOR-DRIVER-MODULE/):
[![enter image description here][1]][1]

*I do not know if it's correct or not.* Notice that the 5v screw terminal is not connected to Arduino in any way. Is it setup going to work? I am wondering where the Arduino is getting its power from?

I am wondering which schematic should I follow. I am hesitant to hook up my L298N motor driver and Arduino without without understanding why each schematic is choosing to power the Arduino differently.

  [1]: https://i.stack.imgur.com/P7d7p.png
  [2]: https://i.stack.imgur.com/thgTB.png
  [3]: https://i.stack.imgur.com/3ZNci.png

body:
Clearly, your design (last image) won't work, because as you expected, the Arduino won't have power. It is a feasible design however, if you use it while still developing and you have the USB cable connected. Because then the Arduino will draw the power for itself from there.

Vin expects 7-12V, but allows an unregulated input (which is fine for connecting a battery). You can use the 5V pin to supply power from a regulated output as well. Since (pressumably) the output of the motor driver is regulated, that could work, however I would not advise it and directly connect the battery to the VIn pin.

Connecting the 5V output of the motor driver to the VIn pin *might* work. While this will likely not destroy anything, it may be to low to drive the internal regulator, which might cause the Arduino to run on undervoltage levels. You might see weird behavior in that case (pins not correctly recognizing high from low, incorrect measurements on analog inputs or even software crashes).


body:
I was facing same problem but I solved it by attaching L298 power pins to icsp power pins

![icsp pins](https://csharpcorner-mindcrackerinc.netdna-ssl.com/article/hex-file-and-icsp-pins-of-arduino/Images/image002.jpg)

Remember the voltage should be constant and there should not be any fluctuation other wise atmega will go in programming mode


message:
Is it possible to generate an exact 15 kHz clock pulse using an Arduino?

I want to generate a 15 kHz pulse with an Arduino using Timer1, but the problem is that if we want a 15000 Hz clock we need to initialize the timer with *1/15000* seconds or *66.66* microseconds, but we can only pass integers without any decimal precision in the `Timer1.initialize(66);` function which generates a frequency of 15155 Hz.

So is it possible by any other means to generate an exact *15000 Hz* or frequencies between *15000 Hz - 15155 Hz*?

```c++
#include <TimerOne.h>

void setup() {
  pinMode(9,OUTPUT);
  Timer1.initialize(66);  // Frequency, 100 µs = 10 kHz
  Timer1.pwm(9,255);
}

void loop() {}
```

body:
Since the timer1 library only accepts whole numbers for the µs parameter you get a error. You could skip using the library and configure the timer directly. Or you could have a look at the [source code of the library](https://github.com/PaulStoffregen/TimerOne/blob/master/TimerOne.h#L189-L213), and see that you can kind of bypass the limitation it has by only calculating a more accurate value for the `ICR1` register.

Look at `cycles = ((F_CPU/100000 * microseconds) / 20);`. If you were to insert your 66.66666µs into this, instead of 66µs, you'd get `533` instead of `528`.

This value is then used to set the PWM frequency in line 213. So you'd need to overwrite the `ICR1` register with the more accurate value.

Your final code should look like:

```
pinMode(9,OUTPUT);
Timer1.initialize(66);
ICR1 = 533;
Timer1.pwm(9,255);
```

PS you might need to tweak this 533 value to get an even more accurate resulting frequency.


body:
*In answer to a comment from the OP asking for another microcontroller that can do this, and in addition to Majenko's reply comment:*

A SAMD21G running at 48 MHz (as seen on some Arduinos) can make 15 kHz, in several ways.

Note that this assumes that the clock is exactly 48 MHz, and stable, and both assumptions could well be wrong, unfortunately. It helps if the clock is derived from a crystal; not all SAMD21G-based Arduinos do that, if any. This possible lack of clock precision and stability applies to all MCUs.

The SAMD21G does have a fractional PLL, and you can of course adjust the PER register, so some fine-tuning is possible if you have the equipment to measure the actual output frequency.

If you decide to go with one of the SAMD21G-based Arduinos: there is a [PWM library][1] for those (I know it well, as I wrote it) that will let you set a clock divider, a prescaler, and a resolution, which should make it easy enough to arrive at a (nominal) 15 kHz. There's a frequency table under "extras".

  [1]: https://github.com/ocrdu/Arduino_SAMD21_turbo_PWM


body:
You can get pretty close if you program Timer 1 directly (not
through the library), and have it run with the prescaler set to 1.
Ideally, you want the period of the timer in clock cycles to be:

F\_CPU / 15 kHz = 16,000 kHz / 15 kHz ≈ 1066.67 CPU cycles

If you round this to the nearest integer, you get

F\_CPU / 1,067 = 16,000 kHz / 1,067 ≈ 14.9953 kHz

This is about 0.03% too slow, well within the tolerance of the ceramic
resonator clocking the Uno.

Here is my attempt at this. I have tested it.

```c++
constexpr float PWM_FREQUENCY = 15e3;  // 15 kHz
constexpr uint16_t PERIOD = round(F_CPU / PWM_FREQUENCY);

void setup() {
    // Configure Timer 1 for 15 kHz PWM on pin 9 = PB1 = OC1A.
    DDRB  |= _BV(PB1);    // set pin as output
    TCCR1B = 0;           // stop timer
    TCCR1A = _BV(COM1A1)  // non-inverting PWN on OC1A
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS10);   // clock @ F_CPU
    ICR1   = PERIOD - 1;  // period
    OCR1A  = PERIOD / 4;  // duty cycle
}

void loop(){}
```


body:
A better way to do the above *average* 15 kHz (or any other frequency) is with a phase accumulator scheme.  There are no IF tests; on each tick of an interrupt, you add a step to an accumulator and output the state of its MSB.  This can give incredible resolution, and is probably the best you can do.  But though the *average* frequency will be dead-on, the jitter can be terrible.  I use this method in my open-source DaqPort sketch
<https://www.daqarta.com/dw_rraa.htm#00ff>, which is used by DaquinOscope
<https://www.daqarta.com/dw_rroo.htm> and Arduino_Oscillators <https://www.daqarta.com/dw_rrss.htm> mini-apps running in Daqarta.  There's also a Jitter_Tbl macro to compute the jitter for arbitrary sample rates and output frequencies.  Although not relevant here, this phase accumulator method can also go to exceptionally *low* frequencies, into the micro-hertz range, and the jitter is extremely small there.


body:
I can get within 5 Hz of 15,000 using a 16 MHz clock on a Nano, Uno or 2560. Here is the code...

    // RTM_TimerCalc 1.20
    // Timer-1 Mode_14_16Bit_Fast_TOP_is_ICR

    TCCR1B = 0x18; // 0001 1000, Disable Timer Clock
    TCCR1A = 0xA2; // 1010 0010

    ICR1 = 1067-1;
    OCR1A = (int) (ICR1 * 0.25);
    OCR1B = (int) (ICR1 * 0.50);
    TCNT1=0x0;

    // UnComment following lines for UNO-NANO Timer-1 Pins
    // pinMode(9, OUTPUT);  // OC1a
    // pinMode(10, OUTPUT); // OC1b

    // UnComment following lines for 2560 Timer-1 Pins
    // pinMode(11, OUTPUT);  // OC1a
    // pinMode(12, OUTPUT);  // OC1b

    TCCR1B |= 1; // Prescale=1, Enable Timer Clock

Here is the Error Results...
ASK:       15,000 Hz
CALC:     14,995.3139643861 Hz
OFFSET:  -4.6860356139 Hz

hth


message:
Time signal. Determine the presence of pulses and their duration

I want to detect the exact time signal from an FM radio station. The signal is transmitted in the form of 5 short pulses and one long one. My task is to determine the presence of a pulse in the audio data stream and its duration.
It is understood that the signal is received by the radio receiver and then the audio signal is fed to the atmega microcontroller.
The pulse duration varies in the range of 100 ... 560 ms

How can you control the appearance of these pulses using a microcontroller, and also determine their duration? Below is an example of computer processing. The same is required to be implemented on a microcontroller.

1. I have a reference recorded signal in WAV format.
This recorded signal from the output of the radio receiver contains both the speaker's speech, music, and the **exact time signal**:
[![enter image description here][1]][1]

2. I know the time signal is centered at 1 kHz, so
apply filtering to this signal. The filter has the following frequency response:
[![enter image description here][2]][2]

The signal after the filter looks like:
[![enter image description here][3]][3]

3. It remains to apply the threshold device and duration selection.
However, I do all this in an audio editor to understand the ongoing processes. In fact, I need to implement this on an arduino, so I really hope for your tips, because I don't know how to implement a filter on an arduino for one frequency, and I also don't know how to make a pulse detector and a meter for its parameters.

Below is the result of homodyne, the method suggested in the comments. On the test signal, the algorithm was able to identify the required pulses! It remains to write a sketch where there is a detection threshold and definition of the duration!
I was able to write a condition, when the threshold is exceeded, the LED turns on, and turns off otherwise. But I don't know how to make the definition of duration yet ...[![enter image description here][4]][4]

*Added after a few days:*

I was able to assemble the entire structure, the sketch below does the following:
1. Listens to the audio signal coming to the analog input of the arduino from the radio receiver on the RDA5807M microcircuit, through an amplifier on one transistor, which provides signal amplification and offset to the positive range.

2. Performs homodyne processing: selects only the signal with a frequency of 1 kHz, all other frequencies are suppressed

3. Selects the optimal detection threshold for finding the exact time signal of 1 kHz frequency at the background level.

4. Calculates the duration of each pulse

5. Finds the exact time by the last impulse using the recalculation formula.

Thus, at the moment I get the exact time digit in the serial port monitor.

But the end result I want to get is setting the resulting digit on a seven-segment display. Having looked at the sketches of his work, I found that the values in the loop are constantly processed there, which again slows down the microcontroller, but for me this is unacceptable. As I understand it, you need to write a separate function into which you pass the value of the hour and set this value on the indicator only once an hour. But I don’t know how to implement it. I ask for help!

    / * Last edited on January 25, 2021.
       1 kHz homodyne signal detection

      This program continuously samples analog input A0 and uses a homodyne
      detection circuitry for signal identification at 1 kHz (+/- 24 Hz at -3 dB).

      The A / D converter is set to "free running mode" and takes one sample every 104 µs.
      The samples are multiplied by two generated 1 kHz signals ("local oscillator") in quadrature to each other.
      The products are then low-pass filtered with a time constant of 64 sampling periods (6.656 ms),
      which gives (I, Q) signals with a bandwidth of 24 Hz.
      Finally, the signal strength is calculated as I ^ 2 + Q ^ 2.

      The program is designed for Arduino Uno and will probably work on any AVR based Arduino,
      having an ADC and operating at a frequency of 16 MHz.

      For a detailed explanation, see
      http://arduino.stackexchange.com/a/21175

      Posted by: 2016 Edgar Bonet Orozco.
    * /

    // Here is everything related to the parameters of the RDA5807M receiver:
    #include <Wire.h>

    #define RDA5807M_RANDOM_ACCESS_ADDRESS 0x11
    // registers
    #define RDA5807M_REG_CONFIG 0x02
    #define RDA5807M_REG_TUNING 0x03
    #define RDA5807M_REG_VOLUME 0x05
    #define RDA5807M_REG_RSSI 0x0B
    // flags
    #define RDA5807M_FLG_DHIZ 0x8000
    #define RDA5807M_FLG_DMUTE 0x4000
    #define RDA5807M_FLG_BASS 0x1000
    #define RDA5807M_FLG_ENABLE word (0x0001)
    #define RDA5807M_FLG_TUNE word (0x0010)
    // masks
    #define RDA5807M_CHAN_MASK 0xFFC0
    #define RDA5807M_CHAN_SHIFT 6
    #define RDA5807M_VOLUME_MASK word (0x000F)
    #define RDA5807M_VOLUME_SHIFT 0
    #define RDA5807M_RSSI_MASK 0xFE00
    #define RDA5807M_RSSI_SHIFT 9

    uint8_t volume = 7; // 0..15
    uint16_t freq = 938; // 107.3FM
    uint16_t reg02h, reg03h, reg05h, reg0Bh;
    // Receiver end

    unsigned long startTime; // Turn on two timers, this
    unsigned long elapsedTime; // and this one
    int threshold = 300; // Set the maximum noise level
    boolean timing = false; // I do not know...

    #include <util / atomic.h>

    // The analog input used must be between A0 and A5.
    const uint8_t analog_in = 0;

    // The frequency we want to define, in Hz.
    const float SIGNAL_FREQ = 1000.0;

    // Time bits.
    const float SAMPLING_FREQ = F_CPU / (128 * 13.0); // 9.615 kHz
    const long PHASE_INC = round (SIGNAL_FREQ / SAMPLING_FREQ * (1L << 16));
    const int LOG_TAU = 6; // tau = 64 / SAMPLING_FREQ = 6.656 ms

    // Set the ADC to constant conversion mode "free running mode"
    static void configure_adc ()
    {
      ADMUX = _BV (REFS0) // ref = AVCC
               | _BV (ADLAR) // left adjust result
               | analog_in; // input channel
      ADCSRB = 0; // free running mode
      ADCSRA = _BV (ADEN) // enable
               | _BV (ADSC) // start conversion
               | _BV (ADATE) // auto trigger enable
               | _BV (ADIF) // clear interrupt flag
               | _BV (ADIE) // interrupt enable
               | 7; // prescaler = 128
    }

    // Demodulated (I, Q) amplitudes.
    volatile int16_t signal_I, signal_Q;

    // Interrupt handler is called every time the ADC is ready to read.
    ISR (ADC_vect)
    {
      // Read the ADC and convert to a signed number.
      int8_t sample = ADCH - 128;

      // Update the phase of the local oscillator.
      static uint16_t phase;
      phase + = PHASE_INC;

      // Multiply samples by square waves in quadrature.
      int8_t x = sample;
      if (((phase >> 8) + 0x00) & 0x80) x = -1 - x;
      int8_t y = sample;
      if (((phase >> 8) + 0x40) & 0x80) y = -1 - y;

      // First order low pass filter.
      signal_I + = x - (signal_I >> LOG_TAU);
      signal_Q + = y - (signal_Q >> LOG_TAU);
    }

    / * Return the power reading. * /
    static uint16_t get_power_reading ()
    {
      int16_t I, Q;
      ATOMIC_BLOCK (ATOMIC_RESTORESTATE) {
        I = signal_I;
        Q = signal_Q;
      }
      return sq ((int8_t) (I >> LOG_TAU)) + sq ((int8_t) (Q >> LOG_TAU));
    }

    // *********************************************** ***********************
    void setup ()
    {
      configure_adc ();
      Serial.begin (9600);

      // Receiver start:
      Serial.begin (9600);
      Wire.begin ();
      // Register 02h - enable, settings
      reg02h = RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
      setRegister (RDA5807M_REG_CONFIG, reg02h);

      // And then we decided to further strengthen the bass: (I don't need this, I need to somehow remove it)
      reg02h | = RDA5807M_FLG_BASS;
      setRegister (RDA5807M_REG_CONFIG, reg02h);

      // Register 03h - select radio station
      // After reset in register 03h, the default value is 0
      // Thus BAND = 00 (87..108MHz), STEP = 00 (100kHz). Let's leave them as they are
      reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT; // chan = (freq - band) / space
      setRegister (RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);
    // Register 05h. Set the volume, do not change the rest of the beats
      reg05h = getRegister (RDA5807M_REG_VOLUME); // Read the current value
      reg05h & = ~ RDA5807M_VOLUME_MASK; // Reset the VOLUME bits
      reg05h | = volume << RDA5807M_VOLUME_SHIFT; // Set a new volume
      setRegister (RDA5807M_REG_VOLUME, reg05h);
      // Receiver end:
    }

    void loop ()
    {
      // Print power readings every 8ms.
      static const uint16_t print_period = 8;
      static uint16_t last_print;
      uint16_t now = millis ();
      if (now - last_print> = print_period) {
        //Serial.println (get_power_reading ()); // Build a graph by which you can determine the optimal threshold
        // If the signal has exceeded the threshold, start timing:
        if (get_power_reading ()> threshold &&! timing)
        {
          startTime = millis ();
          timing = true;
        }
        // If the signal is below the threshold, stop the countdown and display the amount of time passed - the pulse duration:
        if (get_power_reading () <= threshold && timing)
        {
          elapsedTime = millis () - startTime;
          timing = false;
          //Serial.println(elapsedTime);
          if (elapsedTime> = 80 && elapsedTime <= 580)
          {
            int h = floor ((elapsedTime - 100) / 20); // Get the time in hours, but there are 6 pulses, but only the last one is needed.
            //Serial.println(h);
            // "valround" --- Round to the nearest integer,
            // "floor (x)" --- Round down to integer
            if (h> = 1 && h <= 24) // If the time is defined as abnormal, beyond reasonable limits, then simply forget it:
            {
              Serial.println ("Exact time:");
              Serial.print (h);
              Serial.println (": 00");
            }
          }
        }
        last_print + = print_period;
      }
    }

    // Receiver start:
    void setRegister (uint8_t reg, const uint16_t value) {
      Wire.beginTransmission (0x11);
      Wire.write (reg);
      Wire.write (highByte (value));
      Wire.write (lowByte (value));
      Wire.endTransmission (true);
    }

    uint16_t getRegister (uint8_t reg) {
      uint16_t result;
      Wire.beginTransmission (RDA5807M_RANDOM_ACCESS_ADDRESS);
      Wire.write (reg);
      Wire.endTransmission (false);
      Wire.requestFrom (0x11, 2, true);
      result = (uint16_t) Wire.read () << 8;
      result | = Wire.read ();
      return result;
    }
    // receiver end

  [1]: https://i.stack.imgur.com/sBjw3.jpg
  [2]: https://i.stack.imgur.com/Gknqq.png
  [3]: https://i.stack.imgur.com/7FQRh.png
  [4]: https://i.stack.imgur.com/c0G5k.jpg

body:
If the voice and music are superimposed on top of the signal you are
looking for, that will make matters quite difficult. The first thing you
have to do is filter out all the unwanted sound. The limit on how
aggressively you can filter is given by the width of the pulses. If you
want to detect 100 ms pulses, your filter width should probably be more
than 10 Hz. The filter you used in your test is way larger than that.

Given the limited processing power of your typical Arduino, it may be
preferable to do all the signal conditioning in the analog domain, prior
to digitizing it on the Arduino. If you really have to do everything in
the Arduino, you will still have to adjust the amplitude and the offset
of the signal in the analog domain so that it fits the range of the ADC.

For implementing a narrow-band filter on the Arduino itself, I generally
recommend to use an [homodyne detection][homodyne] scheme. This can give
you very narrow filters at a minimal processing cost. See this [other
answer][answer] where I discuss the working of the scheme, and provide a
link to an implementation.

If you have something similar to an Uno, you should be able to load that
sketch directly, although you may want to tweak the time constant in
order to make the filter narrower. You can then send it your test
signal, collect back the power readings sent by the sketch through the
serial port, and plot those. This should give you a new test signal for
prototyping the next stages of your processing pipeline. If all goes
well, you would just have to set a threshold for detecting the pulses,
and then have some condition on the length of the detected pulses to
sort out spurious pulses from legit ones.

[homodyne]: https://en.wikipedia.org/wiki/Homodyne_detection
[answer]: https://arduino.stackexchange.com/a/21175/7508

**Edit**: I suggested using a threshold on the detected power for
deciding when there is a pulse and when there is not. However, if the
power signal is noisy, this simple scheme may not be good enough.

One possible way to reduce the noise is to increase the time constant of
the filter by increasing `LOG_TAU`. Do not set it above 8,
otherwise it may overflow some variables. Also note that, the larger the
time constant, the lower the bandwidth, which can be an issue if the
frequencies are not very accurate.

Another option is to low-pass filter the power readings. This can be
done on a sub-sampled signal in order to lower the processing cost.

Finally, for deciding whether there is a pulse or not, it can be useful
to add some hysteresis to the detection, basically simulating a [Schmitt
trigger][]. This is simply accomplished by replacing the detection
threshold with two distinct thresholds: a high one for the “no pulse” →
“pulse” transition, and a lower one for the reverse transition:

```cpp
const uint16_t LOW_THRESHOLD  = ...;
const uint16_t HIGH_THRESHOLD = ...;

// within loop:
static enum { NO_PULSE, PULSE } state = NO_PULSE;
uint16_t power = get_power_reading();
if (state == NO_PULSE && power >= HIGH_THRESHOLD) {
    state = PULSE;
    register_pulse_start();
}
if (state == PULSE && power < LOW_THRESHOLD) {
    state = NO_PULSE;
    register_pulse_end();
}
```

[Schmitt trigger]: https://en.wikipedia.org/wiki/Schmitt_trigger


message:
"SparkFun SAMD21 Mini Breakout" 'Serial1' was not declared in this scope

I recently switched computers and installed Arduino IDE, Added SAMD21 to the boards manager and installed drivers.

My sketch previously ran on my laptop with no problems.  Now when I try to compile for the SAMD21 Mini, I get a 'Serial1' was not declared in this scope error.

If I try to compile it for Mega, there are no problems.

I have tried sample code with Serial1 for SAMD21 and it compiled and uploaded with no problems.

body: Ahhhh, I figured it out.  I had to add `#include "Arduino.h"` to the .cpp file.


message:
esp32-cam stuck in repeat boot

I am trying to bring the esp32 example code live. I am able to upload the image error free but when I remove the jumper and then press the reset switch, instead of seeing it logon to my network via serial monitor, I just get this repeating over and over and over again.

    rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    mode:DIO, clock div:1
    load:0x3fff0018,len:4
    load:0x3fff001c,len:1216
    ho 0 tail 12 room 4
    load:0x40078000,len:9720
    ho 0 tail 12 room 4
    load:0x40080400,len:6352
    entry 0x400806b8

    Brownout detector was triggered

    ets Jun  8 2016 00:22:57

    rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    mode:DIO, clock div:1
    load:0x3fff0018,len:4
    load:0x3fff001c,len:1216
    ho 0 tail 12 room 4
    load:0x40078000,len:9720
    ho 0 tail 12 room 4
    load:0x40080400,len:6352
    entry 0x400806b8

    Brownout detector was triggered

    ets Jun  8 2016 00:22:57

    rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    mode:DIO, clock div:1
    load:0x3fff0018,len:4
    load:0x3fff001c,len:1216
    ho 0 tail 12 room 4
    load:0x40078000,len:9720
    ho 0 tail 12 room 4
    load:0x40080400,len:6352
    entry 0x400806b8

    Brownout detector was triggered

    ets Jun  8 2016 00:22:57

    rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    mode:DIO, clock div:1
    load:0x3fff0018,len:4
    load:0x3fff001c,len:1216
    ho 0 tail 12 room 4
    load:0x40078000,len:9720
    ho 0 tail 12 room 4
    load:0x40080400,len:6352
    entry 0x400806b8
    ets Jun  8 2016 00:22:57

How do I boot an esp32-cam correctly?

code:

    #include "esp_camera.h"
    #include <WiFi.h>

    //
    // WARNING!!! Make sure that you have either selected ESP32 Wrover Module,
    //            or another board which has PSRAM enabled
    //

    // Select camera model
    //#define CAMERA_MODEL_WROVER_KIT
    //#define CAMERA_MODEL_ESP_EYE
    //#define CAMERA_MODEL_M5STACK_PSRAM
    //#define CAMERA_MODEL_M5STACK_WIDE
    #define CAMERA_MODEL_AI_THINKER

    #include "camera_pins.h"

    const char* ssid = "getAjobFool";
    const char* password = "andreasd1";

    void startCameraServer();

    void setup() {
      Serial.begin(115200);
      Serial.setDebugOutput(true);
      Serial.println();

      camera_config_t config;
      config.ledc_channel = LEDC_CHANNEL_0;
      config.ledc_timer = LEDC_TIMER_0;
      config.pin_d0 = Y2_GPIO_NUM;
      config.pin_d1 = Y3_GPIO_NUM;
      config.pin_d2 = Y4_GPIO_NUM;
      config.pin_d3 = Y5_GPIO_NUM;
      config.pin_d4 = Y6_GPIO_NUM;
      config.pin_d5 = Y7_GPIO_NUM;
      config.pin_d6 = Y8_GPIO_NUM;
      config.pin_d7 = Y9_GPIO_NUM;
      config.pin_xclk = XCLK_GPIO_NUM;
      config.pin_pclk = PCLK_GPIO_NUM;
      config.pin_vsync = VSYNC_GPIO_NUM;
      config.pin_href = HREF_GPIO_NUM;
      config.pin_sscb_sda = SIOD_GPIO_NUM;
      config.pin_sscb_scl = SIOC_GPIO_NUM;
      config.pin_pwdn = PWDN_GPIO_NUM;
      config.pin_reset = RESET_GPIO_NUM;
      config.xclk_freq_hz = 20000000;
      config.pixel_format = PIXFORMAT_JPEG;
      //init with high specs to pre-allocate larger buffers
      if(psramFound()){
        config.frame_size = FRAMESIZE_UXGA;
        config.jpeg_quality = 10;
        config.fb_count = 2;
      } else {
        config.frame_size = FRAMESIZE_SVGA;
        config.jpeg_quality = 12;
        config.fb_count = 1;
      }

    #if defined(CAMERA_MODEL_ESP_EYE)
      pinMode(13, INPUT_PULLUP);
      pinMode(14, INPUT_PULLUP);
    #endif

      // camera init
      esp_err_t err = esp_camera_init(&config);
      if (err != ESP_OK) {
        Serial.printf("Camera init failed with error 0x%x", err);
        return;
      }

      sensor_t * s = esp_camera_sensor_get();
      //initial sensors are flipped vertically and colors are a bit saturated
      if (s->id.PID == OV3660_PID) {
        s->set_vflip(s, 1);//flip it back
        s->set_brightness(s, 1);//up the blightness just a bit
        s->set_saturation(s, -2);//lower the saturation
      }
      //drop down frame size for higher initial frame rate
      s->set_framesize(s, FRAMESIZE_QVGA);

    #if defined(CAMERA_MODEL_M5STACK_WIDE)
      s->set_vflip(s, 1);
      s->set_hmirror(s, 1);
    #endif

      WiFi.begin(ssid, password);

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

      startCameraServer();

      Serial.print("Camera Ready! Use 'http://");
      Serial.print(WiFi.localIP());
      Serial.println("' to connect");
    }

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

body:
The message:

> Brownout detector was triggered

is being generated by your ESP32 because there is a problem with the Vcc power to the module.

Check the following:

1. Your USB cable.  Some cables are just plain cheap and can't supply the power the ESP32 needs.  Get a better one.

1. Some PCs are not able to supply enough power from their USB ports to supply the ESP32, try a powered USB hub and/or a different PC.

1. Some ESP32 modules are poorly made and may have bad solder joints or low quality components.  Your only real option here is to buy a better ESP32.

1. If you are powering other components from the ESP32's power supply, stop it.  Power any accessories separately.


message:
I'm working on a NodeMCU project and have a small doubt about LEDs and resistors

In my NodeMCU I want a statement to turn on an LED, which is easy, just use `pinnumber, HIGH`. But, what I'm trying to do here is connect multiple LEDs to one pin like this:[![Diagram showing multiple LEDs on a breadboard using a single current limiting resistor.][1]][1]

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

I just wanted to know if this will work and whether all the LEDs will turn on by one command write `(pinnumber, high)` or do I have to do something else to this circuit?
Please help I'm a noob to electronics.

And also, is the resistor correct(1k ohm) or is it 220ohm, because different places suggest different things.

body:
No! Most likely it will not work.

An LED lights up if the Voltage between the Anode (one side of the LED) and cathode (the other leg) exceeds a so called forward voltage (Vf).

This Vf depends on the creation process and differs between different colors. Vf can be between abt. 1.8 Volt (red LEDs) and abt. 4.2 Volt (blue LEDs). Even if the LEDs would have the same color, they might have different forward voltages. If you arrage 4 LEDs in parallel, like you did above, the Voltage over the 4 LEDS is as low as the Vf of the LED with the lowest Vf among the four. If the four LED would not have equal (Vf)s, only one LED will light up and all others stay dark or just glow a little bit.

The sum of the current that flows through the 4 LEDs must also flow through the resistor. So the resistor must let pass 4 times the current that is required for one LED. An normal 3mm or 5mm LED works best at about 10mA to 20mA. Let's say the LEDs have all the same Vf = abt. 2 Volts, and you choose to drive them with 15 mA.
You need 60 mA in sum for the 4 LEDs, that must pass the resistor. You can compute the required resistance with  Ohms law. `R = U / I`.

 - R is the resistance in Ohms.
 - U is the voltage over the resistor in Volts.
 - I is the current through the resistor in Ampere.

    U = Voltage of the ESP (3.3 Volt) minus
        the lowest forward voltage of the LEDs (2 Volt)
    I = the wanted current 60mA = 0.06 Ampere

    R = (3.3-2) / 0.06 = 140 / 6 = abt. 23 Ohm
    (27 Ohm resistors should be available.)

The resistor depends on the Voltage of the ESP, the kind of the LED and the amount of current you need to reliably light up the LEDs. You can not just take values from schematics or discussions the internet. Also 60 mA is very much current for the ESP pin. That might be a problem.

The best way the Light up 4 LEDs from one pin would be to use one resistor for each LED and a MOS FET Transistor that is connected to 5 Volts with its Drain pin, the parallel LED resistor pairs with its Source and to the ESP pin with its Gate. You should also be sure that the MOS FET you use is able to switch with a 3.3 V voltage from the ESP on its Gate.

If you did not understand what I have written, I advice you to learn the basics before experimenting further. The values above are all useless if the conditions change.


body:
Yes, technically your circuit works. But don't do like this.

TLDR;

This applies only to what you are doing
1. LED is current device. We control brightness by control current flow through it.
2. Each IO pin (of ESP8266) has current drive capable (source/sink) 12mA only, so calculate it wisely or you risk killing it.
3. Simplest way to control current of LED is using current limiter or just a resistor in series
4. Voltage drop across red LED (Vf) is 1.8v
5. 4 LEDs in parallel work just like 1 LED, assuming the same kind, but of course 4 times dimmer
6. Current goes through each LED = 1/4 of current goes through resistor (kirchhoff law of current)
7. Equation: 3v3 = 1.8v + V_R hence , V_R = 1.5v
8. Current goes through resistor I_R = V_R / R
9. 5mm LED has nominal current of 20mA to be considered brightest that last VERY long time.
10. BUT ESP8266 can only do 12mA. You go 20mA, ESP8266 goes bye bye.
11. So choose 10mA to be on safe side. Plug 10mA into #8, hence R = 1.5v / 10mA = 150 ohm
12. You can choose resistor value from 220R up to 1K, no problem. Higher resistance, less current.
13. You can do rough calculation, ignore voltage drop across LED, just use 3v3 / 10mA = 330R. Hence you will see people usually use resistor 330 ohm regardless 3v3 or 5v, red LED or green LED. Because at 5v it is 15mA, red or green makes only 0.3mA different. Nothing to worry.
14. But your circuit has 4 LEDs in parallel, hence current through each LED = 10mA/4 = 2.5mA
15. Fact: Even as low as 0.15mA (R=10k with 3v3 power supply), RED and GREEN LEDs are still bright enough for indication.

Note:
- My guess is, you are using LEDs like a torch. More LEDs = more brightness, right? Unfortunately, it won't work like that. You want to use transistor (BJT) or mosfet as a switch to turn on power supply for LED instead of driving LED from IO pin. Google high side switch or low side switch for that matter. Better solution is to use LED driver IC.
- Normally for simple indicator, I just whack a 470R resistor in series of a LED regardless voltage to drive it (5v or 3v3). It still gives quite intense brightness when you stare directly on it. Sometime you want to use 1k ohm just to reduce the brightness further or even sanding the LED from crystal clear into translucent white.