text:
Ethernet Shield Issue
I just bought a Ethernet Shield for my Arduino UNO. I connected it to my arduino and flashed the Example code for Ethernet Shield, but the code didn't work. The COLL LED on ethernet shield is glowing and I checked with my router, it has not assigned any IP to my ethernet shield. I tried all of the examples given, but none of them worked. Help me in understanding wrong I am doing here?
Ethernet Shield(W5100) Link: https://www.banggood.in/Ethernet-Shield-Module-W5100-Micro-SD-Card-Slot-For-Arduino-UNO-MEGA-p-908461.html?rmmds=search&cur_warehouse=CN
Exampled code given in Arduino (DhcpAddressPrinter):
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};

void setup() {
  // You can use Ethernet.init(pin) to configure the CS pin
  //Ethernet.init(10);  // Most Arduino shields
  //Ethernet.init(5);   // MKR ETH shield
  //Ethernet.init(0);   // Teensy 2.0
  //Ethernet.init(20);  // Teensy++ 2.0
  //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet
  //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    } else if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // no point in carrying on, so do nothing forevermore:
    while (true) {
      delay(1);
    }
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  switch (Ethernet.maintain()) {
    case 1:
      //renewed fail
      Serial.println("Error: renewed fail");
      break;

    case 2:
      //renewed success
      Serial.println("Renewed success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    case 3:
      //rebind fail
      Serial.println("Error: rebind fail");
      break;

    case 4:
      //rebind success
      Serial.println("Rebind success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    default:
      //nothing happened
      break;
  }
}

Output
Initialize Ethernet with DHCP:

Code I wrote for Webserver:
#include<SPI.h>
#include<Ethernet.h>

int led = 8;
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xEF, 0xED};
EthernetServer server(80);
String readString;

void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  Ethernet.begin(mac);
  Serial.print("Server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  EthernetClient client = server.available();

  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.print(c);

        if (readString.length() < 100) {
          readString += c;
        }

        if (c = '\n') {
          Serial.print(readString);
          client.println("<HTTP/1.1 200 0K>");
          client.print("<Connection-Type: text/html>");
          client.println("<Connection: close>");
          client.println("");

          client.println("<!DOCTYPE html>");
          client.println("");
          client.println("");
          client.println("<title>Webserver</title>");
          client.println("");
          client.println("");
          client.println("<button>LED ON</button>");
          client.println("<button>LED OFF</button>");
          client.println("");

          delay(1);
          client.stop();

          if (readString.indexOf("?button1on") > 0) {
            digitalWrite(led, HIGH);
          }

          if (readString.indexOf("?button2off") > 0) {
            digitalWrite(led, LOW);
          }
          readString = "";
        }
      }
    }
  }
}

Output
Server is at 0.0.0.0

Thank You

Also what ethernet shield?

what do the examples print to Serial Monitor?

I have added the code in my question. The ethernet shield I am using is W5100

try this code  https://github.com/esp8266/Arduino/blob/master/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino

Try disabling the SD. Add pinMode(4, OUTPUT); digitalWrite(4, HIGH); to the setup().

@jsotola Thanks for helping. I tried that code, but the serial monitor prints "Failed to configure Ethernet using DHCP"

@MikaelPatel After adding those lines in setup(), the output in Serial monitor is same, "Server is at 0.0.0.0"

do you have the router set up with a whitelist of MAC addresses? .... also, you could try using a static IP

@darkpanda Did you put the code first in setup()?

@MikaelPatel yes


text:
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!

measure the voltage while the Arduino is connected

your question is not about the Arduino ... your question is about how to determine if a battery is in good condition .... voting to close

@jsotola  I updated my question after further tests. Now please help.

a fan is not a voltmeter ... as i asked before, what is the battery voltage when the arduino is connected to the battery? ... also, what is the power adapter voltage when the arduino is connected to the power adapter?

I have re-opened the question as it mentions Arduino 5 times and thus is hardly not about Arduinos.

@NickGammon  Thank You So Much for opening my question again and Supporting me.     People like you are so much needed in stack exchange communities. ❤

