message:
Arduino slave with 2 masters sharing the same I2C Bus?

Consider a scenario where two (or more) `master` devices (the NodeMCU's, in this case) share an `I2C bus` with one (or more) `slave` device(s), like thus:

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

Would this be a feasible setup?  In other words,  could both `masters` request (not simultaneously) from the `slave`?

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

body:
The situation you describe is called MultiMaster. It is normally done in hardware using the I2C peripheral in the MCU. However the ESP8266 doesn't have one (or if it does, it's not used), and uses bit-banging to implement I2C in software. If you can add MultiMaster functionality to the ESP8266's Wire library then possibly yes, you could do it.

Another option is to have some other communication channel between the two masters (it could be as simple as a wire with a pullup resistor - see below) so that only one master communicates at a time.

Electrically there is no problem with your setup - I2C is a fully open-drain system (or should be implemented as such - hence the pullup resistors needed on the SCL and SDA pins), so multiple devices can drive the lines at the same time. It's just that if they do you will get data corruption and communication won't happen.

----

Example: Semaphore Wire Implementation

1. Connect any two GPIO pins together with a wire. Add a pullup resistor to the wire (10kΩ should suffice).
2. Both GPIO pins are set to INPUT.

When a master wants to send it first reads the GPIO pin:

* If it is HIGH then it is "clear to send". So it sets the GPIO to OUTPUT and pulls the line LOW.
* If it is LOW then it waits for a random amount of time and tries again.

Once communication is finished the master sets the GPIO pin to INPUT again.


sender: user

sender: assistant

body:
Changed diagram after comments and accepted answer:

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

  [1]: https://i.stack.imgur.com/nvCyT.png
  [2]: https://i.stack.imgur.com/qklDJ.png


message:
Reset NodeMCU master from Arduino slave

I designed a PWS (personal weather station) which will be placed in a difficult to access location.  In case of the master crashing and not requesting from the slave for a certain amount of time (stay alive protocol), is it possible to reset the master from the slave by powering a digital pin?

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

Note, I improvised a pull down circuit so that the Arduino Nano's D7 (or any other digital pin) 5V output could be pulled down to 3.3V.

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

body:
There is no need for a voltage divider or a level conversion on the reset pin of the esp8266. The esp8266 has internal pull-up on reset pin. To reset the esp8266 the reset pin must be connected to ground for a very short moment.

To pull the reset pin LOW with pin of the other MCU we do:

    void resetEsp() {
      pinMode(ESP_RESET_PIN, OUTPUT);
      delay(1);
      pinMode(ESP_RESET_PIN, INPUT);
    }