The input voltage on the DC pin is specified as 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 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).

I was thinking the same - I had this exact problem about a year ago with a solar powered setup. Droped the input voltage to 10V and no problemo!

Thank You So Much for your answer. I've read the Wikipedia article of the Buck Converter and I believe it will work in my case also, as you have already explained me. I have ordered a buck converter online. I'll update you as soon as it arrives and I use it in my project. Thanks Again. ❤

@Bevan Thanks for mentioning about your case. It strengthened my will to modify my current settings as told by Nick  and not leave it. Otherwise I was thinking of changing the battery  or the board

@Bevan One more help will be appreciated from your side. People have downvoted my post considering it as an off-topic post. It would be very great if you upvote it because it has resulted the decrease in my community reputation .

@Nick Gammon   sorry for the delayed update. My package with the buck converter just arrived today. I have installed it and it is working like butter. Thank You

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


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

sensors don't output HIGH or LOW, their output is numbers...

revert your code to where it worked and start rewriting the code again

The issue is that I can't revert back to my old code so I need to rewrite.

Also, even if I use 1 or 0 I have the same issue

What is your "sound sensor"?

Im sorry about all the confusion, I just read up on how it works and apparently it outputs low when it senses a sound, weird because it was working before when I was checking for a HIGH input. Anyways my problem's solved thank you for the suggestions.

one thing that may help you in future code writing ... treat my sound sensor as if it's always HIGH .... this is absolutely not true ..... it is just that your code does not do anything when the sensor is LOW

@jsotola Not really. It toggles the LED when the sensor is reads HIGH, with a delay of 100 ms between each toggle. When the sensor does not read HIGH it doesn't toggle the LED. Thus it does something different when the sensor is HIGH compared to LOW.

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.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to connect ESP8266 to my home WiFi securely
I'm working on a home automation project using NodeMCU ESP8266. Most of the example projects I see online provide their WiFi SSID and password in plain text at the beginning of the code by storing them into some variable
Is there a secure way of doing that? I'm worried if my ESP8266 gets hacked by someone online, they'll now have my WiFi SSID and the password. Is there a way of encrypting this information before passing it to ESP8266. Or is there a way of creating a separate WiFi password which will only be used by the ESP8266?

this may help https://www.esp8266.com/viewtopic.php?t=13977

If the credentials are hardcoded the attacker will have to read out the flash through the internet (which is almost impossible, I guess). Even after that s(he) has to be at your home to login to your wifi, which is very unlikely as long as you are not a person of interest. Providing an interface to the credentials might be more vulnerable than hardcoding them. By the way, the esp supports flash encryption.

An interesting question. This is not a forum - just a comment section.  But consider that this information is only valuable in close proximity to your house as most wifi is not long range.  And if this really was a risk there are other barriers you can put up like MAC filter on your router.  So why is this a concern?  (BTW, don't use the same password for your router's admin and your router's SSID!)


text:
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.

you cannot do that without hardware ... and all hardware is not the same ... so i think that you forgot include all of the information

you avoided a downvote from me because you explained the desired functionality very clearly ... you can use that clear description and turn it into code ... simple loop with an incrementing pointer and a 2 second delay ... 2 minute 58 seconds delay after loop finishes ... then all off and back to begining

turning a relay on is no different than turning on an LED, so start writing the code. functions you gonna need mainly is delay(), pinMode() and digitalWrite(). after finishing the prototype using LEDs replace the LEDs with a NPN transistors like a 2N2222 to turn on relays. don't connect relays directly to arduino...

What have you tried so far?

@newbie, NO, not delay(). That is a dead-end. You, and the OP, need to search on "blink without delay explained" and read the resulting article.

@DuncanC yes delay() is a "code-blocking" function but easier to use than millis() that's why i suggested delay() function...

delay() is easier to use for dirt-simple sample code. The minute you go beyond the absolute simplest goal, it becomes a blocker that prevents you from accomplishing your task and you have to rip out the delay-based code, go study the "BlinkWithoutDelay" example, and learn how to use millis() to do cooperative multi-tasking. Except in VERY limited circumstances delay() is a dead end that teaches bad habits.

Once my DuPont cables arrive I can connect the relay module to the Arduino. I should have mentioned about the relays earlier. I’m obviously new at this where as you guys have been around the block a few times. I’m pretty sure that once I go through your suggestions I can come up with a plan. Thanks

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, or better yet this 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" which will likely fry your transistors (and possibly the Arduino)

I particularly liked the fact that you did not provide a complete working solution, but rather pointers for the OP to write his own code.. +1

Yup. I don't like to provide code to beginners. I think it's counter-productive. More often than not they copy/paste it into their program, complain if there are minor compile errors, and don't really gain any understanding. By outlining a solution and supporting the OP they actually learn.

While I agree you shouldn't give a complete working solution; I do think this source (https://www.forward.com.au/pfod/ArduinoProgramming/TimingDelaysInArduino.html) will help to atleast get an understanding of the possible implementation.

Simple code:
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.

The Arduino will not sense your button presses because, most of the time, it will be busy delaying when you press the button.

There is no requirement to do anything else after the start button is pressed, so a dumb delay in this instance will provide the control needed.  In general, blink without delay style timing would be better.

Sorry, my comment was wrong: I was mislead by your poor indentation (and missing braces) and didn't notice the delay() was within the if. I fixed your code formatting to make the intent clearer.

This code will miss button presses most of the time while running a relay sequence because it will spend the vast majority of its time in one of the 2 delay statements. A reset button wouldn't work very well, and would not stop the 3 minute period while all the relays are active (unless you press the hardware reset button and reboot the Arduino.)

Is there any requirement to do anything else for (2 seconds * 12) + 3 minutes?  No. So let the delay whining go already.

I'm not whining. I'm pointing out a severe limitation of the approach you are suggesting. I've been bitten several times by writing some Arduino code where I think "it doesn't matter, I don't need to handle more than one thing at a time - delay() is fine!" and then expanded my project to the point where using delay() is a total blocker for what I need to do next, and then had to go back and rewrite substantial chunks of code with very different logic.

It's a bad habit to use that approach because it only works in the most trivial of cases, and if you start out with delay() and move beyond the trivial to doing anything of any complexity, you have to throw out your delay-based code and rewrite it. The logic flow of using millis() is different, so it can be a painful rewrite. I speak from experience.


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

I have connected pin 3 to a DC motor and using analogWrite and DigitalWrite to try making it start. However, nothing happens.
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.
Here is a link to the tutorial and software.

Thanks for any help!

There is a big PDF tutorial that goes with this kit. Did you download it? Did you read the chapter on controlling a motor?

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.

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.

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.


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

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

what is abnormal behavior   ... that description has meaning only to you

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

Likely this is because of switch bounce.  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.  Or in hardware by using capacitors to filter out bouncing.

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.


text:
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.

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.

Thank you. I will do it using this method this time but is there any way I could do stereo and/or 50KHz +? Just curious.

@A.Shetye: For stereo, you could add something like ADMUX ^= _BV(MUX0); to the ISR in order to alternate between the A0 and A1 inputs, but then the per-channel sampling rate would be half as fast. For faster sampling, you could set the prescaler to 16 and get 76.9 kHz mono or half that in stereo, but I do not guarantee the Arduino will keep up with the processing load. A prescaler lower than 16 will likely give very noisy readings.

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


text:
TM1637Display is not updating on loop
Alright so I've been trying to update/change the number on the display during a loop, but nothing really happens. It doesnt change/update, the value is always exactly same.
#include <TM1637Display.h>

#define led_display 1
#define led_display_scnd 3

int analogPin = A0;
int moisture;
int percentage;

int map_low = 686;
int map_high = 350;

TM1637Display display(led_display_scnd, led_display);

void setup() {
  pinMode (led_display, OUTPUT);
  display.setBrightness(1);

  display.showNumberDec(1);
  digitalWrite(led_display, HIGH);
  Serial.begin(9600);

}

void loop() {
  display.showNumberDec(5);
  moisture = analogRead(analogPin);
  Serial.print("Raw: ");
  Serial.print(moisture);

  int sensorValue = analogRead(A0);
  percentage = 100-((sensorValue-110)*100L/(1023-110));

  Serial.print(" | Percentage: ");
  Serial.print(percentage);
  Serial.println("%");

  display.showNumberDec(moisture); // updating the value

  delay(2000);
}

Does the value of "Raw:" change on the terminal? That's the number you are trying to display.

Yeah it does. Here an example from whats In terminal
18:39:41.242 -> Raw: 1018 | Percentage: 1%
18:39:43.294 -> Raw: 956 | Percentage: 8%
18:39:45.353 -> Raw: 955 | Percentage: 8%

That leaves a compiler bug that affects either the library or your call to it, a bug in the library (such as its I2C implementation), or your wiring to the pins being used by the library for I2C (from least likely to most likely, if I had to guess). Double check your wiring against the pins you chose for the display. Also it looks like one of those pins is pin-1, which is the hardware UART's serial transmitter. Try a another pin for the display; you may just be trying to back-drive the UART.


text:
L298N beeps and malfunctions when receiving certain analogWrite values

I created a simple circuit with an UNO, L298N and a single motor.
Wrote the following code to test controlling the speed of the motor.
Tested motor with digitalWrite() function and it works fine.
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);
}