ESP_RESET_PIN is the pin wired to reset pin of the esp8266. It is not configured in `setup()` and it is never set `HIGH` (we don't want to send 5 V to esp8266). Setting the ESP_RESET_PIN to `OUTPUT` connects it to ground, setting it back to `INPUT` hands the control of the line back to esp8266 reset pin's internal pull-up.


body:
As per verification from Juraj, this would be correct wiring for his answer:

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

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


message:
one Arduino with RS485 and Ethernet shields: does this work?

I'm planning to wire a few Arduinos together via RS485, and have one of them act as a hub that collects information from the others and presents it via http on an Ethernet connection.

For instance an Aduino MKR with [ETH shield][1] and [485 shield][2]. Can I expect these to work together? My worry is having 2 shields that potentially need lots of bandwidth, timing issues etc.

  [1]: https://store.arduino.cc/mkr-eth-shield
  [2]: https://store.arduino.cc/arduino-mkr-485-shield

body:
Should be no problem.

The ETH shield uses SPI to communicate with a W5500 chip. That chip does most of the network processing for you.

The 485 shield just connects to the UART TX and RX pins. It's just serial communications with a couple of control pins from there on out.

Neither use any pins that the other one uses.


message:
Arduino IDE display DEBUG PORT Serial1 output

How can I display / capture Arduino IDE's `Serial1` output?
Can I display it using `Arduino IDE` or using a script in `Python`?

This python script ([courtesy of Chad G][1]) works for the Serial:

 #!/usr/bin/env python3

 import serial
 import sys

 if len(sys.argv)<2:
     print("Please give serial port number")
     exit()
 port=sys.argv[1]
 ser= serial.Serial('/dev/ttyUSB'+port,9600,timeout=5)

 while True:
     try:
  stringMe = str(ser.readline().strip())
  if len(stringMe)>3:
      print(stringMe)

     except:
  print(sys.exc_info())
  ser.close()
  exit()

called as (for USB0):

    python3 Arduino/tools/multiMonitor/monitorUsb1.py 0

or, if I want to save to a log file:

    python3 Arduino/tools/multiMonitor/monitorUsb1.py 0 >> Arduino/tools/multiMonitor/log/usb00.txt

  [1]: https://arduino.stackexchange.com/a/67229/30341

body:
`Serial1` (on most Arduino boards that have `Serial1`) is connected to a pair of pins on the GPIO headers and nowhere else.

To get it to your computer you will have to feed those TX and RX pins through a USB to TTL UART (FT232, CP2102, etc) adaptor.

From there on in it's exactly the same as using `Serial` but of course with a different device name.


message:
A proper way to get the roll, pitch and yaw values

TL, DR : What is the method (in terms of sensors and algorithm) to get the roll, pitch angles of an aircraft at any instant?

I am planning to build a hobby aircraft. I am so confused about which kind of sensors should I use and how to use them in order to get the roll, pitch and yaw angles of the aircraft.

I think I also have some problems understanding the concept. I consider these P, R, Y angles similar to the x,y,z coordinates as if they are able to describe the **attitude** of a body. If something in the below list contains "nonsense" arguments, please also enlighten me about them.

What I want is to be able to know at any instant:

1. What is the pitch angle of the aircraft, i.e how much degrees its nose pointing away from the horizontal plane of the earth.
2. What is the yaw angle, i.e to what direction(north, east etc) is the aircraft pointing through.
3. What is the roll angle, i.e what is the angle between aircrafts body surface ( wing to wing **x** tail to head surface ) and the horizontal plane of the earth/sky.

In some sources there is something going on as the importance of order of the application of roll, pitch and yaw. But I cannot understand why this is related.

I have used accelerometer values by inputting them into some formulas on the internet (those arctangent formulas, which everybody uses but nobody explains well) to get the roll and pitch values. However could not understand how to manipulate them in order to meet my requirements (different axis orientations of the sensor).

I also have basic understanding about what a gyroscope is.

I have an MPU6050(Accelerometer+Gyroscope).

P.S : my goal is to build a quadcopter but I guess in order to understand these concepts a fixed wing standard plane model.

body:
> In some sources there is something going on as the importance of order of the application of roll,pitch and yaw. But I cannot understand why this is related.

Take your right hand: point your thumb upwards, your index finger away from you, and your middle finger to the left. You now have a righthanded coordinate system: your thumb is the x axis, your index finger the y axis, and your middle finger the z axis.

First rotate +90° around the x axis (thumb). Your index finger now points to the left, and your middle finger towards you. Next, rotate +90° around the y axis (index finger). Your thumb now points away from you, your index finger to the left, and your middle finger upwards.

Now, move back to the initial position, and apply the same two rotations in a different order, first around the y axis and then the x axis:
Rotate +90° around the y axis (index finger). Your thumb is now pointing to the right, your index finger away from you, and your middle finger upwards. Next, rotate +90° around the x axis (thumb). Your thumb now points to the right, your index finger upwards, and your middle finger towards you.

This is different from the last result: order of rotation matters.

> I have used accelerometer values by inputting them into some formulas on the internet(those arctangent formulas, which everybody uses but nobody explains well)

When the aircraft is moving at a constant velocity, the accelerometer just measures the acceleration due to gravity, which is a vector pointing exactly downward, (0, 0, -g) in the global coordinate system. This is always true, regardless of the orientation of the sensor.
If the sensor is perfectly level, the sensor's local coordinate system is aligned with the global coordinate system, so the sensor also measures (0, 0, -g).

When the sensor is tilted, the measured vector also has an x and y components.
To keep things simple, imagine the case where the sensor is tilted around the positive y axis.
The sensor now measures an x component as well as a z component: (x, 0, -z).

As you can see from the following image, the angle of rotation `θ = atan2(x, z)`.

![gravity acceleration vector](https://i.stack.imgur.com/lGzHt.png)
The black arrow is the acceleration due to gravity, and the red and blue arrows are the x and z axes of the coordinate system of the (tilted) sensor.

***

However, accelerometer measurements are not useful for determining the orientation when the sensor is accelerating, because then the measured vector no longer points exactly downward (in the global coordinate system).

Gyroscopes measure angular velocity. By integrating the angular velocity, you get the angle.
There's one caveat: it is impossible to integrate exactly, because we only have measurements at discrete points in time. This means we have to use something like Euler's method, which is known to result in drift of the orientation estimate. To make matters worse, the measurement is noisy, and this noise is integrated as well, resulting in an even larger error.

Luckily, you can combine both imperfect measurements into a single, better orientation estimate using a sensor fusion algorithm. I've successfully used [Sebastian Madgwick's algorithm](https://x-io.co.uk/open-source-imu-and-ahrs-algorithms/) for my quadcopter.
It uses the measurements of the accelerometer to minimize gyro drift.

Note that this algorithm uses quaternions instead of Euler angles (roll, pitch, yaw), because the latter suffer from gimbal lock, and because quaternions geneally require less processing power.

Also note that you cannot determine the yaw angle using the accelerometer, so you'll get some drift on that measurement.

It's a good idea to do all of your calculations using quaternions. You probably won't need Euler angles for your quadcopter, except maybe for debugging purposes.

If you want to, you can also get the quaternion from the acceleration vector directly:

```cpp
    Quaternion quaternionFromDirection(Vec3f v) {
        /*
         * Formula:
      * q = cos(ϑ / 2) + sin(ϑ / 2)·(x·i + y·j + z·k)
      * where (x y z) is a unit vector representing the axis about which
      * the body is rotated; ϑ is the angle by which it is rotated.
      *
         * Source:
         * https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Using_quaternion_as_rotations
         *
      * The rotational axis (x y z) can be calcuated by taking the normalized
         * cross product of (0 0 1) and the given vector. The angle of rotation
         * ϑ can be found using |A×B| = |A||B|·sin(ϑ).
      */

        // First check the edge case where v == (0 0 z), i.e. vertical
        if (v.x == 0 && v.y == 0)
            return {1, 0, 0, 0};

        // Calculate the cross product and its norm.
        Vec3f cross     = {v.y, -v.x, 0};
        float crossNorm = cross.norm();
        cross /= crossNorm;

        // Calculate the angle ϑ.
        float angle = std::asin(crossNorm / v.norm());

        // Calculate the resulting quaternion.
        return {
            std::cos(angle / 2),            //
            std::sin(angle / 2) * cross.x,  //
            std::sin(angle / 2) * cross.y,  //
            std::sin(angle / 2) * cross.z,  //
        };
    }
```


message:
Connect 5v 30a relay with Arduino Uno

I have previously connected [5V 10A relay switches][1] to my Arduino.

But for my new project I need to use a [5V 30A relay switch][2] with my Arduino.

In 10A relay switches, we make connection with Arduino using GND, VCC and IN.

But for 30A switches, there are DC+, DC-, IN.

My question is that, how do I connect my Arduino to the relay using these pins?

  [1]: https://www.amazon.in/dp/B01HXJDBII/ref=pd_lpo_sbs_dp_ss_1?pf_rd_p=cd818f9c-142a-4b42-ad2c-f0421857aaf5&pf_rd_s=lpo-top-stripe&pf_rd_t=201&pf_rd_i=B00C59NOHK&pf_rd_m=A1VBAL9TL5WCBF&pf_rd_r=MJP2SHRW2PN89Y5J5V18&pf_rd_r=MJP2SHRW2PN89Y5J5V18&pf_rd_p=cd818f9c-142a-4b42-ad2c-f0421857aaf5
  [2]: https://www.amazon.in/xcluma-1-Channel-Module-Optocoupler-Trigger/dp/B072THSX9Q/ref=sr_1_1?keywords=5v 30a&qid=1564212590&s=industrial&sr=1-1

body:
From the Amazon page you linked to:

> 1 dc+ : Dc power supply positive pole
> 2 dc- :Dc power supply negative pole (i.e. ground)

Arduino:
VCC: positive DC power supply
GND: ground

[technically][1], VCC = the voltage at the collector of a transistor, these days it's used as shorthand for the positive output pin of an IC.

  [1]: https://en.wikipedia.org/wiki/IC_power-supply_pin


message:
Arduino DUE and 5V logic sensor?

For an application I use Arduino DUE and VNH2SP30 as the motor driver.I think this motor drive is only compatible with 5V logic but DUE provide 3.3V logic.Will my problem be solved if I use logic level shifter to convert 3.3V logic level to 5V?In the meantime, I control the speed and direction of the motor with the following code:

    analogWrite(PWM_kare,head_analog);
    digitalWrite(INB_kare, HIGH);
    digitalWrite(INA_kare, LOW);

body:
According to [the datasheet](https://www.elecrow.com/download/VNH2SP30 Datasheet.pdf) (page 5) the "Input High Level Voltage" is 3.25V.  That means that any voltage over 3.25V will count as a HIGH.

That is kind of borderline for 3.3V logic which can drop below 3.3V for a HIGH depending on load and other circumstances.

So while it *might* work off 3.3V I would say for reliable operation you should use some form of level shifting in your circuit, yes.

A simple, cheap, MOSFET-based logic level shifter will do the job - there is no need for anything fancy.


message:
How can I give power to Arduino Uno using a 12V 7.5 Ah Lead-Acid battery?

I am trying to give power to my Arduino Board using a 12V 7.3 Ah Lead-Acid Battery but I am unable to do it.

I connected the battery to Arduino Uno (via DC Pin) and it worked for a couple of minutes but then, it automatically stopped working. I checked the voltage of the battery using a Multimeter from the same DC Pin which was connected with battery and board. The voltage was 12.62 volts.
Then I thought my board might have been fried. So, I checked the board by connecting it with a 12V 2 Amp DC adapter and I found that my board was not fried and it was working fine with the Adaptor. The Adaptor was giving 12.48 volts voltage. Then, I again checked the board using battery but still it didn't work. I tried charging the battery via a charger but it still didn't work. I tried these steps multiple times but the results were always same.

I checked with my 12V DC Fan & some other devices also and it works perfectly, but it doesn't work with my Arduino Board.
This indicates that my battery is in a good condition but not working with Arduino Board only. While Arduino is also in a good condition, working with 12V DC Adaptors but not with the Battery.

Please Help!

body:
The input voltage on the DC pin [is specified as](https://store.arduino.cc/usa/arduino-uno-rev3) 7 to 12V. Your battery may well be supplying more than that, causing the voltage regulator to overheat and shut down.

> The voltage was 12.62 volts.

That is out of spec for the Arduino Uno. When you operate out of specified voltages anything can happen, and that anything may not be very good.

You could get a [buck converter](https://en.wikipedia.org/wiki/Buck_converter) to lower the voltage.

Certainly a Uno should be able to run for a long time on a 7 Ah battery (provided you are supplying voltages in range for it, preferably using a buck converter or similar to make sure that a fully-charged battery does not supply too high a voltage).


message:
Why does my code treat my sound sensor as if it's always HIGH

I have a sound sensor that was working perfectly fine as I was using it as a clap sensor to turn lights on and off. However, I tried to change the code to make it work a little smoother and for whatever reason it stopped working. I then tried to write a very simple script to allow it to turn on and off using just one clap but now it treats the sound sensor as if it's always inputting HIGH. Any ideas why this might be happening?

note: I've turned up the sensitivity and can see that the sound sensor isn't always HIGH. Even when it's too high to hear me clap it still turns the LED on and off as if the if statement below was always true.

    int SENSOR = 2;
    int LED = 13;

    void setup() {
      // put your setup code here, to run once:
      pinMode(LED, OUTPUT);
      pinMode(SENSOR, INPUT);
    }

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

      if(digitalRead(SENSOR) == HIGH){
        digitalWrite(LED, (digitalRead(LED) == HIGH ? LOW : HIGH));
        delay(100);
      }
    }

This is the sound sensor module I am using: [Robojax Sound Detection Microphone Module][1]

  [1]: https://www.amazon.ca/Robojax-Detection-Microphone-Module-Arduino/dp/B07PPYK3ND/

body:
The robojax microphone switch I was using outputs LOW when it senses a sound rather than outputting HIGH as I assumed. The solution was just to replace all the if statements testing for a HIGH input with LOW.

note: sorry about not looking into the microphone earlier.


message:
Timing 12 relays

I need a simple code to turn on 12 outputs one after another 2 seconds apart. A pushbutton will initiate this and the outputs will stay on for 3 minutes at which time all outputs will turn off awaiting the pushbutton input

So far:

    Void setup
    pinMode (10,output);
    PinMode (11,output);
    PinMode (12,output);

    Void loop
    delay(100);
    digitalWrite (10,HIGH);
    delay (2000);
    digitalWrite(11,HIGH);
    delay(2000)
    digitalWrite(12,HIGH);

    delay(180000);
    digitalWrite (11,LOW);
    digitalWrite (12,LOW);
    digitalWrite (10,LOW);
    exit(0);

Push remote reset button to restart.

Only tried 3 outputs for now and haven’t tried “Crossroads” code yet but I will.

body:
Simple code:

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

    byte buttonPin = 2;
    byte relayPins [] = {3,4,5,6,7,8,9,10,11,12,13,14,};
    byte x;

    void setup() {
      pinMode(buttonPin, INPUT_PULLUP);
      for (x=0; x<12; x=x+1) {
        pinMode(relayPins[x], OUTPUT);
      }
    }

    void loop() {
      if (digitalRead(buttonPin) == LOW) {
        for (x=0; x<12; x=x+1) {
          digitalWrite(relayPins[x], HIGH); // drive base of NPN or N-MOSFET to sink current
          delay(2000);
        }
        delay(180000); // dumb 3 minute delay
        for (x=0; x<12; x=x+1) {
          digitalWrite(relayPins[x], LOW);
        }
      }
    }

And of course, supporting hardware to drive relay coils.


body:
Don't use Delay. CrossRoads provided a decent starting point for your code, but his code is based on `delay()`, which is a dead end.

Instead of delay, use a bool `running` to track whether you're relay sequence is running or not. Also have an `unsigned long` `startTime`, and an array of bools to track if each relay is on or off.

If !running, check the button. If the button is pressed, set running to true, and set startTime to `millis()`.

Then, use millis() to figure out where you are in the sequence. Calculate `(millis()-startTime)/1000/num_relays`. Let's call it `relayIndex`.

When `relayIndex` is less than `num_relays - 1`, check the bool for that relay, and if it's off, set it on and turn on that relay. When `relayIndex` reaches `num_relays-1`, you're done turning on relays. Now it's time to wait for 3 minutes to go by. After 3 minutes, turn off all the relays and relay bools, and set `running=false`. Have the reset button do the same thing.

## EDIT ##

Also note that controlling relays from an Arduino (or from other solid state devices for that matter) requires special hardware and precautions. You should probably use a "digital" relay (something like [this][1], or better yet [**this**][2] 6 channel relay) that isolates the Arduino control line from the high current needed to drive the relay.

Failing that, you should build a control circuit from a MOSFET transistor and a "flyback diode". Without flyback diodes, the inductive coils on your relays emit "[**back EMF**][3]" which will likely fry your transistors (and possibly the Arduino)

  [1]: https://www.amazon.com/Tolako-Arduino-Indicator-Channel-Official/dp/B00VRUAHLE/ref=asc_df_B00VRUAHLE/?tag=hyprod-20&linkCode=df0&hvadid=309803885710&hvpos=1o2&hvnetw=g&hvrand=11611615258717876708&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9008140&hvtargid=pla-568715033020&psc=1
  [2]: https://www.amazon.com/NOYITO-6-Channel-Trigger-Optocoupler-Isolation/dp/B07HWHJTBC/ref=asc_df_B07HWHJTBC/?tag=hyprod-20&linkCode=df0&hvadid=242027088707&hvpos=1o2&hvnetw=g&hvrand=6696300912666984277&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9008140&hvtargid=pla-583600390012&psc=1
  [3]: https://en.wikipedia.org/wiki/Counter-electromotive_force


message:
DC motor does not work using PWN or Digital pins

1. I have connected `pin 3` to a DC motor and using `analogWrite` and `DigitalWrite` to try making it start. However, nothing happens.

2. If I try to move the pin from `pin 3` to `5V` or `3.3V` the motor starts.

**Q:** What could be the problem since it does not start using pin 3 (or others). I am using `HIGH` on `digitalWrite` and `255` on `analogWrite`.

* I just bought a starter kit. [It has FREENOVE written on it][1].

* Here is a link to the [tutorial and software][2].

Thanks for any help!

  [1]: https://www.ebay.com/itm/Freenove-Ultimate-Starter-Kit-with-UNO-R3-Arduino-Compatible-Breadboard/302057861688?hash=item46540d3238
  [2]: https://git.io/fj8Jq

body:
The Tutorial.pdf document that describes the components in the kit does not tell you what the current draw of the motor is. Chapter 10 has 2 tutorials on how to use the motor with a relay or L293D IC. This suggests to me that the motor draws a lot more current than a digital output can provide.

The tutorial using the L293D gives you the ability to vary the speed of the motor using PWM, so it would be a good place to start.

Hopefully pin 3 was not damaged by the excess current flow when the motor was attempted to be powered from it.


body: The digital/analog pins cannot directly source enough current to run a motor. Use the pin to control a switching device like a mosfet which then controls current flow to the motor.


body:
You should read up on controlling motors from digital circuits and follow a tutorial until you understand the "gotchas".

You have to be careful with the pins on an Arduino and not trying to draw too much current from them. A motor very likely needs several times more current than an Arduino digital pin can provide (you should keep the current draw on an Arduino pin ≤20 mA. Your motor might well draw 10 times that much. You might have damaged or destroyed the pin you used.

Secondly, motors use inductive coils (electromagnets). Inductors have an effect called "back EMF" that causes a reverse surge of current when you remove power from them. That will also fry whatever solid state component is driving the inductor. (The Arduino pin if you're trying to drive the inductor directly, or a transistor if you're switching the current to the inductor using a transistor.) You need a "flyback diode" on the inductor to protect the circuit that drives it.


message:
arduino boolean function

In the following code :-
The aim of code is " when push button is pressed , led is on and when push button is is pressed again led is of"

    #define led 12
    #define button 7
    boolean trigger = false;
    boolean previous = false;
    void setup()
    {
      pinMode(led , OUTPUT);
      pinMode(button , INPUT);
    }
    void loop()
    {
      int current = digitalRead(button) ;
      if (current && !previous)
      {
        trigger = !trigger;
      }
      previous = current;
      digitalWrite(led , trigger);
    }

My Questions are as follows:-

 1. When i used digitalread(button) instead of introducing variable i.e
    current. LED shows abnormal behavior. Why ?
 2. What is the purpose of current = previous expression. Whats its
    significance?
 3. Also please explain the working of a code in a brief manner in a
    loop.
 4. Why I should use Boolean instead of int?

body:
> When i used digitalread(button) instead of introducing variable i.e
> current. LED shows abnormal behavior. Why ?

Likely this is because of [switch bounce][1].  The processor is very fast compared to the bounces a mechanical switch makes when operated.  So the results can be unexpected.  You can get around this problem in [software by using a state machine][2].  Or in [hardware by using capacitors to filter out bouncing.][3]

> What is the purpose of current = previous expression. Whats its
> significance?

The program is tracking the state of the switch.  So you need to know the previous state of the switch to know if the state of the switch has changed.

> Also please explain the working of a code in a brief manner in a loop.

The two fixed or reserved function names in an Arduino sketch are "setup" and "loop".  "setup" is called only once on boot up.  And "loop" is called over and over again after "setup"is called.  In "loop" the code reads that state of the button, then tests to see if the state of the button is true and the previous state is false.  If it is, then toggle the variable which tracks the state of the LED.  Then the code will always save the current state as the past state and turns on / off the LED according to the value tracking the state of the LED.

Now comes the tricky part.  Assume the switch is perfect and does not bounce.  The toggling only occurs when the switch is 1st pressed.  That is because the next time through "loop" both trigger & previous are true and the test will then be false and the LED will not be toggled.  Not until after the switch is released does the code reset previous to false.  Now if the switch is pressed again, for only 1 iteration through "loop", the test will be true and the LED will be toggled.

This approach depends on the switch not to bounce.  And is difficult to understand.  Consider using a 4 state machine (button up / LED off, button down / LED on, button up / LED on, button down/ LED off) rather than this 2 state machine (button down / LED toggle, button up / LED steady).

> Why I should use Boolean instead of int?

Bools only have two states.  Integers can have many states.  It is less confusing and less error prone to use a variable that only has two states if that is the intent of the program.

  [1]: https://en.wikipedia.org/wiki/Switch#Contact_bounce
  [2]: https://www.arduino.cc/en/tutorial/debounce
  [3]: https://hackaday.com/2015/12/09/embed-with-elliot-debounce-your-noisy-buttons-part-i/


message:
Sampling stereo audio at greater than 40 Hertz using arduino

I am working on a project to make a speaker with reactive lighting. I need to be able to sample stereo audio at a decent rate for songs. The `audioRead ()` function can do about `8 kHz` and I have heard you can push it up till `35 kHz` but than you can only use it for mono and you cannot use the arduino for anything else.

* Someone recommended that I use an ADC. What can it do for me?

* Is the arduino's operating speed a limitation?

* If not the arduino which other micro-controller is suitable for this purpose.

body: The first part of the speed limitation on the Arduino is that the ADC is painfully slow.  If you had a faster ADC chip then you could take analog readings faster so you can take more per second.  Once you're over that threshold then the next limitation you run into is the speed with which Arduino can communicate with that ADC.  So make sure you get something fast (like SPI).


body:
If you are only interested in getting a reading of the sound intensity,
then 8 kHz may be enough. You can also convert the signal to mono
using a pair of resistors. If you want the Arduino to do other stuff
while taking the analog readings, then you should forego `analogRead()`
and access the ADC directly. This is more involved that typical Arduino
programming, as it involves configuring the ADC at low-level, in “free
running mode”. In this mode the ADC operates in an autonomous way, and
send you an interrupt every time a sample is ready.

I have written a program that does something similar: it samples an
analog input at 9.6 kHz (104 µs per sample) an periodically
sends the reading through the serial port: [sound-meter.ino][]. You can
probably adapt it for driving LEDs instead of the serial port.

[sound-meter.ino]: https://gist.github.com/edgar-bonet/e693799f58a545ca89a2


message:
L298N beeps and malfunctions when receiving certain analogWrite values

1. I created a simple circuit with an `UNO`, `L298N` and `a single motor`.

2. Wrote the following code to test controlling the speed of the motor.

3. Tested motor with `digitalWrite()` function and it works fine.

4. Tested motor with `analogWrite()` function and from `255` down to around `70` motor works at various speeds.

**Q:** But from around 70 and below, the L298N starts to beep and the motor stop spinning. Any thoughts?

    int enr = 9;
    int inr1 = 8;
    int inr2 = 7;

    void setup() {
     pinMode(enr, OUTPUT);
     pinMode(inr1, OUTPUT);
     pinMode(inr2, OUTPUT);
    }

    void loop() {
      analogWrite(enr, 71);
      digitalWrite(inr1, HIGH);
      digitalWrite(inr2, LOW);
    }

body:
Ok, here is my theory what's happening:

Every motor has an amount of friction at his rotor. You need to pass enough energy to overcome this friction, or the motor will not move. When you use `analogWrite(enr, 71)` or lower, you pass only a small amount of energy to the motor, so that it cannot overcome the friction.

Now you have to understand, what `analogWrite()` really does. It does **not** output an analog voltage. Instead it generates a PWM signal. The voltage changes between HIGH and LOW level (5V and 0V in case of the Uno) at a specific frequency. The relation between HIGH time and LOW time is called duty cycle. That is, what's controlling the motor speed. So instead of supplying different voltages, we turn the motor on and off very fast. Since the rotor has a relatively big inertia (because of it's mass), it cannot react fast enough to follow these pulses. We only give it small pushes very fast. Instead it integrates over all the pulses. If the duty cycle is low (more LOW than HIGH time) only a small amount of energy is passed to the motor.

So, what is the motor doing, when it's got not enough energy to overcome the friction? It will still get little pushes very fast, but cannot actually spin. Instead the passed energy will induce vibrations in the motor, which have the frequency of the PWM signal. These vibrations can then be heard as a continuous beep.

If enough energy is passed to overcome the friction, the rotor spins correctly and does not vibrate, thus you cannot hear a beep.

**What to do now:**

The described principle applies to every motor, so cannot do much about that. You can simply go the easy way and not drive the motor with such low duty cycles. Another cause might be, that your motor likes to get a higher current to give it's full power. The L298N is quite inefficient, so you could change that to a H-bridge driver, that uses MOSFETs instead of bipolar transistors. Also maybe you can increase the voltage, that you use to drive the motor (depending on the not specified motor).

You didn't describe, how you have connected everything, so 2 other points: You cannot drive a motor from a digital pins power (since a digital output pin can only provide 40mA at max, 20mA recommended) and you should also not power a motor through the Arduino, since you might fry the voltage regulator or the protection diode. You can get away with that, when using small motors without any load, but that doesn't scale well. You should always connect the motor circuit directly with the power supply, so that the motors current does not have to flow through the Arduino.


message:
Is My Motor Shield Broken?

So I am trying to work on a mini battle bot project. However, it has been a while since I have worked with my Arduino electronics. So I am going through and learning how to do each thing before putting it all together. So far I have learned how to use the IR remote and got that working. I got my brushless motor with esc working with the Arduino. Now I am trying to get my dc motors working for the wheel component. I am just trying to get one motor running from the motor shield as proof of concept essentially. So here is the run down.

I have 8xAA batteries in  series with each AA running at 1.5 volts for a total of 12 volts. I have verified this with my multimeter. The dc motors need 9-18 volts to run, so 12 should have it running. However, I will probably step that up to 18 volts for maximum power and run 4 dc motors since I am guessing my project will be a little heavy, so I need as much power as possible. I have the 8xAA batteries connected correctly with positive to the positive and negative to negative on the motor shield. I have checked my soldering connection and the pins are not bent and it looks straight and good. I made sure I firmly pressed down to get it onto the Arduino. Motor is connected to m2 as per the code. I don't understand why this isn't working as it should work. I have tried using this form: https://arduino.stackexchange.com/questions/20000/why-is-my-adafruit-motor-shield-not-spinning-my-motors

And that did not solve it. I originally was using a 9 volt battery but that form told me to use more than 9 volts and to use AA batteries, so I did that. I also checked my connections and made sure soldering is good. Here is my code:

    #include <AFMotor.h>

    // DC motor on M2
    AF_DCMotor motor(2);

    void setup() {
      Serial.begin(9600);           // set up Serial library at 9600 bps
      Serial.println("Motor party!");

      // turn on motor #2
      motor.setSpeed(200);
      motor.run(RELEASE);
    }

    int i;

    // Test the DC motor
    void loop() {
      motor.run(FORWARD);
    }

I have connected my motor to the battery directly and motor runs just fine. I have checked the voltage of my battery and it is great, not below the 12 volts and not above 13 volts. I have opened up serial monitor and I do see 'motor party' so I know the code is running. I looked for errors down below and saw none. The port I have checked and it is correct. Motor shield is made by Adafruit. I do have the correct library installed, in fact I just installed it today so I have up to date library. The lights on the Arduino light up and the light indicating power on the motor shield also light up when my AA batteries are plugged in. When I plug it in, lights light up but motor doesn't run. Here are a few pictures.

https://i.stack.imgur.com/cSo3x.jpg

I am have a hard time figuring this out, so if anyone can help me, thanks in advance.

body: As noted by markshancock, you are using an older version of the Adrafruit Motor Shield library meant for the version 1 of the board (you have the version 2.3), and according to their forum they are not compatible (they use different communication protocols) use the newer version of the library https://forums.adafruit.com/viewtopic.php?f=31&p=276888


body:
The commands you are using don't match the ones listed for this board.  Here is the [AF Documentation][1] for the Motor Shield Board V2.

Try

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_MS_PWMServoDriver.h"

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    Adafruit_DCMotor *motor = AFMS.getMotor(2);

    void setup() {
      Serial.begin(9600);           // set up Serial library at 9600 bps
      Serial.println("Motor party!");

      // turn on motor #2
      AFMS.begin();
    }

    int i;

    // Test the DC motor
    void loop() {
      motor->run(FORWARD);
    }

Note: In this library, getMotor() returns creates a pointer; so, you have to use "->" rather and "." to access the motor run() method.

  [1]: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/using-dc-motors


message:
global volatile variable not being updated in ISR

Running on atmega168p, I've got an interesting behavior I can't explain. A global volatile var that's called `pos` over here is not updated as it should. Once I add some code below the assignment, it starts working.

```c
#define ENCODER_DO_NOT_USE_INTERRUPTS
#include <Encoder.h>

Encoder myEnc(A2, A3);

void setup() {
  Serial.begin(115200);
  while (!Serial); Serial.println("Started.");
  PCMSK1 |= bit(PCINT10) | bit(PCINT11) | bit(PCINT12);
  PCIFR  |= bit (PCIF1);   // clear any outstanding interrupts
  PCICR |= bit(PCIE1);
}

volatile int pos  = 0;
int oldpos = 0;

void loop() {
  if (oldpos != pos) {
    oldpos = pos;
    Serial.println(pos);
  }
  delay(100);
}

// PCINT10, PCINT11
ISR(PCINT1_vect) {
  pos = myEnc.read();
  //  adding digitalRead(A0)
  // or even Serial.println(pos) updates the var correctly
}
```

Switching from `int` to `byte` doesn't change anything. Encoder library is https://github.com/PaulStoffregen/Encoder. Any clues?

body:
You are using pos outside of the interrupt without turning the interrupt off.  pos is two bytes, so it takes the Arduino more than one cycle to read in that variable no matter how it is handled.  If an interrupt occurs during that time, you get a corrupted value.

You need to have a cli() and then make a copy of pos to another variable and then a sei() and then use that copy in your calculations in loop.


body:
Well, the long awaited answer to this question is simple - the library that I've tried to use in my code was over-optimizing things by going full ASM and interfering with my stuff. Using C version straightened things up.

For anyone getting strange behaviour I recommend taking a quick glance at the lib's code you're using, maybe it's not your fault after all.


body:
<!-- language-all: lang-arduino -->

# How to recognize and fix race conditions in Arduino by using atomic access guards:

> Switching from int to byte doesn't change anything. Encoder library is https://github.com/PaulStoffregen/Encoder. Any clues?

Your code here:

    void loop() {
      if (oldpos != pos) {
        oldpos = pos;
        Serial.println(pos);
      }
      delay(100);
    }

has an unaddressed race condition, which leads to undefined behavior and data corruption. Making `oldpos` into a `uint8_t` or `int8_t`, each of which is 1 byte, instead of `int`, which is 2 bytes, won't fix it, because you need the whole section from `if (oldpos != pos) {` through `Serial.println(pos);` to be atomic so that the value of `pos` you use to enter the `if` block does not get changed by the interrupt while you are in the `if` block. I'll explain more later. This is reminds me of a problem I had a few years back, here: [C++ decrementing an element of a single-byte (volatile) array is not atomic! WHY? (Also: how do I force atomicity in Atmel AVR mcus/Arduino)](https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why).

So, let's walk through a case where making a 2-byte variable into a 1-byte variable WILL solve the problem, first, to ensure we understand why one might think making it a 1-byte variable is the solution.

Let's look at this example. **It has a race condition and undefined behavior. Can you spot it?**

    volatile uint16_t isr_counter = 0;

    void setup()
    {
        // enable the ISR here
    }

    // Any ISR
    ISR()
    {
        my_var++;
    }

    void loop()
    {
        Serial.println(isr_counter); // <== race condition!
    }

The answer is that `isr_counter` is a 2-byte variable, and AVR microcontrollers have 8-bit (1-byte) CPUs, so, it is possible that as `isr_counter` is being read in `loop()` to be printed, 1 of the 2 bytes is read out correctly to be printed, then the ISR fires, changes the variable, and gives control back to the main loop. The 2nd byte, now not what it was supposed to be, is read out, leading to a corrupted variable! Ex: let's assume `isr_counter` was 0xFFFF, or 65535, at the moment it is supposed to be printed, and lets say the low byte is read out correctly as 0xFF, then the ISR fires, the variable is incremented to 0x0000 since it overflows, then the control goes back to the main loop, and the 2nd byte is read out, it is now corrupted. What will be printed would be the contents of the variable containing 0x00FF, or 255, when what *should* have been printed out was 65535, and the next value after that to be printed out would have been 0. And what if the high byte was read out correctly before the low byte? (I'm not sure which order AVR mcus read the bytes), then your corrupted value would be 0xFF00, or 65280, when what *should* have been printed out was 65535 (0xFFFF), and the next value after that to be printed out would have been 0 (0x0000).

So, simply making the variable a `uint8_t` magically solves this race condition **for this one particular case** because 8-bit variables on 8-bit CPUs are read or written atomically, which means "as an atomic, or whole, single, unit, not broken up or corrupted by interrupts or other threads". **All operations which take 1 single CPU instruction cycle are automatically atomic, because they cannot be interrupted.**  For any multi-instruction-cycle code block which we need to be atomic, we must **force it to be atomic by using what I call "atomic access guards".** Reading a 1-byte variable on an 8-bit CPU, or writing a 1-byte variable on an 8-bit CPU, is 1 instruction, so it is naturally atomic. Incrementing or decrementing a 1-byte variable, however, is NOT an atomic operation, since the variable must be read, modified, and written. Reading a 2-or-more-byte varible on an 8-bit CPU, or writing a 2-or-more-byte varible on an 8-bit CPU, is also NOT atomic, since it takes one instruction per byte. This means just reading a 2-byte variable or writing a 2-byte variable can be interrupted by an ISR in the middle of the operation, which leads to data corruption if you do not use atomic access guards!

Now, your case: would making `pos` into a 1-byte variable as `volatile int8_t pos = 0;` solve the race condition? No, not at all. Let's look at your code again, this time imagining that `pos` is an `int8_t` instead of an `int` (which is `int16_t` on AVR Arduino):

    void loop() {
      if (oldpos != pos) {
        oldpos = pos;
        Serial.println(pos);
      }
      delay(100);
    }

Let's walk through a potential scenario: `pos` is 7. `oldpos` is 6. So, `oldpos != pos` is true, and you enter the `if` statement. Now, right as you enter, the ISR fires, `pos` is changed by the ISR to 6 (or to any other number--it's still a race condition and undefined behavior), `oldpos` is now set to 6, which is what it already was, and you have data corruption because _it should have been set to 7!_ Note that when I say this is undefined behavior in this case, I simply mean we cannot predict what will happen. This is buggy code. Code should *always* be predictable. Undefined behavior is a bug! Note also that when talking about "undefined behavior" according to C or C++ standards, we mean "the standard doe not _define_ what will happen", which means your code may act one way on one architecture or with one compiler, and differently on another architecture or with a different compiler. This is not what I am talking about here. Here, when I say "undefined behavior" I don't mean "according to the C or C++ standard", I mean, "according to the rules of logic."

The solution to fix your race condition is to *enforce* atomic access using what I like to call **"atomic access guards"**. On multi-threaded systems, this means to use **locks, mutexes, and semaphores**. On single-threaded systems, such as this, it means to **disable any interrupt which could interfere and cause the race condition** (you can think about interrupts interacting with the main loop as a parallel to one thread interacting with another thread, so it is as though you had a multi-threaded system just by having a single-threaded system + interrupts). For AVR microcontrollers, disabling interrupts to act as atomic access guards is usually done by disabling global (or all) interrupts. BUT, disabling interrupts introduces jitter by delaying the processing of the ISR, so it should be done _for as short of a time period as possible!_ **That means you should just disable interrupts, make copies of volatile variables, and re-enable interrupts.** This is an important point though: sometimes, in the case of using a 1-byte volatile variable, using a *copy* of your variable, which can NOT be changed at any moment by an ISR, also, in and of itself, acts as a form of "atomic access guards" and solves the problem all by itself. I'll post an example of this below.

But: **DANGER DANGER!** It's a "best practice" to always back up the interrupt state, disable interrupts, then restore the interrupt state, rather than just turning interrupts off then back on all the time. Why? Because what if you write a function which sometimes gets called _from within an ISR itself?_ If you enable interrupts inside an ISR, you just enabled _nested interrupts_, which leads to _more race conditions._ If you know exactly what you are doing and you *want* nested interrupts, this is fine! But, chances are one is just making a mistake here and _accidentally_ enabling nested interrupts without even realizing it, leading to really-hard-to-track down data corruption due to nested interrupts. Safety-critical systems can crash and hurt people when this happens, so we can't ever allow unmanaged race conditions.

So, do it like this:

1. Force atomicity in `loop()` by backing up the interrupt state.
1. Make copies of the volatile variables.
1. Then restore the global interrupt state.
1. Use only the copy of the varible in the rest of your code. This (using the copy) is also a form of "atomic access guards" all by itself for later code blocks using the variable because using the copy instead of the volatile variable means that the variable can NOT be changed at any moment by an ISR. This enforces atomicity as well!

Making a copy of the volatile variable and nothing else, while interrupts are disabled, _minimizes time where interrupts are disabled_, making your code the best it can possibly be! It should now look like this:

**1 of 3: THE BEST WAY!:**

    volatile int pos  = 0; // assume this variable is still an `int`, which is 2-bytes

    void loop() {
        uint8_t SREG_bak = SREG; // back up the global interrupt state
        noInterrupts(); // disable interrupts
        // make copies of your volatile variables here
        int pos_copy = pos;
        // restore interrupt state, turning them back ON if they were ON before,
        // or leaving them OFF if they were OFF before.
        SREG = SREG_bak;

        // Now do what you want with the copy, using pos_copy ONLY,
        // to avoid race conditions! (ie: using this copy here enforces
        // this entire block to be naturally atomic now, and by itself
        // is a form of "atomic access guards", as explained above.)
        if (oldpos != pos_copy) {
            oldpos = pos_copy;
            Serial.println(pos_copy);
        }
        delay(100);
    }

Solved!

Let's look at 2 other examples, however, for completeness.

Here, we force the whole `if` statement block to be atomic. This looks correct at first, but has two problems: 1) [a true bug] `Serial.println` will block forever if the outgoing serial buffer is full, as it relies on interrupts to empty it, and if interrupts are off, that will ever happen, and 2) [an undesirable effect leading to performance issues, but *not* a bug] it keeps interrupts off for a longer time period than is necessary. The code above was best: it kept interrupts off the absolute minimum time possible by just making copies of the volatile variables, and it ensured this whole `if` statement block was atomic by simply using the copy there, which automatically acts as an "atomic access guard" by itself and enforces atomicity in the `if` statement block.