The LN298N should not beep and should not be able to. Might it be the motor, who is beeping? That the motor is not moving below 71 can be because the friction is too big for the motor to move

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.

Awesome info! Thank you. The friction problem makes perfect sense (motors are powered by a 7.5V external source). I got used to Lego Mindstorms motors that can turn really slowly. I shall adjust my expectations for now and look into alternative configurations in the future. I did read that the L258N is ancient technology, but by then I had committed my project! Thank you!


text:
Burn bootloader into Arduino UNO from Arduino Duemilanove
I have been working with my Arduino UNO for 2-3 hours and after that it was not possible to load sketchs into the board since it returns a

"avrdude: stk500_recv(): programmer is not responding" error.

The internal led "L" of the board is permanently on.

After a little research I guess that the bootloader was corrupted at some point (I still don't understand when and how).
Q: Apart from this board I have an Arduino Duemilanove board and I would like to know if it is possible to use this Duemilanove board to burn the bootloader in the broken board, is this possible? in afirmative case, how?
Since all the examples over there shows how to do it with the same board and not with a different one.

https://www.arduino.cc/en/Tutorial/ArduinoISP

Yes, Nick Gammon has a page on doing that here  https://www.gammon.com.au/bootloader

Hey, a big ___ ____ to whomever downvoted this with no comment.  Nick has a great page written up, answers the question very directly, and has been in place for several years.


text:
Arduino due erase button and power switching
Last days I have been investigatin schematics of arduino due board. The purpose of proper understanding of schematics in crucial for me, beacuse I indend to build myself my own board with some minor modifications.
I would really want to learn something from it and not just blindly copy stuff that are already done. In schematics there are two things that I do not understand. First is the working principle of erase button (see: erase button). I have my own idea how does it work, but would like to clarify the working principle from someone that know exactly what is the purpose of all the elements that are connected to erase button. Also, why is ERASE_CMD  line connected to Atmega processor?
 Second thing is switching of power supply between external power and both usbs (see: usb switch). Again, would someone please just brifly describe working principle? Here I really do not undertand why is there op amp added?
Thank you in advance.
Erase button:

USB switch:

PLEASE NOTE: Both pictures are taken from original arduino webpage: https://store.arduino.cc/due  (see: documentation -> schematics)

The asker posted the same question and received an answer here
There is discussion regarding the purpose of the Erase switch here

You're encouraged to summarize the essentials such that the answer will remain useful if the links become broken.


text:
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: 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.

I would double check the wiring.  The motor controller is pretty tough.  Most likely you would know if you blew it up.  Is there a drive enable light on the motor shield?  Does it come on?  If not, try replacing with motor drive with an LED or measure the pin with a meter.

I have tripled checked the wiring, it is all good as you can see in the picture. About the drive enable light, I see a "power" led that does light up when the AA batteries are connected to it. Other than that, I do not see one. For measuring the pin, do you mean measure m2 on the shield? If so, I have tried that but my multimeter reads 0 when set to 20 volts DC. Partially why I think it is broken, but I never seen any smoke or anything to really tell me that I 'blew it up.'

I just added 2 more pictures to the end, via the site I gave. These show it plugged in as well as a close up while plugged in.

I haven't used this board but it does look pretty nice.  I found tech info on it here it uses a couple of 6612 dual h-bridges.  It looks like each motor uses a PWM (speed) signal and two directional control signals which look generated on board and controlled over SPI

This AF Documentation uses different commands.

So what you said actually made it work, so my problem was the wrong library and wrong code, the code I used was for the old library. I see that the code uses OOP programming now, so I am assuming I need to create a new object for each motor right? Anyways, I would like to give you the credit since even jDAQ said it was noted by you. So give an answer and I can give you the check mark.

Oh, I see with the documentation, it just said I can give it another name and initialize it with a different motor, so I don't need to create an entirely new object.

The commands you are using don't match the ones listed for this board.  Here is the AF Documentation 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.

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

So yes a new library and different code did the trick. It now works, however, I want to give the right person credit here which you said "as noted by markshancock" so I will give him the credit if he posts an answer, if not then I will give you the thumbs up and check mark. I do see that this new code uses OOP so I assume I have to create a new object for each motor?

Oh, I see with the documentation, it just said I can give it another name and initialize it with a different motor, so I don't need to create an entirely new object.

Thanks @BobG.
Glad to hear that was the issue.  I added an answer as you requested :)


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