**2 of 3: this still has 2 problems: one is a bug, and one is a performance issue but not a bug:**

    volatile int pos  = 0; // assume this variable is still an `int`, which is 2-bytes

    void loop() {
        uint8_t SREG_bak = SREG; // back up the global interrupt state
        noInterrupts(); // disable interrupts

        if (oldpos != pos) {
            oldpos = pos;
            Serial.println(pos);
        }

        // restore interrupt state, turning them back ON if they were ON before,
        // or leaving them OFF if they were OFF before.
        SREG = SREG_bak;

        delay(100);
    }

And lastly, what if the volatile variable was a 1-byte variable? Well, then you could simplify to this, since reading a 1-byte variable is naturally an atomic operation!

**3 of 3: this works too (without bugs and without performance issues), but ONLY if your volatile variable here is 1-byte!:**

    // this variable is now a 1-byte variable, which has naturally atomic read and
    // write operations! (but not increment or decrement)
    volatile int8_t pos  = 0;

    void loop() {
        // Make copies of your volatile variables here.
        // Being a 1-byte variable on an 8-bit (1-byte) CPU architecture, this operation
        // is already naturally atomic, so no need for "atomic access interrupt guards".
        int8_t pos_copy = pos;

        // Now do what you want with the copy, using pos_copy ONLY,
        // to avoid race conditions! (ie: using this copy here enforces
        // this entire block to be naturally atomic now, and by itself
        // is a form of "atomic access guards", as explained above.)
        if (oldpos != pos_copy) {
            oldpos = pos_copy;
            Serial.println(pos_copy);
        }
        delay(100);
    }