It looks like ISR is being fired only once. bummer.

I think it would be better to use a library that support PCINT interrupts instead of hacking it onto a library that doesn't. For example, https://github.com/kr4fty/EncoderPCI looks like it supports PCINT.

Related: 3 ways to ensure atomic access  on Arduino/AVR microcontrollers: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why/39693278#39693278

@kotique, you have unmanaged race conditions in your code. I've addressed them and given a thorough explanation here: https://arduino.stackexchange.com/a/77512/7727. I can't say those are the only problems, but you definitely have race conditions. Making the volatile variable an int8_t won't fix them, they are still there. Give it a shot with my corrections I describe in my action and see what happens now.

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.

Sounds like a dodgy library, if it interferes with C++ code. It perhaps is meddling with registers without telling the compiler.

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.

Or use a int8_t if that’s possible.

You should've read till the end of the question, which states "Switching from int to byte doesn't change anything."

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

Force atomicity in loop() by backing up the interrupt state.
Make copies of the volatile variables.
Then restore the global interrupt state.
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:

My own race condition problem: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why
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

I agree about making the copy (as in your example using pos_copy) however for a one-byte variable you wouldn't need to disable interrupts, as copying from one byte to the "copy" would be atomic. However it could be a subtle bug-in-waiting if someone one day decides to make pos two bytes without realizing why you had not put the atomic access guard there. Perhaps a comment would help in that case.

In your example, the delay(100) wouldn't work if interrupts were off so perhaps saving and restoring SREG is overkill. You could just turn interrupts back on. If they somehow get turned off elsewhere then the delay will fail, and you would need to address that.

You are right on the 2nd comment, but I think it's just a best practice sort of thing, since frequently I wrap this stuff up into functions which I intend to be called in or out of ISRs.

Regarding your 1st comment: however for a one-byte variable you wouldn't need to disable interrupts, as copying from one byte to the "copy" would be atomic., I agree with you on this point: as copying from one byte to the "copy" would be atomic., but disagree with you on this: for a one-byte variable you wouldn't need to disable interrupts, because what needs to be atomic is from the if statement down through the serial print, inclusive. That whole block needs to be atomic, or else you evaluate the if statement on one variable state but do something with it (and print it) on another.

In other words, the atomic access guards for the 1-byte variable are still required to ensure that what you are using inside the if block is also what you used to decide to enter the if block in the first place, no?

@NickGammon, I'm interested in your response to my last two comments here if you get a chance.

Yes, but, what can you do? If you make it guarded, it still might change, but you won't realize it. Making a copy, and comparing to another byte, is the best you can do. That whole block needs to be atomic, or else you evaluate the if statement on one variable state but do something with it (and print it) on another. - not at all. You are evaluating the copy, and printing the copy.

@NickGammon, your response here indicates we are actually agreeing and saying the same thing & just not realizing it. not at all. You are evaluating the copy, and printing the copy. What I am saying is that making the copy is the adding of atomic access guards around that whole block. We are agreeing.I realize we are agreeing on the 1-byte variable thing too. I'm saying his original code will not work even if he uses a 1-byte variable. I thought you disagreed with me, but you disagreed with something else. I'll update my answer to make what I'm saying more clear.I'm pretty sure we agree.

Answer updated. This answer is ridiculously thorough for this question. I think I should move it to a wiki style question someday, where I both ask the question and provide the answer. This topic of race conditions and atomic access and stuff comes up all the time and needs a thorough, canonical answer like this to address it and to which we can point people whenever they have a question or problem which requires it, and that's what I've tried to make this answer.


text:
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 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, attached it's a snapshot of it.

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)

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

That transistor is too small. The 3.6 Watt could be the average power usage. Do you have details of that pump? What is the maximum current? Use a darlington transistor that can drive a few amps or a mosfet.

@Jot I used this one. They say it is a 4.2W pump on the website, but on the pump is written 3.6W. Do you think a TIP120 will work ok?

It says "Max rated current: 350mA", so the PN2222A should be able to do that. Perhaps that information is not reliable or perhaps it has a peak current when it starts. The TIP120 is okay, you can use a resistor from the base to pin 9 of 1k, but you can also try with the 220 ohm.

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 you suggested and looks like when the same problem with the power happens, nothing is burning out :)

I am not an electronics expert, but I too tried controlling a 12v circuit from arduino my first attempts were with transistors and always had problems with either switching on or switching off (depending upon the actual transistor).  Eventually I discovered MOSFETs and my project has been working perfectly ever since (continuous 24x7 for over 1 year). Wouldn't a MOSFET be better for this?

Mosfets are better. The TIP120 is very old, but easy to use. When it turns on with a constant large current, then it will become hot. A good mosfet stays cool.

Note: P2N2222A seems to have a different pinout to PN2222A.

@AlexBuicescu Please remove Edit2 from your post and instead add it as one of the answers.

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)

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

PN2222A

Thanks for the quick response @markshancock, but I think I did use the correct pinout (unlike tinkercad). I edited the post with a photo my partial breadboard.

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

Yes, the TIP120 fixed the problem. The pn2222a was doing a great job while the arduino was powered on (it could keep the pump turned on for more than 20-30 seconds without issue), but when the arduino got shut off, the pump turned on and the transistor burned out after 4-5 seconds

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.

simulate this circuit – Schematic created using CircuitLab

Hi, I edited the post with more information about my pinout (also see the comment to @markshancock answer)

Note: P2N2222A seems to have a different pinout to PN2222A.

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.

These aren't the values I have seen on their datasheet in the past. Eg. this one from OnSemi. Can you link to a datasheet that backs up your values?

I pulled the data from the Mouser link in the answer from jDAQ, http://www.mouser.com/ds/2/149/PN2222A-371983.pdf  See Page 3 and Note 4.  Also the discussion of how it takes 50mA Ib to allow 500mA Ic, which an Arduino can't supply directly without damaging an I/O pin.  The OnSemi datasheet has a similar note "* Pulse Test: Pulse Width≤300µs, Duty Cycle≤2%" for "IC=500mA, IB=50mA ".

Thanks. You should note in your answer that that is for an Ib of 15mA. Two transistors in a Darlington pair would do the job

I think I'd have suggested a low Rds P-channel MOSFET instead, or an even lower Rds N-channel MOSFET to sink current thru the motor vs sourcing to it, but that was not the question asked.