For _3 other ways to create atomic access guards in 8-bit AVR-based Arduinos_, see my answer from 2016 here: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why/39693278#39693278.

_Last comment:_ Paul Stoffregen is one of the most-expert in Arduino in our day. I'm sure he makes mistakes, but my default is to trust anything he's written. He's a most-excellent software developer and engineer: one of the absolute best in the entire world. Look for bugs in what he writes, and let him know if you found any, but you have unaddressed race conditions here, so that's what I'd look at first.

# References:
1. My own race condition problem: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why
1. My own race condition solution, demonstrating 3 (or 4, depending on how you look at it) ways to enforce **"atomic access guards"** on AVR-based 8-bit Arduinos: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why/39693278#39693278


message:
Why does the transistor burn out

I have an arduino uno which turns on a water pump (12V, 3.6W) once every 10 hours for a few minutes (I've followed [this](https://www.instructables.com/id/Automatically-water-your-small-indoor-plant-using-/) tutorial on how to connect the water pump). To turn on the water pump I used a **PN2222A transistor**, and connected the **base** in serial with a **220 ohm** resistor to the **digital pin 9**.
A few minutes after turning on the power on my Arduino UNO the **PN2222A** transistor burned out (lots of smoke coming out of it).

I also used a **1N4007** diode, cathode connected to the positive pin, and anode to the negative pin of the water pump.

The power supply outputs around 12.6V

Maybe the resistor is too low/weak?

I've created a schematic [here](https://www.tinkercad.com/things/93WNCASSUjE), attached it's a snapshot of it.

[![tinkercad schematic][1]][1]

**EDIT1:**
Here is a picture on how I connected my transistor. I've removed from the photo:

 - the input wires (should be top-right of breadboard)
 - wire to arduino digital pin (should be on h-19 on the breadboard)
 - water pump from the breadboard (positive pin: c-2, negative pin: h-2)

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

**EDIT2 (a solution that worked for me):**

It looks like the input to the arduino (arduino and the pump share the same 12V input, but the arduino's goes through a step down converter to 10V) was a bit loose (to be more specific, the negative pin was loose) and randomly, the arduino would shut down and then the pump would start (maybe because the digital pin becomes HIGH, dont know why though) all while the arduino is shut off. That's when the transistor (PN2222A) burned out. I switched to TIP120 with a 1k resistor as @Jot suggested and looks like when the same problem with the power happens, nothing is burning out :)

  [1]: https://i.stack.imgur.com/lzeB8.png
  [2]: https://i.stack.imgur.com/VSxU4.jpg

body:
Seems to be a simple pinout issue, I checked the PN2222A and its pins are in EBC order. You probabily reversed it and burned the transistor. Reverse the transistor and the problem will be solved.

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

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

<!-- End schematic -->


body:
TinkerCAD may have mislead you on the pinout for the transistor

**TinkerCAD**

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

**PN2222A**

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

  [1]: https://i.stack.imgur.com/z6D3Z.jpg
  [2]: https://i.stack.imgur.com/y9RxJ.jpg


body:
Datasheet for the PN2222A indicates it is only good for 150mA Ic for a pulse test, pulse width <= 300 microseconds, 2% duty cycle.

Your water pump, 12V, 3.6W.  With P=IV, or P/V = I, then 3.6W/12V = 0.3A, indicates this transistor is not the correct choice for this application.


body:
By this, does it mean that you still have a problem turning the pump on? Because a PN2222A should handle up to 1A through its collector, as the datasheet states http://www.mouser.com/ds/2/149/PN2222A-371983.pdf
>  That's when the transistor (PN2222A) burned out. I switched to TIP120 with a 1k resistor as @Jot suggested and looks like when the same problem with the power happens, nothing is burning out :)

If you are still having problem turning the pump on, try turning it on manually by moving the jumper that is on the Arduino pin 9 to either GND or 5V, that should indicate if the problem lies on the Arduino pin (GPIO) or on the transistor.

It is also important to check the current needed by the pump, because the datasheet indicates that, to have a current IC = 350 mA -> IB = 35 mA which is close to the maximum of an Arduino pin (40 mA). If the Arduino pin cannot supply enough current to put the transistor in saturation mode, it will either kill the pin or put the transistor in its linear region, meaning it will dissipate a lot of power (Ic*Vce).
> Base-Emitter Saturation Voltage
>
> IC = 150 mA, IB = 15 mA
>
> IC = 500 mA, IB = 50 mA


body:
It looks like the input to the arduino (arduino and the pump share the same 12V input, but the arduino's goes through a step down converter to 10V) was a bit loose (to be more specific, the negative pin was loose) and randomly, the arduino would shut down and then the pump would start (maybe because the digital pin becomes HIGH, dont know why though) all while the arduino is shut off.

That's when the transistor (PN2222A) burned out. I switched to TIP120 with a 1k resistor as @Jot suggested in one of the comments and looks like everything is ifne now (even when the same problem/bug with the power randomly happens)


message:
Faster Arduino Mega

I am using Arduino Mega 2560 for interfacing devices such as the [Maxim MAX22500E][1] and [TI ADS1241][2].

Now I am requiring more speed for hopefully the same coding, and I am thinking in the Arduino Due (84 MHz Clock) which is enough faster than the Arduino Mega (16MHz Clock) but imposes working with 3.3V, hence using some 3.3V 5V [level conversion][3] for every input and output.

If I want to keep the same "arduino" coding environment, is there another faster 5V processor? Or should I focus in the strategy of interfacing the 5V devices from a 3.3V processor?

  [1]: https://datasheets.maximintegrated.com/en/ds/MAX22500E-MAX22501E.pdf
  [2]: https://www.ti.com/lit/gpn/ADS1241
  [3]: https://next-hack.com/index.php/2017/09/15/how-to-interface-a-5v-output-to-a-3-3v-input/

body:
You should begin working with 3.3V. 5V is getting rarer and rarer as far as "real world" applications go.

Many devices that you have been using at 5V will also work at 3.3V (such as the MAX22500E). Running those at 3.3V will mean you don't need logic level translation.

Others, like the ADS1241, have "split power" where you can have different logic voltage (DVDD) and analog voltage (AVDD), so you just run the logic at 3.3V and the analog at 5V so you don't need a logic level translator.

For those few rare devices that have to run at 5V and don't have a 3.3V equivalent, yes you will need to use some logic level shifting.


message:
Arduino Nano - Strange problems

# Update:
**The arduino works only when I connect 3.3v to reset pin. And I successfully uploaded a sketch but it stops when I disconnect 3.3v and reset.**
# Update 2:
**-- Removed --**
# Update 3:
**Its working perfectly and running smoothly for like 5+ min but the problem starts again**

----------

I bought a new arduino nano V3 clone. Till now, I have been facing very strange problems with it:

 - The pre-uploaded blinking sketch works for a few seconds (like 5 sec and only works when powered after a break) and then it starts to glitch
 - The L led stays on or off after that
 - Reset button does nothing (No led blinks or anything)
 - Can't upload any sketch
 - Programmer is not responding
 - RX led blinks during uploading (3 times only)
 - USB not recognized when connected

Here is what I tried to solve:

 - Loopback test > Successful
 - Changed ports
 - Changed proccessor
 - Tried uploading with parallel programming
 - Sketch worked with another arduino nano clone
 - Manual reset
 - Tried with Old bootloader
 - Tried uploading sketch with older version of Arduino IDE.

Here is the exact image of one I have:

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

Here is the error message:

    Arduino: 1.8.10 Hourly Build 2019/07/23 10:33 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"

    C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\arduino-builder -dump-prefs -logger=machine -hardware C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware -tools C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\tools-builder -tools C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -built-in-libraries C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\libraries -libraries C:\Users\MN\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10810 -build-path C:\Users\MN\AppData\Local\Temp\arduino_build_778230 -warnings=none -build-cache C:\Users\MN\AppData\Local\Temp\arduino_cache_273206 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -verbose C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\examples\01.Basics\Blink\Blink.ino
    C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\arduino-builder -compile -logger=machine -hardware C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware -tools C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\tools-builder -tools C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -built-in-libraries C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\libraries -libraries C:\Users\MN\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10810 -build-path C:\Users\MN\AppData\Local\Temp\arduino_build_778230 -warnings=none -build-cache C:\Users\MN\AppData\Local\Temp\arduino_cache_273206 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -verbose C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\examples\01.Basics\Blink\Blink.ino
    Using board 'nano' from platform in folder: C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\arduino\avr
    Using core 'arduino' from platform in folder: C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\arduino\avr
    Detecting libraries used...
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10810 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\sketch\\Blink.ino.cpp" -o nul
    Generating function prototypes...
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10810 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\sketch\\Blink.ino.cpp" -o "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\preproc\\ctags_target_for_gcc_minus_e.cpp"
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\preproc\\ctags_target_for_gcc_minus_e.cpp"
    Compiling sketch...
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10810 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\sketch\\Blink.ino.cpp" -o "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\sketch\\Blink.ino.cpp.o"
    Compiling libraries...
    Compiling core...
    Using precompiled core: C:\Users\MN\AppData\Local\Temp\arduino_cache_273206\core\core_arduino_avr_nano_cpu_atmega328old_96bc3f74325b2724b539066aa6a6e44d.a
    Linking everything together...
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\tools\\avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230/Blink.ino.elf" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\sketch\\Blink.ino.cpp.o" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230/..\\arduino_cache_273206\\core\\core_arduino_avr_nano_cpu_atmega328old_96bc3f74325b2724b539066aa6a6e44d.a" "-LC:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230" -lm
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\tools\\avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230/Blink.ino.elf" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230/Blink.ino.eep"
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\tools\\avr/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230/Blink.ino.elf" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230/Blink.ino.hex"
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\tools\\avr/bin/avr-size" -A "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230/Blink.ino.elf"
    Sketch uses 924 bytes (3%) of program storage space. Maximum is 30720 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr/bin/avrdude -CC:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM6 -b57600 -D -Uflash:w:C:\Users\MN\AppData\Local\Temp\arduino_build_778230/Blink.ino.hex:i
    An error occurred while uploading the sketch

    avrdude: Version 6.3-20190619
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM6
             Using Programmer              : arduino
             Overriding Baud Rate          : 57600
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x85

    avrdude done.  Thank you.

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

What is wrong with my arduino?

Note: I was uploading the blink (Example) code, tried with others too...

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

body: Sounds like it is missing the 10K reset pullup resistor.  Try adding one from the RST pin to VCC, which is pin 2 of the 6-pin header.


body:
The compiler log said:

`-libraries C:\Users\MN\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10810`

It seems your AVR is not updated, try to update your `Arduino Avr Bords` on the boards manager. also make sure your `avrdude.conf` file might to be :

`
...
Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
...
`

Dont forget to wire RX to GND or connected RX to TX directly.

Hope this helps.


body: When soldering the pin headers, I used too much flux. So this caused contact between the GND and RST on the ICSP causing the arduino to stay in the reset position. I removed the ICSP pin headers and there was a lot of flux. I removed it and now my arduino is working perfectly. Thanks to @Juraj for figuring it out that there must be a contact between GND and RST


message:
Reading from EEPROM and combining

I'm trying to read from the EEPROM and combine the information and send it out over SoftwareSerial using write() function but i'm getting the following error

    error: invalid operands of types 'const char [3]' and 'const char*' to binary 'operator+'

----------

    void loop()
    {
      const char* eTest1 = EEPROM.read(1);
      const char* eTest2 = EEPROM.read(2);
      const char* eTest3 = EEPROM.read(3);

      char combinedVal[] = eTest1+":"+eTest2+":"+eTest3;
      bluetooth.write(combinedVal);
    }

body:
You cannot use the + operator for that.

However, since EEPROM.read only returns one byte and not a string, you can do a much easier implementation:

    void loop()
    {
      char result[] = "1:2:3";
      for (int item = 0; item < 3; item++)
      {
        result[item * 2] = EEPROM.read(1 + item);
      }
    }

This first create a string "1:2:3", where the digits are overwritten in the for loop by that item. Note that the digits in the string do not matter, it's just some free 'comment', it also should work when using "x:x:x".


message:
Arduino powered from motor shield and USB issue

I am using an Arduino (Elegoo) Mega with Motor shield to drive a digital train set. The Motor shield is powered from a 12v 1.1 amp dc power supply and I have the Arduino plugged into my laptop via USB. I have an app which sends commands via serial to the mega which are then turned into commands for the train set and sent down the line.

When using this all of a sudden the main chip on my Arduino blew up and my Laptop seemed to blow a re-settable fuse shutting off instantly (It was dead for about 10-20 minutes then worked again).

**Would this be because something caused power to get back through the Arduino to my laptop?**

The railway will short from time to time if a locomotive derails for example.

I know there is a trace on the Motor Shield which prevents the shield powering the Arduino. I have now cut this although it says you only need to cut it if using over 12v.

body:
Looking at pictures of the Elegoo Mega 2560 they use a "hash fill" for the pour on the tab of the regulator, not a solid fill, and zero vias to another dissipation layer on the reverse. While this may look more funky it provides only a fraction of the heat dissipation of a solid double-layer fill, meaning the regulator is more likely to overheat. Also because this is a Chinese clone the component quality will be lower (cheaper) meaning the regulator probably doesn't have proper thermal overload protection.

So it gets too hot too easily, and **pop** your Arduino is dead as the regulator fails "short" and 12V gets pumped directly into the rest of your Arduino.

Byebye Arduino, and byebye computer (fortunately temporarily in the case of your computer).


body: Be careful dissing Chinese components as 'poor quality' Your TV, Phone, computer and practically any other electronic item you own has chines built components in it. Most of these items are assembled in China anyway. I agree the board design may be poor but component quality from China is fast becoming a thing of the past.


message:
Fade In/Fade Out with multiple LED strips

I want to make a strip led application(Fade In/Fade Out).Each strip has 48 pixels.One of the strips should be red and the other should be blue.Using the for loop, I managed to fade in-fade out a small number of strips (eg 10).But when I fade in / fade out all of the 48 leds, the code behaves as if there is a "delay".I guess that's because there's a lot of data in the for loop.Is there a way to do fade in / fade out without using a for loop?

    #include "FastLED.h"
    #define NUM_LEDS_PER_STRIP 48
    CRGB redLeds[NUM_LEDS_PER_STRIP];
    CRGB blueLeds[NUM_LEDS_PER_STRIP];
    void setup() {
    FastLED.addLeds<NEOPIXEL, 6>(redLeds, NUM_LEDS_PER_STRIP);
    FastLED.addLeds<NEOPIXEL, 7>(blueLeds, NUM_LEDS_PER_STRIP);
    FastLED.setBrightness(0);
    }

    void loop() {
    //fade in
    for(int i=0;i<256;i=i+5) {
    for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
    FastLED.setBrightness(i);
    redLeds[j] = CRGB(255,0,0);
    blueLeds[j] = CRGB(0,0,255);
    FastLED.show();
    }}
    //fade out
    for(int i=255;i>=0;i=i-5) {
    for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
    FastLED.setBrightness(i);
    redLeds[j] = CRGB(255,0,0);
    blueLeds[j] = CRGB(0,0,255);
    FastLED.show();
    }}
    }