I totally agree. Perhaps that should be (a separate) answer (ie. the transistor can't provide the power needed given the current the Arduino can supply to the base, use a MOSFET instead).


text:
Faster Arduino Mega
I am using Arduino Mega 2560 for interfacing devices such as the Maxim MAX22500E and TI ADS1241.
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 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?

There are "unofficial" Arduino ports to the popular STM32 micro controllers, which feature 5V tolerant pins (but can't output 5V). Apart from that, Majenko is right, 5V is hardly needed anymore - otherwise, there wouldn't be so many 3.3V-controllers!

"... Arduino Due (84 MHz Clock) which is enough faster than the Arduino Mega (16MHz Clock) ..." - Note that you can't just compare clock speeds across vastly different processors like that. The Mega has an 8-bit AVR microcontroller, the Due has a 32-bit ARM core. In this case, it's likely the speed difference is larger than the clock speed difference suggests, but in general that's not an assumption you can make.

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.

Thanks. That was the kind of guidance i was needing... I will go fully into 3.3V...


text:
Arduino Due ADXL345 Interference
I am working with an Arduino Due and the Analog ADXL345 through a module following this tutorial, with the wire.h library at Fast Speed (400kHz), the Accelerometer Sampling at 800Hz (for the Maximum Reccomended Limit), and the Serial Monitor at 115200 bps.
The cable is 24AWG solid wire, 6in length, two pairs, for 3.3V, GND, SCL and SDA pins.
When the accelerometer is starting up, it generates a high pitched noise is generated!. Possibly by the 5V-3.3V regulator or by the accelerometer itself.
Under 400kHz|800Hz, the readings are unstable: by simply touching some open terminals in the Due, the Accelerometers readings toggle between strong oscillations and the correct ones (Figure 1).

After some "taps", the oscillations stops and the proper measures can be captured at the expected sampling rate (Figure 2). Note the mean values are modified for plotting only.

What should I do to prevent such behavior?, and what is causing that, considering the device is indeed working at the expected speed?

Please add the wiring of the module and information about cable length, type, etc. The wires should be as short as possible and there should be common ground.

I edited the question with the tutorial  followed, 15cm length cable, 24 AWG solid wire.


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

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

What kind of power supply do you use? Does it work with other sources (e.g. USB ports)? Can you hook up an oscilloscope to the crystal pins?

@Erlkoenig Same happens when powered with the 5V arduino power supply.

@Erlkoenig Which pins are the crystal pins?

Just to eliminate a possibility, Do you have another computer you can try it with?

@GMc I don't have any other computer, but as I have already mentioned I tried the same sketch with another nano and it worked

Sorry I missed that. FWIW, The crystal is (most likely) the little silver box next to the CPU chip. It will (most likely) have something like 16.0MHz engraved on it. Here is a link that includes a photo showing where the crystal is (scroll down a bit) http://www.circuitstoday.com/arduino-nano-tutorial-pinout-schematics

You can look up the MCU's data sheet and look for the "XTAL" pins, which are probably easier to contact than the crystal pins themselves. While you're at it, also check the voltage supply and reset input with the oscilloscope...

I don't have any oscilloscope

did you solder the headers?

@Juraj Yeah, I soldered them.

check the soldering for shorts

Nope, Its perfectly soldered

@Juraj Check the update

you have some week solder connection between reset and ground pin. it pulls the reset down holding the MCU in reset.

So should I resolder?

take a magnifying glass and check it. maybe it only needs a little cleaning. check both reset pins

and check the ICSP header too

@Juraj I resoldered and cleaned it. It worked constantly for like a min but its now in the same state again.

Let us continue this discussion in chat.

Check the soldering on the SMD resistors. It could be that the pullup on RESET is not connected properly.

@Majenko Not sure but all smd resistors seem to be good

Here is a video https://youtu.be/MMiZEQKPJMM

why only use external power without going through USBport as data input

@abu-ahmedal-khatiri I tried with usb port too

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

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.

But wasn't the arduino supposed to work with the old loaded sketch with external power provided?

Yes it should be work using 3v or 5v, same to me, based your error message, you can try my way cause the nano have auto-reset of the arduino-nightly.

Did you try to change in the Tools menu from Atmega328P(OldBootloader) to Atmega328P #NewBootloader. See at Detecting... section and Compiling... are difference using of fqdn.

I have almost tried everything. I will try your way later

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.

Your answer doesn't actually explain too much.  Can you provide detail about it?

Reset pin without a pullup resistor can float, leading to odd results as the Nano can reset intermittently. The resistor keeps that from happening.  I don't see on in the picture presented.

What if it has on the underneath? Can you please show me through pictures cause its hard for me to understand.

Sure - post pictures of the top and bottom of Your card - I don't have one of those myself.


text:
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);
}