body:
Each change of brightness requires sending out 48 LEDs x 3 bytes/strip, = 144 bytes = 1152 bits of data. Each bit needs 2.5uS of data, so 2.88mS minimum at 400 KHz data rate. I don't know what rate FastLED.h uses, might be as fast as 800 KHz. How many strips? 2? So double that.

Each string needs all of its data sent out if any one LED changes, so you might change 1 LED, and leave 143 alone, all the data still gets sent out. That's just the way the addressable strips work.


body:
CrossRoads already gave a likely reason for the delay (so upvoted).

One way to solve it is using one microcontroller (slave) per LED string and split the load, and using one microcontroller as master:

- Use a fast communication protocol between your current MCU (master) and the slaves (preferably small/cheap ones like Arduino Mini/Micro's), e.g. SPI which is easy to use for communication.
- To make sure they all start at the same time, you can first send all data (SPI), and at the end after all data is sent to all slaves, set on the master a GPIO high where all slaves listen to, knowing they have to start sending.
- SPI is very fast, but if you want to save communication time, you can make some smart commands (e.g. like sending a command to reset a group of bytes, or change a group of bytes by a certain value etc). Depending on what commands you want, it might be needed to store the data of all led strips on your Arduino, which can cost quite some money (see CrossRoads answer).


message:
NodeMCU Exception 28 - intermitent problem

I am SOMETIMES getting `exception 28` when running a web upload (over a very unstable rural internet CPE link - wifi is fine, but feed goes on and off):

 Decoding stack results
 0x40213b8c: dns_gethostbyname at core/dns.c line 1472
 0x40204d95: ESP8266WiFiGenericClass::hostByName(char const*, IPAddress&, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp line 468
 0x40208d7c: HardwareSerial::write(unsigned char const*, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/HardwareSerial.h line 159
 0x4020519c: WiFiClient::connect(char const*, unsigned short) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/WiFiClient.cpp line 98
 0x40208fe0: Print::println(char const*) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 190
 0x402040c4: uploadAgrigis(char const*) at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 360
 0x40208f41: Print::write(char const*) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.h line 60
 0x40208f6c: Print::println() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 178
 0x40204a2b: loop() at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 258
 0x402074f0: TwoWire::endTransmission() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/Wire/Wire.cpp line 151
 0x40203a04: BH1750_Init(int) at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 1121
 0x40209d3c: loop_wrapper() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/core_esp8266_main.cpp line 125

My code at line 360 is

    if (client.connect(serverName,80)) {

My current strategy is to keep the wifi connection open all the time.  Should I test for connection before attempting to connect to the server?

body:
Exception 28 is, according to the [exception list document](https://www.espressif.com/sites/default/files/documentation/esp8266_reset_causes_and_common_fatal_exception_causes_en.pdf):

> Access to invalid address

The most common cause is trying to read or write from/to a NULL pointer.

It *could* be because you have debugging turned on, and that debugging is trying to print something that didn't get returned properly from another function call (the call failed) - most likely looking up a host name (`hostByName()`) due to your intermittent internet connection.

This may sound counter intuitive, but try turning off debugging to see if that helps reduce the number of crashes.


message:
A recommendation for a fast-response-time-resolution-mp3-module for arduino

I am working with Arduino which activates a box which is similar to a [Skinner Box][1]. Some of the output sound stimuli are sine waves with duration of less then 5 milliseconds. I output the sounds using the MP3 module [DFR0299][3].

However there are too much problems using this module: it seems like the module has a wakening delay of around 100 ms, so it is not working well with this duration and below (the response time of the module is important).

So, I was thinking of buying a better module. However, I am far from being an expert in these things..

I can look for other modules in the internet, but, just from looking at the datasheets, I cant tell if the quality of the module is what I need.

I would be grateful if any of you could give me names of modules that might feet my requirements (or even advice me at what to look in the datasheets)

Thanks!

  [1]: https://en.wikipedia.org/wiki/Operant_conditioning_chamber
  [2]: https://www.digikey.co.il/product-detail/he/dfrobot/DFR0299/1738-1041-ND/6588463
  [3]: https://cdn.instructables.com/ORIG/FGT/H5J3/IUKEZCYF/FGTH5J3IUKEZCYF.pdf

body:
I'm going to suggest that you stay away from these mp3 modules. It is perfectly reasonable to use a stand-alone arduino unit to directly generate sound using the digital output pins with a low-pass filter RC circuit. This is the most efficient way of doing this and will give you a very low activation latency.

https://playground.arduino.cc/Code/PwmFrequency/

The other option is to connect a DAC circuit and simply build a sample table for the wave outputs you need for each tone.


body:
MP3 modules are way to complex for this project. Tracks of 5ms at max may even be stored directly on the Arduino in raw wave format (without any compression)(depending on the resolution and sample frequency), and then outputted by it.

Since the PWM with low-pass filter method is rather noisy and not very accurate (especially for higher frequencies), you may want to use an external DAC chip. These are available with parallel input port or with SPI. I would suggest using SPI, which is fast and does only need 3 pins (+1 for slave select, if needed). Put the raw wave values into an array and send them to the DAC to output. Depending on available memory and number and size of your tracks you may be able to save them directly on the Arduino. If not, you may want to use an SD card, to save a library of tracks, which then get loaded onto the Arduino and played. This way you would only need to hold 1 or 2 (if double buffered) tracks in the Arduino's RAM.


message:
Changing I2C address of MPU-6050

Is it possible to change I2C address of MPU-6050 ?

I am trying to connect a bunch of MPU-6050 to my Arduino.

Almost all of them are running on the same address. Few are running on different address.

Can anyone tell me how to change I2C address of MPU-6050 if it is possible ?

body:
The MPU-6050 has an address pin, marked as A0, which can be used to set the LSB (least significant bit) of the address. So if you connect A0 to ground, the address will be `0b1101000`, if you connect it to Vcc it will be `0b1101001`. You can find this information in the table under capter 6.4 in the [MPU-6050 datasheet][1] (page 15). Normally this pin is getting hardwired, but you can also connect A0 to a digital output pin of your Arduino and dynamically change the address of the MPU.

So with this pin you can have 2 different MPU-6050's on the bus. If you need more, you can keep all MPU's on one address, while pulling the MPU, that you want communicate with, to the other address. I described this principle at the end of my answer to [this question][2]. It is about a different chip, but the principle is the same.

It is important, that you cannot have multiple devices with the same address on one I2C bus, unless you never communicate with that address. When you try to use an address, where multiple devices will answer, the I2C bus most likely will get stuck, or the data will get corrupted. As long as such an address is never called, everything is fine.

  [1]: https://store.invensense.com/datasheets/invensense/MPU-6050_DataSheet_V3 4.pdf
  [2]: https://arduino.stackexchange.com/questions/67043/software-i2c-sending-data/67044#67044


message:
Why Buzzer interfere with PWM?

This is the code:

    #define TMST A2 // Thermistor
    #define BZR 10  // Buzzer
    #define FanP 11 // Fan

    void setup() {
      DDRD = B11000000;
      DDRB = B00001111;
      DDRC = B00000000;
      TCCR2B = TCCR2B & B11111000 | B00000101; // pin 3 & 11 -> 245Hz
      T0 = 25 + 273.15;
    }

    void loop() {
      if (hallState > magnetDistance) {
        PORTB &= ~(1 << 0); // port manipulation -> LOW
        strcpy(WPStatus, "OFF");
        if (Alarm == 1) { // this will be set in setting menu
          if ((millis() - BZRT) > 500) {
            tone(BZR, 2300);
            BZRT = millis();
          }
          if ((millis() - BZRT) > 250) {
            noTone(BZR);
          }
        }
        else {
          noTone(BZR);
        }
      }
      else {
        PORTB |= (1 << 0); // port manipulation -> HIGH
        noTone(BZR);
        strcpy(WPStatus, " ON");
      }

      if ((millis() - fanTimer) > 2000) { // checks every 2 seconds if temperature changed
        Thermistor();
        if (TX <= 32) {
          analogWrite(FanP, 60); // Fan spinning speed
        }
        if (TX > 32 && TX <= 36) {
          analogWrite(FanP, 120);
        }
        if (TX > 36) {
          analogWrite(FanP, 255);
        }
        fanTimer = millis();
      }
    }
    float Thermistor() { // reading and calculating from thermistor
      VRT = analogRead(TMST);
      VRT = (5.00 / 1023.00) * VRT;
      VR = 5 - VRT;
      RT = VRT / (VR / 10000);
      ln = log(RT / 10000);
      TX = (1 / ((ln / 3977) + (1 / T0)));
      TX = TX - 273.15;
      return TX; // returning the temperature
    }

The 5V buzzer connected to a PWM pin with a 100 ohm resistor, thermistor and fan are connected to Arduino like this:

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

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

<!-- End schematic -->

Why When buzzer is alarming fan stops spinning?

body:
The `tone()` command uses Timer2 to generate the square wave (it triggers an interrupt which toggles an IO pin).

However Timer2 is also used to generate the PWM signal on pins 3 and 11.

Thus you cannot use `tone()` and PWM on pins 3 or 11 simultaneously.

The simple fix: use PWM from pins 5, 6, 9 or 10 to control your fan.


message:
GY91 IMU module, Interrupt?

Are there interrupt Pin in the GY91 Module?
If not, are there good alternative for periodic sensor reading?
(apart from mcu schedule/external timer)

body:
No. The INT pin of the MPU-9250 is not presented on the IO header of the GY-91.

The *only* way of knowing what is going on inside the MPU-9250 at any time is to go and look. I.e., periodic polling of the sensor.

If you want to use the interrupt pin you will have to shop around for a different module that gives you access to that pin.


message:
flash read err, 1000

I know this question has been asked multiple times but solutions giving there hasn't been working,

I've got an esp32 soldered to my own designed PCB board with a UART to USB converter all that is working fine, I can get connected to my esp from the Serial monitor.

But it prints every about 0.5s:

    rst:0x10 (RTCWDT_RTC_RESET)
    boot:0x13 (SPI_FAST_FLASH_BOOT)
    flash read err, 1000 ets_main.c
    371 ets Jun 8 2016 00:22:57

Solutions have been to make sure to have 3.3v on the esp. I find it unlikely to have anything to do with it, 'cause its voltage range goes from 2.6v to 3.6v, but anyway I have tested it with an advanced transformer and a multimeter to check that there was 3.3v on the Vcc pin (didn't change anything).

All help would be appreciated.

Here is a bit more info:

I've also connected a 10uF capacitor (someone told me to try that).

If I pull IO0 to ground, it prints waiting for download in the serial monitor and I can almost upload the program, this is what I get:

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

> THERE IS NO CONNECTION BETWEEN NEIGHBORING PINS

(I have checked with multimeter)

PCB board:

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

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

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

  [1]: https://i.stack.imgur.com/BLthw.png
  [2]: https://i.stack.imgur.com/lGWxK.png
  [3]: https://i.stack.imgur.com/a5IWU.png
  [4]: https://i.stack.imgur.com/RCZn3.jpg

body: Your PCB is lacking in the majority of things you need to get the module working. These modules are not "simple" in that you provide power and forget about it. You must add all the *required* support components. Those support components are **NOT optional**. For example: you aren't setting the boot mode properly with the right pullups. You lack a capacitor on the power pins (I told you to add one already. Where is it?). Also your power traces are too thin. The impedance is too high.


body:
ok, the solution was to add a 10k pull-up resistor to the EN pin, as shown [HERE][1]

No capacitor needed

  [1]: https://www.14core.com/wiring-and-flashing-programming-esp-32-esp32s-with-usb-ttl-uart/?cn-reloaded=1


message:
Lipo Battery level display using nodemcu

I'm designing a connected collar for pets for a project, for this I am using a nodemcu on ESP8266 powered by a Lipo battery I'm guessing around 1000mAh of capacity is enough for a respectable autonomy (? any advices).
Lipo model : https://www.lipolbattery.com/lithium polymer battery.html
In order to charge the battery I have found this USB LiPo charger (https://learn.sparkfun.com/tutorials/lipo-usb-charger-hookup-guide/all), my first question is: Is it still usable for higher capacity LiPo batteries (1400mA)?
Also I would like to display the battery level via and RGB LED (example: green is for battery FULL battery and RED for LOW battery level in need of charging) is there any way to do this? Thank you

body:
It is still usable for higher capacities. I recommend you tp4056 and some step up converter.
You can use resistor divider (that drops safely voltage to nodemcu 3.3v) and connect its output to an analog pin of your nodemcu. Values of resistors must be high, like 10k.
You can simply connect your diode to nodemcu and code if voltage is less than 3.2v let the red diode turn on, when above 3.8v let the green diode turn on


body:
Answering the second question "Also I would like to display the battery level...?" (next time, please open a new question for that):

To measure the module voltage level (a.k.a. VCC) of a NodeMCU (which is just a board containing an ESP8266 chip) programmed in Arduino IDE (which I assume given that you ask on the arduino stackexchange), this here applies:

> To read VCC voltage, use ESP.getVcc() and ADC pin must be kept unconnected.
> Additionally, the following line has to be added to the sketch:
>
> ADC_MODE(ADC_VCC);
>
> This line has to appear outside of any functions, for instance right after the
> \#include lines of your sketch.

[Source: ESP8266 Arduino reference][1]

So you could just drive a red and a green LED (don't forget the mandatory current limiting resistor) from any other two pins of your NodeMCU. Then switch them in your sketch if VCC falls below 3.2V (you may need to experiment with that because of measurement tolerances; a [sketch to start with that would be here][2].

  [1]: https://github.com/esp8266/Arduino/blob/master/doc/reference.rst
  [2]: https://gist.github.com/chaeplin/d47c2de3c6d92513996cf0163aed531b


message:
Serial Port fails with speeds greater than 19200

In Arduino Mega 2560 R3, properly selecting the Serial Monitor bauds, this code works with `#define R 38400`, but for some reason, not with `#define R 19200` (?),
<!-- language-all: lang-cpp -->

    #define R 38400
    int rate=R;
    HardwareSerial* hwSerial[]={&Serial,&Serial1,&Serial2,&Serial3};
    void setup() {
        for (int i=0;i<=3;i++){
            hwSerial[i]->begin(rate);
            while (!hwSerial[i]);
        }
        hwSerial[0]->print("Hello World");
    }

    void loop() {
    }

Both speeds should be not problematic for Arduino, what is happening?

It seems the `int rate R;` is problematic when changing speeds (??).

body: Answer is simple. You assign 38400 to a variable of type int. The signed range of integer values that can be stored in 16 bits is −32,768 through 32,767;


message:
Decoding RC transmitter data

I would like to use my FSi6 transmitter but not the receiver that comes with it (I´m trying to save weight), for that I was planning to get one of this NRF24L01 breakout boards. The problem is, how do you interpret the incoming traffic? After some googling, I couldn´t find any information from flysky.

I would think that this is a common thing to do, as you could pair the transmitter with another receiver (perhaps other brand) so there must be a standard protocol.

Any ideas?
Thanks!

body:
Unless the FSi6 (whatever that is) uses an nRF27L01+ as its transmitter, then no - you can't.

The nRF24L01+ chip will *only* communicate with other nRF24L01+ chips.  It contains its own custom protocol within the chip and it can only talk that protocol and no others.


message:
Maximum sampling rate of Arduino Mega2560

I'd like to know what is the maximum sampling rate achievable while using ADC on Arduino Mega2560.

Thanks

body:
The beginning of section 26 of the [datasheet for the ATMega2560][1] gives the following data:

> • 13µs - 260µs Conversion Time
• Up to 76.9kSPS (Up to 15kSPS at Maximum Resolution)

  [1]: https://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf


message:
Can you help me figure out why my arduino code is not working

The code is made to sense were an object is and send out

    int const trigPin = 10;
    int const echoPin = 9;
    int const buzzPin = 1;
    int const LED1 = 2;
    int const LED2 = 3;
    int const LED3 = 4;
    void setup()
    {
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(buzzPin, OUTPUT);
    pinMode(LED1, OUTPUT);
    pinMode(LED2, OUTPUT);
    pinMode(LED3, OUTPUT);
    }
    void loop()
    {
    int duration, distance;
    digitalWrite(trigPin, HIGH);
    delay(1);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    //                                      Go
    distance = (duration/2) / 29.1;
    if (distance <= 1000 && distance >=0) {
    digitalWrite(LED1, HIGH);
    } else {
    digitalWrite(buzzPin, LOW);
    digitalWrite(LED1, LOW);
    }
    delay(60);
    }
    //                                      SLOW
    if (distance <= 50 && distance >=0) {
    digitalWrite(LED2, HIGH);
    } else {
    digitalWrite(buzzPin, LOW);
    digitalWrite(LED2, LOW);
    }
    delay(60);
    }
    //                                      STOP
    if (distance <= 50 && distance >=0) {
    digitalWrite(buzzPin, HIGH);
    digitalWrite(LED3, HIGH);
    } else {
    digitalWrite(buzzPin, LOW);
    digitalWrite(LED3, LOW);
    }
    delay(60);
    }

body:
Try adding in some serial output at important code-parts. If you see that these are getting printed you can be sure that the code gets executed until that point. If it doesn't get executed it could also be a problem with the wiring so be sure to check that everythign is set up properly.

At this part:

    ...
    void loop()
    {
    int duration, distance;
    digitalWrite(trigPin, HIGH);
    delay(1);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    //                                      Go
    distance = (duration/2) / 29.1;
    ...

You are trying to divide an integer (wich can only hold whole numbers) with a real number. Please make sure to use a data type wich can hold more fine-grained results like double or float.

To set up a serial interface you have to add **Serial.begin(9600)** to you code in the setup() function. Then when you write **Serial.println("Your debugging message here")** it should be visible in the serial monitor after compiling. (Arduino IDE->Tools->Serial Monitor)


message:
How to save arduino serial monitor data into excel file

I am looking for the software that can help me to save arduino serial monitor data into excel file. And how to use that with your own code.

body:
Your computer is able to access the serial data and export it to a text file, which can then be converted to an excel file within *Excel > Data > From Text*. However, the data should be formatted in a way that excel can read it by separating values with a delimiter such as `","`.

Once you have done this, simply run your serial data and open up your computer's console and write:
`type COM(# here) >> serialdata.txt`

Finally, import this text file into excel.

You could also use [Excel VBA with MSCOMM][1] to take the serial data directly into excel.

This answer is a regurgitation of a [duplicate question][2] asked earlier.

  [1]: http://www.dailyfreecode.com/Forum/accessing-serial-port-excel-vba-26041.aspx
  [2]: https://arduino.stackexchange.com/questions/47805/how-do-i-import-data-from-serial-monitor-to-excel-document-without-copying-and-p