btw: for a C string (char array terminated with 0), the write function is same as print()

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

Ok thats great it trys to combined them but comes up with the following error                                 warning: invalid conversion from 'uint8_t {aka unsigned char}' to 'const char*' [-fpermissive]
const char* eTest1 = EEPROM.read(1);
^

@Rickstar I made a better implementation, since EEPROM.read always returns exactly one byte (character).

@Rickstar EEPROM.read() returns one byte, not a pointer to string.

Thanks @MichelKeijzers

You're welcome.


text:
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.

Is it a genuine Arduino or a cheap Chinese clone?

Its an Elegoo but I have used them for years without issue. To be fair this is the first time I have powered them from a motor shield though.

@Majenko This is part of an open source project to make getting into digital train sets as cheap as possible so we are trying to keep costs down hence the clone. If it does turn out that the official board would be a better choice though it would be good to know.

It could be that the voltage regulator on the clone is inferior and died allowing 12V through to the rest of the Arduino and hence your computer.

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

Do you agree that by cutting the Vin trace on the motor shield there will no longer be a risk to my computer?

Sounds likely, yes.

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.


text:
How to enable auto reset in Arduino Leonardo?
I am  trying to program an ATMega32u4 microcontroller through arduino IDE. I have added external oscillator(16Mhz) and capacitors and few other connections according to the Schematic. I had put a sparkfun bootloader onto it(caterina) using Avr Pocket Programmer. A usb 2.0 is connected to the microcontroller. Arduino IDE recognizes microcontroller as Arduino Leonardo with the help of this usb. Bootloader file.
I was able to upload codes into the microcontroller but the issue is, I have to put the reset pin to ground momentarily each time when the IDE goes to uploading stage.
If i do not reset it, the COM Port for leonardo disappears but it never comes back until I reset it manually and therefore the uploading bar just gets stuck. I have also added the circuit connected to the Reset Pin according to the schematic but even if i remove all of it and just connect a switch, no difference can be observed. No power on reset is working.
Since one can upload codes without having to manually reset each time in Arduino Leonardo, I was wondering what could be the issue here.
Is there a way to auto reset this? Or perhaps fix the auto reset issue in this case?

how is it done on rhe Leonardo?

How is what done on the leonardo? I'm sorry, I didn't get your question.

did you look at the Leonardo schematic?

Yes, I did. Also rigged the circuit connected to the reset pin but it doesn't seem to be working. Any idea what could be wrong?

The leonardo should reset if you open the serial port at 1200 baud then close it again. If there is no serial port showing then your sketch isn't creating one, or your sketch isn't running properly.

Yes, I did try that and it works. However, I would need to do that while uploading the code quickly, else the code won't upload. Again, it's not exactly an automated thing.


text:
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();
}}
}

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.

Thank you for the advice, but I don't know what you mean by "leave 143 alone."How do I make the 143 LED leave alone with the code?

@bopole 143: the number of bytes for one ledstrep that you do NOT want to change (48 leds * 3 bytes/strip = 144 bytes, 1 you want to change, the others  (143) not).

Say you had just 1 LED. Now you want to change 1 LED, and leave the other 2 as is. You have to send the 1 new value, and resend the 2 unchanged values. That's the way a chip like WS2812B  and others used in addressable strips work.  Expand to 48 LEDs. One byte changes, you send that new value and resend the unchanged values for everything else.

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