text:
What's wrong with infinite loops inside loop()?
I wanted to run the following code as something similar to Tone or pwm. However for some reason that I am unable to seek it doesn't work.
#define WAIT 3200UL

void setup() {
  DDRB |= B00000001;  // set pin8 as output
}

void loop() {
  unsigned long t;
  while (1) {

    PORTB &= B11111110; // clear pin 8

    for (t = 0 ; t < WAIT; t++);

    PORTB |= B00000001; // set pin 8

    for (t = 0; t < WAIT; t++);

    //            PORTB &= B11111110;
    //            delayMicroseconds(WAIT);
    //            PORTB |= B00000001;
    //            delayMicroseconds(WAIT);

  }
}

the code is pretty simple, just toggling a pin. If I use the commented section, it works fine but as is, it doesn't work.
I removed the "while(1)" statement since it was unnecessary for now, it started to work improperly, (changing the WAIT didn't have any effect and I'm not sure I'm getting a full swing).
Pin 8 is connected to an LED + R to ground and a piezzo in parallel to them. the LED seems to be steady on yet the buzzer makes a low noise. I measured a   voltage of 3.8v DC and arround 9v AC on the pin, other pins I ran the code for were similar.
As another attempt I put a Serial.print in the beginning of the while(1) but it printed out only once.
Also looked at the assembly code generated for a clue to find out what does delayMicroseconds() do but couldn't figure out what's wrong.
Appreciate your help.

Answering your title - there's nothing wrong with an infinite loop within loop, but it's not necessary as loop itself is an infinite loop. Move unsigned long t; into setup and you will have an infinite loop without needing to explicitly code the while(1).

First, I will give you some unsolicited advise about your coding style.
Instead of writing:
PORTB &= B11111110;
...
PORTB |= B00000001;

you could write:
PORTB &= ~_BV(PB0);
...
PORTB |= _BV(PB0);

These are standard AVR idioms, and they make it clearer that you are
toggling the pin PB0.
Then, to answer your actual question, your delay loop does not work
because it got optimized-out by the compiler. This has already been said
in Michel Keijzers' answer, but let me elaborate.
All modern compilers are optimizing compilers. This means they can
change your code in whatever way they see fit, as long as the visible
effects remain the same. The effects considered visible are usually
I/O and access to variables declared volatile. Quite importantly, the
slowness of the program is not considered a visible effect for the
purpose of optimization. And if you think about it, it makes good sense:
if the slowness of the program were to be preserved, then any form of
optimization would be impossible. Thus, a loop that has no effect other
than slowing your program down can legitimately be optimized-out.
The solution to your problem is quite simple: if you want a delay, then
call delayMicroseconds(). Or maybe even delay() if you are OK with
its low resolution. On the other hand, if you need sub-microsecond
resolution, you can call _delay_us(), from the avr-libc. This function
(or rather, macro) provides single-cycle resolution. If you write
#include <util/delay.h>

...
_delay_us(1.375);

you get exactly what you ask for, i.e. a delay of 22 CPU cycles
(on an Arduino Uno clocked at 16 MHz). The issues with this
function are that it is AVR-specific, and its argument must be a
compile-time constant.
It has been suggested to you to write your delay loop using a volatile
loop counter. I strongly advise you against doing that, for three
reasons:

Doing so will force the counter to be allocated to RAM, thus
consuming a scarce and valuable resource for no good reason.
Incrementing a RAM-based 32-bit counter takes 20 CPU cycles. Add
to this the time required to test the end-of-loop condition and you
will realize that your delay resolution is way worse than that of
delayMicroseconds().
Your actual delay will depend on the clock frequency, and probably
also on the compiler's version, making your code pretty fragile.

Upvoted for the (much extra) explanation

Re, "effects considered visible are usually I/O and..."  There is no I/O in the C++ programming language.  The effects that are considered visible are calls to functions with external linkage, and access to volatile functions.  When a C++ program does something like std::cout<<"hello world!\n";, that's a call to an external library function.

static loop counter should work just as good in this particular case, saving some of the load/store instructions.

@jameslarge: Recent versions of the Arduino IDE pass the -flto option to the compiler, which triggers full-program link-time optimization. In this case, external linkage is irrelevant, and calls to external functions can be optimized out (yes, I tried).

@wondra: I tried with a static counter, both a global static and a local static. In both cases the loop got optimized-out, although the counter did get written with its end-of-loop value.

@EdgarBonet work for me using VisualStudio, seems that such construct mgiht be even more dangerous than initially expected. Another reason to use the delay from avr lib.

Oops!  I meant, ...access to volatile variables.

First
t = WAIT;
for (t = 0; t < WAIT; t++);

The first statement is not useful, since t will be assigned to 0 in the for loop.
However, since t is not used, probably it is optimized and removed by the compiler, meaning it will not perform a delay.
You should make t volatile. This prevents the compiler from optimizing it (out).
The only difference with or without the infinite loop is that variable t does not need to be allocated for (and keeps its value from the previous loop), but since the value is overwritten it does not make a difference.

Even t is marked volatile, the loop will execute that quickly you won't even see it flickering.

increasing the WAIT value might help ... not sure how many clock cycle are used. I would say 16 MHz / number of clock cycle for one iteration handling.

And a useful device to analyze this is a logic analyzer, you can buy it for 5 euro from China and is easier to use for low signal checking than a (cheap) oscilloscope.

Correct me if I am wrong, but t is used(read) in the t < WAIT expression and both written&read in the t++ expression. The fact that the statement of the for cycle is empty might make it target to compiler optimization for another reason, but it does not appear to me that t is unused.

it is not used afterwards and has no side effects, so the compiler can optimize it away.

Incrementing, comparing and jump is just a single digit of instructions. At max (65535) this is around 600000 tics, so 600000/16000000 = 37ms. So it SHOULD be a noticable flickering.

@Kwasmich why is 65535 the same as 600000  tics and not 65535 tics? Than it would be 3,7 ms and because in the example 32000 is used it would be appr. 2 ms or less which is probably unnoticable.

65535 loop iterations times single digit count of ticks (10 or less) is roughly 600000 (rounded for convinience), yes, 3200 is a pretty low delay.

I commented out the t=wait which was silly and  was left from a while(t--) ; structure but it's still the same, also I already had tried many different values to fall in a sensible range but still doesn't work. I guess the problem is somewhere else.

Check the time before/after a loop and see if it is optimized out (you can even put an extra for loop to check longer times).

@MichelKeijzers OK thanks! defining t as volatile solved the problem. but I'm still in doubt like the comment by @wondra  so I wrote it as for(t = 0; t < WAIT;) t++; but still the compiler ignore it unless defined as volatile. what exactly is using afterwards as @kwasmich also mentioned?

Probably what he meant is (and I put in my answer), is that when using volatile, you prevent the compiler to ignore the for statement. That is why it works with volatile and not works without volatile.

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


text:
UART communication, is it possible to use only the TX line?
I am trying to connect an ESP-01 with an ArduinoMega through the serial port of both, as they use different voltage levels I would need a voltage divider between the TX pin of the Mega (pin 1) and the pin RX of the ESP-01 (pin 4) , it is not difficult to do, but I just need to "send data" from ESP-01 to Mega, then I have a question and it is as follows:
If I just need to send data from one device to the other, could I just connect the TX pin of the ESP-01 to the RX of the Mega? If I do so, will I receive data in the Mega?
Greetings

Did you try it?

I tried using an FTDItoUSB for the ESP-01, it didn't work for me...the answer that give me back (Arduino IDE and PuTTY) is: "Unable to open PORT4. PORT4 is in use".

OS reporting that the port in use, has nothing to do with what is actually connected to RX and TX pins.

A PC operating system complaint that a port is in use would have nothing to do with the question you posted, but merely be an incidental problem in the course of usage.  Try closing any programs that might use serial communication, including the arduino IDE, serial monitor, tools like putty, defunct instances of avrdude, etc.

I tried restarting the PC (in this scenarios I use Windows) for any rare program, then I tried again using the same configuration, the same result.

the esp-01 will not blow if you connect 5 V logic to it. the io pins are 5 V tolerant. maybe not for long term, but sure for some tests. has this esp-01 some bigger value for you, that you are so cautious?

Yeap, I'm in Cuba and this pieces of technology from "outter space" are veryyyyy difficult to have. If some day you came here, let me know :)

It works! Just (in my case) the TX pin from the ESP goes to the TX pin from the Mega, I don't know why, but work in this way.

Yes.
You can connect only the the line with which the ESP-01 transmits to the Arduino's receiver, and accomplish one-way data transfer.
However, the ESP will have to be willing to transmit without prompting, and you will not be able to use the Arduino to setup or configure it.  Further, you will not be able to use any in-band signalling to ask the ESP to refrain from sending, so you will have to be sure that your Arduino sketch is generally ready to claim any input which may arrive, and that if there are periods when it is not, the behind-the-scenes serial buffer is large enough.
There's also the question if it is safe to connect the ESP transmit pin directly to the Arduino receive.  In the intended direction of operation, it is.  But should you ever load code on the Arduino which uses that pin as a GPIO output, there is some risk of damage to the ESP.  It's up to you to decide if careful usage will be enough to prevent that; if not, you may want to try something like a 1K series resistor and a schottky diode to clamp the line to the ESP's 3.3v supply, in a way that diverts the current from any accidental 5v output around any internal protection diode that may have more limited power handling.

Thanks for the quick answer and for the recommendations! You just give the tips that I was looking for! I just want to connect my phone to the ESP, open any browser and send some data (a color code, wich is just hexadecimal codes), the ESP recieve that data and send to the Mega, the Mega then will select from the hexa-code the color to set to some leds (50 leds from WS2812B led strip). Do you think the serial buffer from the Mega can hold this? And all this for don't put just to resistences!!! :-)

If you don't hammer it with constant requests, yes.  Do note that receiving multi-character strings can take a little care - you might consider adding a terminating newline as a definitive end marker, and then using line-oriented input.

Sorry for for the unknow but: what do you mean when you say: "terminating newline" and "line-oriented input".

Essentially it means typing a value and then hitting the return key, or having a program do so.  This is more deterministic than sending a value and having the Arduino merely wait until it decides you are not going to type any more digits.   You could rig this up with Serial.readBytesUntil() and atoi() but it will require some work.  Unfortunately, the built-in turnkey methods like Serial.parseInt() use the less reliable timeout approach.  Still many seem to manage using those.  You can also see if sending a newline helps parseInt() finish more promptly.

Ok, I got what you say...is like have the Mega waiting for the character "\n", meaning a new line, and then download all you have in the bus of the serial to a variable. Is that what you want to say? Another question come to me: can I use RegularExpresions (regex) in the Mega?

There are no doubt libraries for regular expression that you can use and at the scale you want to use they would likely be workable, but it might be preferable to avoid the need for such heavy string processing on the little tiny Arduino.   Can you clean up the data on the ESP side (or even at the network source) and only send the more Arduino a clean command, like "123\n" ?

Yeap I think that you're rigth, thanks for the directions you gave to me!!!

source: Stack Exchange

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

sort: votes


text:
When the TX and RX pins for Bluetooth are connected the LCD screen will not update. Why is that?
I have connected a Bluetooth shield and LCD screen to an Arduino Uno. I have two active low push buttons to increase or decrease the variable desiredTemp. This value is meant to be displayed on the LCD screen, and on my smartphone over the Bluetooth serial connection.
This works as intended for my smartphone, however, when my transmission and receive pins are connected to the board the LCD screen is frozen until the pins are removed. Additionally, I'm not able to update the desiredTemp variable through the Bluetooth serial connection.
Attached is my code:
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>

LiquidCrystal LCD(10,9,3,2,1,0);
double inIRPin = A0;
double inThermPin = A1;

int LED = 4;
char recvChar;

int increaseTemp = 7;
int decreaseTemp = 6;
int increaseTempState = 0;
int decreaseTempState = 0;

#define RxD         13
#define TxD         12
SoftwareSerial BTSerial(RxD,TxD);

double valIR = 0;
double valTherm = 0;
double val = 0;
double temp = 0;
double const tempRatio = 0.125;
double desiredTemp = 40; //Degrees Celcius

void setup() {
 // put your setup code here, to run once:

 pinMode(increaseTemp,INPUT);
 pinMode(decreaseTemp,INPUT);

pinMode(RxD, INPUT);
pinMode(TxD, OUTPUT);
pinMode(LED, OUTPUT);
setupBlueToothConnection();

pinMode(inIRPin, INPUT);
pinMode(inThermPin, INPUT);
LCD.begin(16,2);
LCD.setCursor(0,0);

}

void loop() {
  // put your main code here, to run repeatedly:
   valIR = analogRead(inIRPin); //IR Sensor Output
  valTherm = analogRead(inThermPin);

   increaseTempState = digitalRead(increaseTemp);
   decreaseTempState = digitalRead(decreaseTemp);

   if(increaseTempState == LOW){
    desiredTemp++;
  }
   if(decreaseTempState == LOW){
     desiredTemp--;
   }
   if(BTSerial.available()){
      recvChar = BTSerial.read();
      Serial.print(recvChar);
      BTSerial.println(desiredTemp);
      if(increaseTempState == LOW){
         desiredTemp++;
         updateLCD();
       }
       if(decreaseTempState == LOW){
         desiredTemp--;
         updateLCD();
       }
       if(recvChar == '1'){
         BTSerial.println("Increasing Temp");
         desiredTemp++;
       }
       if(recvChar == '0'){
         BTSerial.println("Decreasing Temp");
         desiredTemp--;
       }
   }
    updateLCD();
  }

 void setupBlueToothConnection()
 {
    BTSerial.begin(9600);

    BTSerial.print("AT");
    delay(400);

    BTSerial.print("AT+DEFAULT");             // Restore all setup value to
    factory setup
    delay(2000);

    BTSerial.print("AT+NAMESmartCoaster");    // set the bluetooth name
    delay(400);

    BTSerial.print("AT+PIN0000");             // set the pair code to connect
    delay(400);

    BTSerial.print("AT+AUTH1");             //
    delay(400);

    BTSerial.flush();

  }

 void updateLCD(){
      LCD.setCursor(0,0);
      LCD.print("Current Temp:");
      LCD.println(temp);
      LCD.setCursor(0,1);
      LCD.print("Desired Temp:");
      LCD.println(desiredTemp);
      delay(100);
  }

So you connected the LCD to RX and TX pins and wonder why the LCD fails when the serial sends something?

Nope the LCD screen is using pins 10,9,3,2,1,0. Rx is using pin 13 and Tx is using pin 12.

Serial.print(recvChar); sends to pins 0 and 1.

I need some help with Arduino serial communication, could you please tell me one thing, if I want to connect two serial communication with Arduino Uno pin 2,3 and normal hardware serial communication 0,1 and two devices are one is Bluetooth and another one is GPS, so my question is there is any problem will come during the time of receiving and transmitting data from Bluetooth? And the next question is what serial communication we can use for this type of project?

You connected the LCD module to serial hardware pins 0 (RX) and 1 (TX).
When you receive the data from the Bluetooth module, through the software serial, you send it to the hardware serial.
if(BTSerial.available()){
      recvChar = BTSerial.read();
      Serial.print(recvChar);
...

This messes up the communication with the LCD module. Remove Serial.print(recvChar); and it should work.

A more sensible solution would be to use hardware serial for the Bluetooth module and the other pins for the LCD module.
Software serial should only be used, if you really can't use the hardware serial, e.g. you need the hardware serial to communicate with another device (a PC or some other module).

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


text:
I2C Interrupting Loop?
Imagine i have a code, that loops, and at one point there is i2c request.
Is loop() paused right away when there is Wire.onReceive() or loop is finished then Wire.onReceive() is called?

Let's not imagine stuff. Let's post an example piece of code.

Interrupts happen (almost) immediately if that answers your question.

if i have loop of 10 lines, and when loop is on line 4, at that time there is i2c request, will arduino switch to i2c request process it and then countiniue to line 5 of loop or it will finish loop first then go to i2c request?

You are basically asking how interrupts work so see my question and answer about interrupts.

Thanks Nick, now when i know that receiveEvent is just a classic ISR now its all clear.

The onReceive callback is called from an interrupt service routine (ISR). As the name says, interrupts are "interrupting" the currently executing code almost immediately. And "almost immediately" means that it only will take a few clock cycles. (This is the reason why changing data in an ISR can corrupt data, since the ISR may change a variable, when the main code tries to read it)
So the Arduino will not wait for the loop() function to end. It will interrupt in the line, where it was when the interrupt occured, and return to it after the ISR returns.

So basically I2C receiveEvent is just normal ISR?? I didnt know that.

@Nicky -  It is not strictly speaking a normal ISR. For one thing,  it takes an argument. However it is called from code in the library function which is called by the TWI_vect (I2C interrupt vector). Therefore the time that the onReceive is called is "any time" (that interrupts are enabled).


text:
Arduino leonardo + OV7670 non-FIFO
I want to transfer image to PC via Arduino leonardo.
OV7670 is non-FIFO, and no SD card connected.

I followed this blog and this youtube video.using this code.
when uplaod, I got errors below:
Arduino: 1.8.5 (Windows 10), Board: "Arduino Leonardo"
error: 'ASSR' was not declared in this scope
error: 'EXCLK' was not declared in this scope
error: 'AS2' was not declared in this scope
error: 'TCCR2A' was not declared in this scope
error: 'COM2A0' was not declared in this scope
error: 'WGM21' was not declared in this scope
error: 'WGM20' was not declared in this scope
error: 'TCCR2B' was not declared in this scope
error: 'WGM22' was not declared in this scope
error: 'CS20' was not declared in this scope
error: 'OCR2A' was not declared in this scope
error: 'UBRR0H' was not declared in this scope
error: 'UBRR0L' was not declared in this scope
error: 'UCSR0A' was not declared in this scope
error: 'UCSR0B' was not declared in this scope
error: 'RXEN0' was not declared in this scope
error: 'TXEN0' was not declared in this scope
error: 'UCSR0C' was not declared in this scope
error: 'UCSR0A' was not declared in this scope

I know that error occurred because this code is only for UNO. But mine is leonardo. Changing settings (Tool->board:uno board) was still compiling error.
I have search this Topic found nothing. I am so confusing, please help.


text:
card.init(SPI_FULL_SPEED,SD_CS_PIN) returns false for Arduino Mega
I am working with a music shield, I have got my code from this site https://www.waveshare.com/Music-Shield.htm it works fine with arduino UNO but when I try to use it on MEGA it give me errors, Well I found that the problem is with this line
card.init(SPI_FULL_SPEED,SD_CS_PIN)

in uno SD_CS_PIN=10 I tried to change it to 53 based on this map
SPI   Uno   Mega
SS   10   53
MOSI   11   51
MISO   12   50
SCK   13   52

which is available on https://forum.arduino.cc/index.php?topic=165170.30 but still it returns false. What other options do I have to make it work on MEGA?
Thing that I am trying
#define SD_CS_PIN=10
#define VS_XRESET A0
#define VS_DREQ   A1
#define VS_XDCS   A2
#define VS_XCS    A3
void VS10XX::init(void)
{
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  pinMode(53, OUTPUT);

  pinMode(VS_XRESET, OUTPUT);
  pinMode(VS_DREQ, INPUT);
  pinMode(VS_XDCS, OUTPUT);
  pinMode(VS_XCS, OUTPUT);
  digitalWrite(VS_XDCS, HIGH);
  digitalWrite(VS_XCS, HIGH);

  reset();
}

In setup I added used this code but still does not work
void setup()
{
  Serial.begin(115200);
  pinMode(53, OUTPUT);//setting pin 53 to input
  player.begin();
}

the error code when I attempt to init sd card is 0 which says
/** timeout error for command CMD0 */

did you try the examples of the shields library? 'your' code is from insides of the library

@Juraj yes it is exactly that code, I am just changing parametrs to find out where is the problem

I think nothing needs to be changed for Mega. only set the pin 53 mode to output in .ino

@Juraj I removed all modifications from library and added pinMode(53, OUTPUT);//setting pin 53 to input to setup() but still does not work

from SD library comment of card.init: "The value one, true, is returned for success and the value zero, false, is returned for failure.  The reason for failure can be determined by calling errorCode() and errorData()."

@Juraj The error code is 1 and error data is 0 I tried to look it up in this source https://github.com/arduino-libraries/SD/blob/master/src/utility/Sd2Card.h but could not find it yet

53 is a SS pin if the Mega is SPI slave. Pin 10 is connected to shield to select it as a listening slave. So let the parameter set to pin 10. Additionally on Mega set pin 53 to output, otherwise the Mega can 'fall' into SPI slave mode.
SPI pins 50, 51 and 52 are connected to the ICSP header too. The 6 pin ICSP header is on the same place relative to Uno an Mega common pin headers.

thanks very much, Sorry for my noob question, I am new to arduino, So you mean I must set SD_CS_PIN to 10 and only add pinMode(53, OUTPUT); after SPI.begin(); ?  I updated the question

if it worked with 10 on Uno, then let it 10. for the shield the pin 10 is on the same place on Mega and Uno. 10 is a logical choice for SS on Uno. it must be an output (for the same reason 53 must be output on Mega) if SPI library is used

I tried based on what you said but it still returns false. I showed my code in question


text:
NodeMCU (ESP8266) Defining static IP, stops Firebase processing
Hello i am new to NodeMCU (ESP8266) i am building a small program to connect with WIFI (with internet) and if internet is not available i want to process request over IP address.
I am using firebase as a database / server to fetch the status. And process command through a URL like http://192.168.1.223/on?pin=04 if internet is connected then no problem i can update firebase entry, but with same network (LAN) connection over wifi i want to process i need to have static IP. But the concern is i am not able to make this IP address static, and if i make it static then my NodeMCU is not able to connect with firebase.
Here is how my code looks like:
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include <ESP8266WebServer.h>

#define FIREBASE_HOST "pushst-56f2c.firebaseio.com"
#define FIREBASE_AUTH "mhBpzrNyhhwEGwmFxkVFTIEylwrXMw0gm"
#define PATH "/clients/devicename/watermotor"

IPAddress ip(192, 168, 1, 223);  //Node static IP
IPAddress dns(192, 168, 1, 223);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);

char ssid[] = "MyNetwork";
char password[] = "Qwert98!!";

int wifiStatus = WL_IDLE_STATUS;

ESP8266WebServer server(80);

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

      delay(100);
      Serial.println();
      Serial.println();
      Serial.print("Your are connecting to;");
      Serial.println(ssid);

      WiFi.begin(ssid, password);
      WiFi.config(ip, dns, gateway, subnet);

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

      wifiStatus = WiFi.status();

      if(wifiStatus == WL_CONNECTED){
          digitalWrite(WIFI_CONNECT_LED, LOW);

         Serial.println("Your IP address is: ");
         Serial.println(WiFi.localIP());

         Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
         Firebase.set("/clients/devicename/watermotor/name", "Motor");
         Firebase.set("/clients/devicename/watermotor/relay_status", "off");
         Firebase.set("/clients/devicename/watermotor/device_status", "online");
         Firebase.stream(PATH);

         server.on("/on", handleOnRequest); //Associate the handler function
         server.on("/off", handleOffRequest); //Associate the handler function

         server.begin(); //Start the server
      }
      else{
        Serial.println("");
        Serial.println("WiFi not connected");
      }

}

void loop() {
    server.handleClient();
    if (Firebase.failed()) {
      Serial.println("streaming error");
      Serial.println(Firebase.error());
      delay(1000);
      return;
    }

    if (Firebase.available()) {
        Serial.println();
        Serial.print("Firebase available");
        Serial.println();
        FirebaseObject event = Firebase.readEvent();
    }
}

I am not sure if its there is some problem with FirebaseLibrary or its just the ESP8266!
Any suggestions will be helpful, thanks in advance! :)

why same IP for esp8266 and DNS?

Its just for reference, i can keep any @Juraj

it should be the address of the DNS server which can resolve the name of the firebase host

Not getting you @Juraj any example?

example? just fill in the IP address of the DNS server which is usually the address of the router/gateway IPAddress dns(192,168,1,1); (if this is right)

Don't cross post. You already asked this on SO.

Ok i am trying it @Juraj

Hey buddy its done! It helped! @Juraj

They suggestion you gave has make it work! :) Thank you so much. I think you should post it as an answer. I will be happy to upvote it.

You have wrong DNS server IP address. In your sketch it is the same as the static IP address you assign to esp. Then the name of the firebase host can't be resolved by DNS.
The DNS server is usually the router/gateway.
IPAddress dns(192,168,1,1)

I also placed the same problem(If I set the static IP means it's not getting internet)But Then I added the DNS "IPAddress dns(192,168,1,1)" for that also it didn't connect to the Internet. But I connected to the Internet after adding the "IPAddress dns(8,8,8,8)".
This is my Code
#include <ESP8266WiFi.h>
const char* ssid = "Varaprasad";
const char* password = "varara";
int red = D6; int green = D7; int blue = D8;
const char* host = "18.221.215.201";
IPAddress staticIP(192,168,1,78);
IPAddress gateway(192,168,1,254);
IPAddress dns(8, 8, 8, 8);
IPAddress subnet(255,255,255,0);
void setup()

{
 pinMode(red,OUTPUT); pinMode(green,OUTPUT); pinMode(blue,OUTPUT);
Serial.begin(9600);
Serial.println();
Serial.printf("Connecting to %s\n", ssid);
WiFi.begin(ssid, password);
WiFi.config(staticIP,dns, gateway, subnet);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
  if(WiFi.status() == WL_CONNECTED){
  WiFiClient client1;
    if (client1.connect(host,80))
      {
         client1.stop();
      analogWrite(red,0); analogWrite(green,1023); analogWrite(blue,0);
      }
      else{
      analogWrite(red,1023); analogWrite(green,0); analogWrite(blue,0);
      client1.stop();
      }
    }
  }

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


text:
how can I break from this case by IRremote even if it's not finished yet?
I want to give a pause to case 0xFF02FD or at least to break from that case by entering the case 0xFFA25D even if the 1st case not finished, when I press power button wich has hexa code ( 0xFFA25D) I turn On the led and when I press playButton(0xFFA25D ) I turn on the piezoo and turn off the led (as you can see in my code) but I can't get out from that case by pressing powerButton again I should wait till it ends .
void loop() {
  if (irrecv.decode(&results)) {
    // If it's been at least 1/4 second since the last
    // IR received, toggle the relay
    Serial.println(results.value,HEX);
    irrecv.resume();
  }

  switch(results.value){
    case 0xFFA25D:
      digitalWrite(redPin,HIGH);
      break;

    case 0xFF02FD:
      digitalWrite(redPin,LOW);
      firstSection();

      //Play second section
      secondSection();

      //Variant 1
      beep(f, 250);
      beep(gS, 500);
      beep(f, 350);
      beep(a, 125);
      beep(cH, 500);
      beep(a, 375);
      beep(cH, 125);
      beep(eH, 650);

      delay(500);

      //Repeat second section
      secondSection();

      //Variant 2
      beep(f, 250);
      beep(gS, 500);
      beep(f, 375);
      beep(cH, 125);
      beep(a, 500);
      beep(f, 375);
      beep(cH, 125);
      beep(a, 650);
      delay(500);
      break;
  }
}

with if (something) break;?

that won't help, if  I can break by if condition I can do this just by calling another case,
the only way to use if ()break; is by setting the condition before entering that case, which is not effective.

you want to go to start of loop() ? use return;

for clarity: I know from the start what OP wants. But I answer what he asks, because Google likes StackExchange and people will come here to find an answer to the question, not what OP had in mind.

you need to clarify the problem in your mind ... it actually has nothing to do with the switch/case statement ... the real problem is how to interrupt a long subroutine with a button press..

You are not asking to simply exit a switch-case statement, but to react to your IR remote button press during the execution of other code. With a normal push button directly connected to the Arduino you would normally do this through an interrupt routine. Maybe the library, that you are using, supports decoding IR signals trough interrupts.
If not, you have one more option:
From your code it seems, that the IR receiving part is non-blocking. This means, that it only executes, if there is really something to receive, else it would let the program execute the rest of the code, not blocking the execution. Then you have to program your piezo code (the code in the case 0xFF02FD:) as non-blocking code (maybe using PWM hardware or timer interrupts to output the right frequency and just setting trigger variables in your switch-case statement).
When the piezo code is non-blocking, the decode function of the IR library is executed also during your beep sequence, so your program can react to the results of it.

thanks for your answer, so the best thing is to use timer interrupts,
is it ok to use timer0 to define an interrupt handler isn't this gonna mess with millis() or delay() ?

Yes, timer0 is used for millis() and delay() and you cannot simply define your own ISR for it without disabling the one defined somewhere in the avr includes (currently don't remember where exactly). Why not using another timer? The ATmega328P, which is used in Arduino UNO and Nano, has 3 timers. But be sure, that the timer you choose isn't used by the IR library.

actually, the IR library was using timer2 and I change it to timer3 because it was interfering with tone() function.
and thank you again.

If this answered your question, please mark it as the correct answer

Because you only check if (irrecv.decode(&results)) at the top of loop(), that is the only point in your code that you can change your action based on a new IR input.
While not an ideal solution, you could just insert if (irrecv.decode(&results)) {return;}in between all beep() calls.
//Variant 1
beep(f, 250);
if (irrecv.decode(&results)) {return;}
beep(gS, 500);
if (irrecv.decode(&results)) {return;}
beep(f, 350);
if (irrecv.decode(&results)) {return;}

and so on.
A better solution would be to avoid re-typing the same code by using loops and functions. You call beep() repeatedly with only the note and duration changing. You could put your sequence of notes and durations in an array and writing a new function that calls beep() for one element in the array and then increments a pointer to the next note to play. Your loop() calls this function and checks to see if there is any IR code ready also.
An even better solution would be to set up a hardware timer to produce regular interrupts and the ISR would check if there is IR data ready and set a global flag that is checked in the program.

thanks for your help,
what I did is I made 4 arrays of frequency and duration of tones and I put them in for loops for every function, and then I insert the  irrecv.decode(&results) on this loops, it works but it's a pain in the butt,

As noted in the other excellent answer by @chrisl, you are mixing non-blocking code and blocking code, but to have the ability to break out at any instant, you would need to have all your code be non-blocking. But beep() is a blocking function -- it doesn't return control until it's done. And to do what it does in a non-blocking way is a bit more complicated. An alternative is to edit IRrecv library so it can call a user function when a code is received, but again -- complicated.

I want to use timers interrupts but I'm not expert and I'm afraid to mess with delay or millis() ,that's why I was looking for an easy solution .
it seems that as you mentioned before using loops and arrays is the easiest thing I can do , so thanks.


text:
Why would the resistor be after the LED in this project?

This is project 2 of their official arduino projects book called "Spaceship interface". I understand resistors normally reduce voltage so the LEDs don't burnout but here 5v is coming from either digital 3, 4, or 5 and it seems like it goes right into the LED before going through a resistor as it goes back to ground. This makes no sense to me.

A LED has no problem with 5V and the current. Purpose of the resistor in to not to burn the Atmega pin.

resistors do not "reduce the voltage" ... resistors reduce the current  .... if you put a 1k resistor across a 6V battery then the voltage across  the resistor is 6V and the current through the resistor is 6mA .... if you use a 2k resistor, then the voltage is the same, and the current is 3mA

It does not matter if a resistor is before or after a component, see the circuits below.
The resistor reduces the current, and this is true for the path where the resistor is in (until the interconnections before/after the resistor). In the examples there is only one path.

simulate this circuit – Schematic created using CircuitLab

but I think the example in the book is ugly.

Because it is after the LED? Actually I also use it after the LED mostly, especially if I use a resistor array.

because of button with pull-down and the line crossings. And I don't know, wouldn't be one resistor for all 3 LED pins enough?

You need a resistor for each to keep the brightness the same. If you only used one resistor on the ground side then all three LED's would be sharing the same reduced current meaning that if only one was on it would be much brighter then if all three were on.

1V? Really? When I tested a standard red LED it didn't illuminate under 1.8V.

@NickGammon I used the default values, changed it to 5V which is typically Arduino's VCC, and set the resistor to 470 ohm which is a safe value.

Looks better. :)

@NickGammon I routinely use red LED powered by a 1.5V AA cell - they run reliably for ~24 hours.

Through what resistor?

@NickGammon  270Ω - they make good survey markers in a cave (you don'y need much light).

I don't know what a goo survey marker is, but in this project I have an LED flashing away for a couple of years now from a CR2032 button cell. (Did you edit that? I know what a "good" survey marker is, sort of).

It doesn't matter where the resistor is located (before and after are meaningless concepts). What is important is that the resistor is in series with the LED.
This produces an approximation to a constant current source (I = V/R). The actual current is lower due to the voltage drop across the LED, so is actually I = (V- VLED)/R. VLED varies; red LED is lower ~1.2V  blue significantly higher.
The resistor serves 2 functions; to limit the current from the Arduino and to limit the current through the LED (either to limit brightness or protect the LED)

The resistor is to limit the current flow through the LED. A LED will burn itself out if given too much current and the maximum Arduino output current is 40 mA per leg (output). A quick calculation of V=I*R where V is 5 Volts, I = 40 mA leaves R = 5/.04 or 125 Ohms. You don't want to pull that much current from the Arduino so using 220 resistors is a safe bet at 22mA current draw per leg.
That 10K resistor keeps pin #2 at the ground potential until the button is pushed. Then the input to pin #2 is 5 Volts.
FWIW - that is an ugly drawing.

Most single or RGB LEDs can't take more than 20mA without risking overheating/burning up. Modern LEDs need as little as 5mA to be really bright.  I use 1K resistors on boards where the LED is being used as an indicator (like Power, or Rx or Tx active, or for the L (SCK activity) LED.  Sometimes 2.2K when 1K seems too bright still.  Depends on the LED. Test first before soldering thinks up.
To calculate a resistor value for a desired current, use Ohms Law, V=IR,
Voltage = current x resistance.  Rearranged, Voltage/current = resistance.
If you know the Voltage, Vf, of the LED when it is on, and you are driving from an Arduino pin that outputs 5V, then:
(5V - Vf)/current = resistor.
With 5mA and say a Vf of 2.5V: (5V - 2.5)/.005A = 500 ohm.
You can determine Vf of an LED by using a 5V source and a 1K resistor. Connect the LED and resistor in series between 5V and Gnd. Measure the voltage across the LED, that is Vf.  5V - Vf = voltage across the resistor, Vr.  5V = Vf + Vr.
If you know the voltage across the resistor, Vr, you can calculate current flow:
Vr/resistor ohms = current Amps.
Say you measured Vr of 2.7V and used a 1K resistor. Then current = 2.7V/1000ohm = .0027A, or 2.7mA.

This is interesting and informative, but it doesn't answer the question of why the resistor is after the LED and not before it. This is probably why the answer has been voted down (it wasn't me!).

I figured the before/after had been discussed plenty already.  Knowing the reason for selecting the resistor value is also important.


text:
How to detect an read buttons pressure on touchscreen
I made simple 3 red buttons like this:
#include <SPI.h>

#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#include "URTouch.h"

#define TFT_DC 9
#define TFT_CS 10
#define TFT_RST 8
#define TFT_MOSI 11
#define TFT_CLK 13
#define TFT_IRQ  7

Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK,

#define t_SCK 3
#define t_CS 4
#define t_MOSI 5
#define t_MISO 6
#define t_IRQ 7

URTouch ts(t_SCK, t_CS, t_MOSI, t_MISO, t_IRQ);

void setup() {

  tft.begin();
  tft.fillScreen(BLACK);

  tft.fillRoundRect (12,15,30,80,5,RED);//50,100,30,80,5,RED
  tft.fillRoundRect (50,15,30,80,5,RED);
  tft.fillRoundRect (88,15,30,80,5,RED);

  delay(500);
}

And this the part where I need help:
void loop()
{
  int x, y;

  while(ts.dataAvailable())
  {
    ts.read();                //-----------> this is the whole thing
    x = ts.getX();
    y = ts.getY();

  }

What I need is, to know how to detect and read the pressure of the button area, so that I can run different tasks.

The fillRoundRect function format is (initial_Xpoint,initial_Ypoint,length,width,corner_radius,color)
Therefore, you already have the information about the location of the button itself. Next, check if the x and y value is within the button area.
void setup() {

  tft.begin();
  tft.fillScreen(BLACK);

  tft.fillRoundRect (12,15,30,80,5,RED);  //button1
  tft.fillRoundRect (50,15,30,80,5,RED);  //button2
  tft.fillRoundRect (88,15,30,80,5,RED);  //button3

  delay(500);
}

void loop()
{
  int x, y, pressedbutton=0;

  if(ts.dataAvailable())
  {
    ts.read();                //-----------> this is the whole thing
    x = ts.getX();
    y = ts.getY();

    if ((x>=12) && (x<=12+30) && (y>=15) && (y<=15+80)) pressedbutton = 1; else
    if ((x>=50) && (x<=50+30) && (y>=15) && (y<=15+80)) pressedbutton = 2; else
    if ((x>=88) && (x<=88+30) && (y>=15) && (y<=15+80)) pressedbutton = 3;
  }

  ...
  ...
  ...
 }

I'm not 100% sure what you ask, but I assume you want to perform a task depending on what button has been pressed.
You can do this by checking x and y, e.g.
switch (x)
{
case 0:
   switch (y)
   {
   case 0: // Button (0,0) is pressed)
      perform_task_A();
      break;
   case 1:
      perform_task_B();
      break;
   ... // etc.
   }
   break;
case 1:
   switch(x)
       // Etc. as above but use different tasks.

Than create for each task a function
void perform_task_A()
{
   // Do your code
}

If you want to change 'functionality' depending on a button press, e.g. assume perform_task_A should read a digit, than create a new switch statement there to read a digit key.
If you want more complicated menu structures/input entering, check into state diagrams to keep track where you are in the UI-flow and act on the current state AND the pressed button.


text:
RF522 version 0x12
I bought a bunch of the common RC522 boards from some AliExpress vendor. They (I tried multiple) seem to work at the register read-write level, but they don't seem to execute commands, much less recognise any RFID card.
But the really weird thing is that the version returns 0X12, which matches neither the rc522 1.0, nor the 2.0, nor the clone that should return 0x88.
I verified with my scope that the chip indeed answers to the SPI byte 1110_1110 (read register 0x37) with the value 0001_0010. The signal is crip, no clock skew, nice sharp edges.
I tried this with an Arduino Uno and an Arduino Due, using a recent version of the miguelbalboa library. But as I see this on my scope, it can't see how it can be a software problem.
Has anyone seen this, or better: found a solution?

Have you verified that your (unseen) code is actaully valid? i.e. does your (unseen) code work with other boards that are not 0x12?

All boards I have seem to respond in this way (I tried some 5 out of 100). For the code I tried a few repo's, last was I think https://github.com/miguelbalboa/rfid. But as I see the SPI 'command' byte & response on a scope, the question is mostly independent of the actual code.

Oh, ok. I meant ones that don't respond with version 0x12 which you say doesn't match any values you expected - Or, put another way, do you have any rc522 boards that return a version that "matches"  1.0, 2.0 or the 0x88? Perhaps these 0x12's require different code?

Looking at the MFRC522 library ... the version needs to be one of 0x88, 0x90, 0x91 or 0x92 ... anything else aborts PCD_PerformSelfTest - other than that there's nothing in the code that specifically requires a particular version ... however, given that the version you have is not one of those four, perhaps the issue is with compatibility

Put a delay(5) right after init() in setup() and firmware readout will work.


text:
How to scroll data in LED dot matrix through multiple modules?
I've been struggling in this issue for a long time, I know there are people who have done it.
But, I don't have much experience in C to have the skills to design or develop such complicated functions.
I want to scroll data, e.g. text, chars or numbers just like the nice projects in YouTube about the dot matrix.
Like this one: How to Make a SCROLLING TEXT Display at Home

I know how to display a char, but I don't know how to scroll it. If I try I don't get the results I want.
This is my function for displaying chars:
void draw(void)
{
  s=0;
  uint8_t data_shift_buf;
  for (l=0;l<26;l++)            // to print 26 letters
  {
    for (row=1;row<9;row++)     // for 8 matrix rows
    {

        SPI_TX_m16(data = (row<<8) | (Alphabet[s]),4);// trying set data by column
        s++;_delay_ms(300);
    }
  }
}

what does this mean ? LED dot matrix throw multiple modules ... what are you throwing?

It's obviously "through". Feel free to improve the question, as I just did.

What module do you have exactly? Maybe this will help: http://www.gammon.com.au/forum/?id=11516

@NickGammon Thanks for the edit :) Like, this one: http://www.belajarduino.com/2016/08/4in1-dot-matrix-led-module-32x8-pixel.html

Yep, the MAX7219 - you can scroll with that. See the link above. I don't know how to make an answer without copy/pasting the whole link. :)

@NickGammon Thank you so much, I've looked into the link and found a lot of development with the MAX7219, and found an interesting comment at the end of the posts: "There is also a demo of scrolling text, however that scrolls a chip at a time, not a pixel at a time.
", which is what I'm looking for! I'm looking for scrolling by pixel.

The very next paragraph under that says: Library updated on 2nd October 2015 to have smooth scrolling. A new example has been added which demonstrates this. To achieve this each for each display module (8 x 8 pixels) the code calculates the pixels for the byte before, the current byte, and the byte after. Then it applies the pixel offset to choose a starting point somewhere in those 24 (horizontally) pixels.

WOW that should be amazing, really I'm trying to solve this problem for days. Yes, he calculation for the first and the second display, OK thank you so much for the support.

Take a look at the Parola.h library also.  https://github.com/MajicDesigns/MD_Parola  It can scroll up, down, left, right, and for large #s of displays.

Thank you for response, that library is very difficult for me, so I tried and tried until I did it on my own, I can only scroll to right. But the function is long compared to functions in Parola library it's written in C++, it's really interesting to do such things in small functions.

This is the function for my problem.
void draw(void)
{
uint32_t map_buffer=0;int8_t i,k;
uint8_t data_reg[4] = {0xaa,0xbb,0xff,0xff};      // random data to write
uint8_t dis_buf[4],no_device,no_col;s=0;l=3;

for (i=0;i<4;i++)
map_buffer |= data_reg[i] << i*8;                 // loading data into map_buffer

for (col=0;col<32;col++)                          // for 8 matrix columns
{
    map_buffer >>= 1;                            // start shifting the data by 1 pixel
    for (i=0;i<4;i++)
    dis_buf[i] = map_buffer >> i*8;              // loading shifted data into display buffers
    for (i=0;i<4;i++)
    {
        for (row=1;row<9;row++)                 // for 8 matrix rows
        {
            SPI_TX_m(data = (row<<8) | (dis_buf[i]),i);
        }
    }_delay_ms(1000);
}

}


text:
D1 Mini; is there a fuse?
While this board (listed on ebay as D1 Mini NodeMcu Lua WIFI ESP-12F ESP8266 WeMos 4M Bytes Development Board Kit) was powered by usb, I accidentially shorted between the gnd (G) and 5v pins on the left, and some magical smoke escaped.
I can no longer power the device from usb, but it works nicely if I supply it with the right voltage on either the 5V on the left or the 3V3 on the right.
So something has burned between the 5V on the usb and the 5V on the regulator.
I have tried measuring the components with an ohmmeter, and compared it to a working board, but I can measure no difference.
Is one of these tiny components a fuse, or a diode to prevent backwards voltage from board to pc, if the board is powered on the pins?
Or could the short between 5V and GND have caused a track to burn?

Hard to tell. Examine it closely with a magnifier and look for holes and cracks in components. There may be a diode there that has gone...

Looking at a possible schematic, yes, there is a diode (called D2 on the schematic) that would likely blow if you shorted 5V to GND.

Looks like it may be just left of the USB socket (small and black)...

I think I may have a D1 Mini somewhere here. If I can find it I'll have a look at blowing it up (AKA "destructive testing") to see what happens.

Found my D1 Mini. It's different to yours. Mine is genuine Wemos (version 2.3.0) and it does include a PTC fuse.

diodes on cheap wemos boards are barely adequate for the MCU and burn on high loads, not just shorts.

@Majenko Mine is similar to the one in the pic above, more pics here: https://imgur.com/a/xhx1ctn Any clue which one's the diode that needs replacing?

@adeelx Immediately to the left of the USB port is a ceramic capacitor. Directly above that is the diode.

It's remarkable how the maker managed to misalign the USB connector by that much and get away with it.

Try measuring with a voltmeter to compare the good board to the bad one. If it is the diode as mentioned in the comments under the question, you should get a different reading on the bad board. It should be fairly easy to replace if you have a soldering iron and a steady hand.

Indeed; I measure about 0,4v across the diode at the good board and 2.9v at the bad board.
I don't have SMD-diodes at hand, but I guess I'll solder a wire from the usb-end to plug into my breadboard while testing.

@Lenne Did you figure out which diode needs replacing? I'm in the same condition and would like to salvage the board if possible.

I came here because of a dead Wemos D1 Mini Pro. One which I managed to kill in exactly the same way (shorting out something while trying to measure a voltage - most likely I shorted the 5V and GND as well :) ).
The symptoms were identical - could power the board via 5V or 3V3, but not via USB. And they were solved after replacing the diode - or, more accurately, bypassing it, since I was unable to find an SMD Schottky to replace it with.
I won't tell you the rest of the story (where I first blamed it on the voltage regulator and replaced that), to save myself the embarassment :)

I can confirm that the component, which on my Mini clones (which have an almost identical layout) is the tiny black component pictured at the upper left corner of the USB shielding, is a diode and can be blown pretty easily by shorting +5 to Gnd. I did as you Lenne proposed and jumpered it with a tiny wire and recovered the device.

I've done exactly the same as the above folks. But I did find S4 diodes on ebay for $2.99/ 100. I've ordered them up. meanwhile I'll jumper around it.


text:
Controlling multiple fans using arduino uno
I'm kind of new on the field of Arduino. Although I have a question concerning multiple fan connection on 1 arduino PWM pin. The goal is to connect around 8 to 16 fans on 1 arduino  pwm header pin and control their speeds separately using a potentiometer. As I seen it can be achieved by using transistors. The question is are there any limitations on how many fans can I connect and control seperatly using tranzistors? Can I for example use 16 transistors and control 16 fans seperatly ?
Thank you for your answers in advance

Need more information about can be achieved by using transistors. Furthermore, I don't think PWM multiplexing is a good idea. See the answers on this https://arduino.stackexchange.com/questions/31099/pwm-multiplexing-on-arduino-nano

You want 16 fans on one PWM pin, is that it? What is the purpose of the PWM pin?

The idea is that the goal is to connect arround 6 to 16 fans (depending on the situation I don't know how many at the moment) and I want to control them seperatly using potenciometer.
The idea is that they should be controled seperatly as in for example FAN1 - 100% (Max RPM)
FAN2 - 70%
And so on..
Do you understand the goal now? What would be the best solution for this situation?
I will also connect a 128x64 screen and  4 buttons for meniu navigation

One PWM pin can control only one fan (or one group of fans). You can't have one PWM pin outputting different values to different fans, since one pin can only have one value. (Yes, there are ways of multiplexing it through time slicing but that is both hard and not a good idea).
You need one PWM per fan if you want individual control of each fan's speed. That means a maximum of 6 fans on an Arduino.
To get more you would either have to use software PWM (which can introduce jitter which may not be a problem with simple fans), or an external PWM controller.  Or add more Arduinos.
If all you want is potentiometer control of the fans you can do it without using an Arduino. A pair of op-amps (it can be a single dual op-amp chip), one acting as a triangle wave oscillator, and the other as a comparator, will generate PWM for you.  Here's an example:

Image by ElectroBOOM (watch his videos sometime, they're hilarious)

Can I merge multiple arduino unos together? for example hook up a screen on one arduino uno, and buttons, and use 2 - 3 arduinos to control fans, but display the info on the first arduino?
Is it possible to use arduinos as extenders? If so how?

@dmxyler Sure. You just need to get them to communicate with each other. I2C and Serial are common ways - there's plenty of online resources.

ok thank you for your advice. WIll try. Have a great day :)

One option for controlling multiple PWM output is to use a I2C PWM Driver (e.g. PCA9685).  It has 16 PWM outputs and is controlled from the arduino with I2C which only requires 2 pins on the arduino.
Tutorial: https://learn.adafruit.com/16-channel-pwm-servo-driver


text:
Getting error 32 in multi-master I2C sketch with library https://github.com/rambo/I2C
I am developing a multi-master scenario sketch with the https://github.com/rambo/I2C library, because this library will handle multi-master data collisions.
I created a setup with two Arduino nano's which act both as master and slave.
My sketch works as long as I use only one master. Sending data from one Arduino to the other works fine. The other receives the data.
But when I sequentially try to send data from the second Arduino to the first, I get an error (32). After that even sending data from the initial Arduino results in error 32.
This is the used sketch for both the Arduino's.
The only difference is that I switch the values of rel_address and own_address when programming the seconds Arduino.
Sending data is done by pressing a button on pin 2 (switchPin)
/**
   atme328 = ATmega328
   SDA --> Pin A4
   SCL --> Pin A5
*/
#include <I2C.h>
#include <Wire.h>

int switchPin = 2;
int relayOnPin = 3;
int relayOffPin = 4;

uint8_t broadcast_address = 0;
uint8_t own_address = 11; // CHANGE FOR EVERY MODULE!!
// rel_address = address of relay to switch; SET to own_address if relay is connected to this chip!
uint8_t rel_address = 10; // CHANGE FOR EVERY MODULE!! SET to own_address if relay is connected to this chip!
uint8_t rpi_address = 1;

unsigned long counter = 0;

void setup() {

   Serial.begin(9600);
   pinMode(switchPin, INPUT_PULLUP);

   pinMode(relayOnPin, OUTPUT);
   pinMode(relayOffPin, OUTPUT);
   // start condition
   digitalWrite(relayOnPin, HIGH);
   digitalWrite(relayOffPin, LOW);

   I2c.begin();
   I2c.timeOut(50);
   // I2c.pullup(true); // done by external 4.7kOhm resistors

   // config Wire library for I2C slave functionality
   Wire.begin( own_address );

   TWAR = (own_address << 1) | 1;  // enable broadcasts to be received!

   // set slave receive callback
   Wire.onReceive( onI2CReceive );

}

void loop() {
   counter = counter + 1;
   if (counter == 20000) {
      digitalWrite(relayOnPin, LOW);
      digitalWrite(relayOffPin, LOW);
   }
   if ( digitalRead(switchPin) == LOW ) {
      sendCmd('d', rel_address); // send command to remote relay
   }
}

void sendCmd(uint8_t cmd, uint8_t address) {
   uint8_t status = I2c.write(address, cmd); //configure device for continuous mode
   if (status > 0) {
      // error codes at https://github.com/rambo/I2C/blob/master/I2C.cpp
      Serial.print(status, DEC);
      Serial.print('!');
      digitalWrite(relayOffPin, HIGH);
      delay(50);
   } else {
      digitalWrite(relayOnPin, HIGH);
      Serial.print('.');
   }
   counter = 0;
}

void onI2CReceive(int howMany) {
   // loops, until all received bytes are read
   while (Wire.available() > 0) {
      digitalWrite(relayOffPin, HIGH);
      Serial.write(Wire.read());
   }
   counter = 0;
}

What do I need to do to be able to send from two units using this library?
Thanks!

Shouldn't you use only one I2C library?

the repeated starts support was added to Wire library some yeas ago, if this is the reason you use the I2C library

@Juraj the I2C library only supports master operations.  I found some dedicated master / dedicated slave example of the I2C library and they also use the Wire library for the slave (https://github.com/Scott216/I2C-Examples)

I use the I2C library to overcome the hanging of the sketch on master send collision. If I use the Wire library, the sketch simply hangs on a collision. Something in the Wire library so it seems...

examples can use Wire for slave, but not in the same sketch. both libraries set the same I2C registers

You cannot use the I2C library and the Wire library at the same time. From the code I guess you wanted the Wire library to do the slaves job and the I2C library to implement the master. But since both libraries use the same hardware, this cannot be divided between them. Combining two libraries for the same hardware isn't that trivial. The I2C library only provides master functionality. So, to reach your goal, you would have to find a library, that provides both master and slave functionality while doing correct bus arbitration (which is the term for correctly handling master data collisions). Or you have to change one of the two libraries yourself, to provide the missing functionality.
And the error you get is defined in #define MT_SLA_NACK    0x20 in I2C.h (0x20 is equal to 32). This means, that you haven't got an acknowledgement from the slave you have addressed. This suggests, that in your current code only the master functionality is working. (But it may have another meaning considering the interaction of the two libraries on the same hardware)

I ended up removing the I2C library and using a modified version of Wire.
I replaced the twi.h and twi.c libraries in C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\utility with those from http://liken.otsoa.net/pub/ntwi/. This implementation adds timeouts to the operations, which prevents a hang-up.


text:
cannot resolve overloaded function... error
I started to learn Arduino and I want to get an input from user to blink LEDs. I wrote under the void loop() section input codes. After i compiled it and Arduino IDE gave me this: "Arduino:1.8.5 (Windows 10), Kart:"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"
C:\Users\Yunus Emre ERYILMAZ\Documents\Arduino\sketch_feb17a\sketch_feb19a\sketch_feb19a.ino: In function 'void loop()':

sketch_feb19a:27: error: cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

 numBlueBlink=Serial.parseInt;

             ^

sketch_feb19a:31: error: cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

 numYellowBlink=Serial.parseInt;

               ^

exit status 1
cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences."

What should i do, how can solve this problem? Thanks.
The code that i wrote:
int blueLEDPin=9;  // Declaring blue led's pin is 9.
int yellowLEDPin=10;  //Decllaring yellow led's pin is 10.
int blueOnTime=250;  // Bue led ontime
int blueOffTime=250; // Blue led offtime
int yellowOnTime=250; // Yellow led ontime
int yellowOffTime=250; // Yellow led offtime
int numBlueBlink=0;
int numYellowBlink=5;
String blueMessage="The blue LED is blinking...";
String yellowMessage="The yellow LED is blinking...";

void setup() {
  String wm1 = "Welcome to";
  String wm2 = " My Program";
  String wm3;
  wm3 = wm1+wm2;
  Serial.begin(115200);
  Serial.println (wm3);
  pinMode (blueLEDPin,OUTPUT);
  pinMode (yellowLEDPin, OUTPUT);

}

void loop() {
Serial.println ("How many times do you want the blue LED to blink? ");
while (Serial.available()==0){ }
numBlueBlink=Serial.parseInt;

Serial.println ("How many times do you want the yellow LED to blink? ");
while (Serial.available()==0){ }
numYellowBlink=Serial.parseInt;

Serial.println (blueMessage);
for (int j=1; j<=numBlueBlink; j=j+1) {
  Serial.print ("   You are on Blink #: ");
  Serial.println(j);
  digitalWrite (blueLEDPin,HIGH);  // Turn first led on
  delay (blueOnTime);  // Wait
  digitalWrite (blueLEDPin,LOW); // Turn first led off
  delay (blueOffTime); // Wait
}

Serial.println (" ");

Serial.println (yellowMessage);
for (int k=1; k<=numYellowBlink; k=k+1){
  Serial.print ("   You are on Blink #: ");
  Serial.println (k);
  digitalWrite (yellowLEDPin,HIGH); // Turn second led on
  delay (yellowOnTime); // Wait
  digitalWrite (yellowLEDPin,LOW);  // Turn second led off
  delay (yellowOffTime);  // Wait
}
Serial.println (" ");
}

The function parseInt is a function and you have to add parameters with ( and ), even when it has no parameters, thus instead of
 numBlueBlink = Serial.parseInt;

you have to write
 numBlueBlink = Serial.parseInt();

See Serial.parseInt for a reference.


text:
Is it possible to upload a file with GPS values onto my arduino?
I am absolutely new at arduino but ok with writing code. I am trying to upload 20 points of interest lat/long as a static file that sits on my arduino. Then I want to use my GPS sensor and a function which uses the haversine formula to constantly measure distance between all 20 points and the GPS data from the arduino and output the distance to the nearest point on an LCD screen.
I cannot figure out how to store and reference that list of GPS points of interest.

The Arduino does not have a file system per-se, to which you could upload files, unless you create the code that does that. There is "EEPROM" space on the Arduino processor that can hold 1024 bytes of data and survives power-cycles. That should be sufficient to hold 20 lon/lat pairs of sufficient precision.
As for how to get the waypoint data onto the Arduino, you could transfer them over the serial port from your computer, either by manual entry from your computer over the serial monitor of the Arduino IDE or by writing a script in Python or some other language to read the waypoint file and transmit the data according to the protocol you invented.
There are are also SD Card peripherals you can add to an Arduino, so you could potentially just load the waypoint file onto the SD Card from your computer, and then insert the card into the SD Card reader on the Arduino and have it read the data from there.

So can I declare them as global variables in the beginning of the sketch, then upload the sketch and have a function that handles the math to figure out the distance?

Yes, you could do that, but then the waypoints would be hardcoded to your sketch and you would have to re-flash the Arduino to get new waypoints. Your question made it sound like you wanted to have an easily-changeable file of waypoints.

I do. I was just trying to think of something for the mvp but then figure out a file system later. I will definitely look at the EEPROM space solution. Thanks for the quick answer and your patience with this new Arduino enthusiast.


text:
Doubt with the library esp8266wifi and Station Mode
I have been working for a while with the ESP8266 I have a question:
According to the online documentation of GitHub from the esp8266wifi library I can initialize the WiFi in Station mode to (obviously) connect to a nearby AP, I can initialize the station mode in 3 "different ways":

WiFi.begin (): The module initializes the Station mode and connects to the last network that is connected, because the credentials (SSID and Password) are stored in its internal memory (flash?).
WiFi.begin (ssid, password): The module initializes the Station mode and connects to the network with "ssid" and "password".
WiFi.begin (ssid, password, channel, bssid, connect): The same as the previous one, only that you pass more parameters: the one that interests me is the bssid, which is the MAC address of the AP to which I am going to connect.

Now comes the question: if I wanted to use the last mode, because I want to make sure that the ESP connects ONLY to an AP (a kind of MAC filtering), I also have to specify the channel and set the connect parameter? Or I can simply use something like this:
WiFi.begin ("MyOwnNetwork", "123456789", "00: 1B: 44: 11: 3A: B7")

I can not prove it right now, I do not have the module in my hands.

type of parameter bssid is  const uint8_t* (byte array)

the configuration is saved to flash https://media.readthedocs.org/pdf/arduino-esp8266/docs_to_readthedocs/arduino-esp8266.pdf

the configuration is saved including the bssid

What do you mean with: "type of parameter bssid is const uint8_t* (byte array)", the way I wrote the sentence is wrong? Could you give some example? Thanks!

anything inside quote marks "" is a string .... google c++ byte array ... https://stackoverflow.com/questions/2240405/byte-array-assignment

This is the function prototype:

Per C++ rules, in order to supply an argument for bssid, you have to pass an argument for channel as well, but connect is optional since it's positioned after your target argument. This should not be a problem though since you can just pass the default value of channel (i.e. 0) into the function; the channel argument is only relevant if you enter a value between 1 and 13 inclusive.
So your call should basically look like:
char ssid[] = "ssid";
char pwd[] = "pwd";
uint8_t bssid[] = {0x00, 0x1b, 0x44, 0x11, 0x3a, 0xb7};
WiFi.begin(ssid, pwd, 0, bssid);

Great answer!!! Just the one I was looking for!!! Thanks!!!!!


text:
Can I use this power supply with my Arduino?
I am new to Arduino and electronics in general.
I am working on a project where I would ultimately like to power the project from 220V AC (Wall light switch) (I want to replace the light switch with one of my own design).
I will want to feed power to the arduino directly from the 220V connecting wires in the light switch cavity.
This power source is 5V (I know the Arduino needs 9-12V), but I will use a USB connector, wired onto my AC/DC power source, to power the Arduino.
Power Source
Ratings:
AC85 - 264V or  DC110 - 370V wide voltage input
DC 5V(+/ -0.2V) 600mA isolated output
Input Current: 0.0273A/115VAC  0.014A/230VAC
Input surge current: 20A (230VAC)
Frequency range: 50/60 Hz
Operating Temperature: -30 - 70 ℃
Relative humidity: 20%- 90%
Rated power: 3W
Output efficiency: 80%

I don't really know why yet (this is part of figuring that out), but I have the feeling that the arduino would want a linear power source, rather than a switching power source. (Because linear is cleaner power?)
Regardless, I am asking the question as if this power source will do the job, and if not, why not? (Why not a switching PSU) ?

Yes, that power supply is ideal for powering an Arduino (an Arduino doesn't care if it's linear or switching, and a linear regulator that goes from 220V to 5V is called a furnace, and you don't want one of those...)
HOWEVER unless you have a very strange wiring setup in your house, under normal circumstances there is no 220V supply in the switch.  You normally have live in, switched live out and NO neutral connection.
That means you don't have the connections you need to wire your power supply up to.
By the way: if you didn't already know that then you are not qualified to mess around with home wiring and you should leave it to the professionals.

Well well well... I DID indeed forget about that. I am no electrician, and to be honest I have never opened a light socket, but I do know (forgot obviously) that they are not powered by a neutral and positive. I got whisked away so fast on the cool project idea, that I did not consider that. I just wrongly assumed "there must be power there" because it turns the light on.
Thanks for getting me back on track! ;-P

actually new code recommends/requires putting a neutral at each switch location exactly to enable smart switches.

@ratchetfreak ... depending on where you live...  codes aren't universal.

Being in South Africa in a rather "long ago built house", I probably do not have a neutral wire in the cavity. I will inspect.

in the USA, we've been running neutrals in practice since the 90s and in code since 2011.


text:
Why I get error on string concatination?
exit status 1
invalid operands of types 'const char [5]' and 'const char [2]' to binary 'operator+'
  String message = "Page not found\n\n";
  message += "URI: " + HTTP.uri() + "\n";
  message += "Method: " + (HTTP.method() == HTTP_GET)? "GET": "POST" + "\n";
  message += "Arguments: " + HTTP.args() + "\n";

which line is it having problems with?

try enclosing the ternary operator in brackets ((HTTP.method() == HTTP_GET)? "GET": "POST")

The operators of the class String apply only for an instance of String. In your expression you concatenate two c-strings "POST" + "\n"

A simple fix is to just move the (const char *)s around a little:
This should compile
  String message = "Page not found\n\n";
  message += "URI: " + HTTP.uri() + "\n";
  message += "Method: " + (HTTP.method() == HTTP_GET)? "GET\n": "POST\n";
  message += "Arguments: " + HTTP.args();
  message += "\n";


text:
memory usage "dos and don'ts"
Though I've written C/C++ code for a long time, the unseen limitations on how memory was consumed on various MCU and SOC programming platforms have often tripped me up. As I'm about to build up code for my first large project for my NANO boards, which will likely use a fair amount of its resources, I'd like to be better prepared for any surprising and unexpected "gotchas" to look out for.
For example, on another SOC I recently worked on extensively (The Pololu.com wixel) I was very surprised to learn that function/method arguments and auto variables, which I'd normally expect to be stack allocated and recovered when a function returns were in fact permanently allocated for the life of the program! Wow! so on that platform, where I'd normally hate to "overwork" variables or reuse variables after their names no longer make sense, I had to adjust my coding to what I'd normally consider BAD for readability. Not to mention realizing that simple loop variables were better off allocated globally. Yecch!
Can those of you who have run into such unexpected coding issues in the Arduino environment share some "special" guidelines about things like this?

auto changed from a storage duration specifier to a variable type specifier in C++11. For simplicity don't use auto.

a positive surprise for me is array allocation on stack with size from a variable https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

Oh... gee... sorry... I never meant to infer I ever used the 'auto' keyword (forgot it even existed!). I just meant whatever the default allocation was for non static vars declared within a function.

As you have noticed yourself, this can be somewhat platform-dependent.
Since you are working on a Nano, my answer will be for the AVR
architecture, when compiled with gcc, the avr-libc, and the Arduino core
library.
First, let me reassure you: this weird behavior you saw of the Wixel
doesn't happen on this platform. Local variables get allocated mostly in
CPU registers, then on the stack.
Now, the first general rule may sound obvious: think twice about what
your program really needs to remember. Also, use each time the
smallest possible data type. The C99 types int8_t, uint16_t and co.
are useful for this.
Another rule you will often hear on this platform: avoid dynamic
allocation, i.e. malloc() and new, as quite often you cannot afford
heap fragmentation. Avoid also the String class, as it relies on
dynamic allocation. Prefer when possible static allocation, or stack
allocation for small things.
Don't forget to use const for constants: with this qualifier the
compiler can often optimize the constants out as immediate operands. For
arrays of constants, use PROGMEM. Yes, it's not comfortable
to use, but it can save you lots of RAM. The F() macro for printing
constant messages is a special case of PROGMEM.
Lastly, be very careful with recursion.

Thanks. Good points! I'll usually avoid malloc or 'new' in any embedded program, especially one that might be running unattended for a long time. And also, I too have used codespace memory for any struct or arrays that won't ever change. Or even EEprom structs for things like settings. But just the fact that function vars are stack based is VERY good news. I began to worry seeing so much example code, where the same var name was used again and again, even when its name no longer made sense.

That last point is interesting too! I wonder if a recursive function that went blow past its stack limits would make the poor board nearly unreachable, as it would always run itself into the same hole everytime it saw power.  Its not like the old devices that you could force to a halt with a stream of CTRL-C's sent during power up!

@Randy: There is no stack limit. If you overflow your stack, you will just start to overwrite the program's heap, if any, then the .bss section, then the .data section.

It's not accurate to say things do or do not happen on a particular chip when they are in actuality results of the toolchain or even the language specification, rather than the hardware.

@ChrisStratton: You are right. I added a clarification to my answer. On the other hand, the AVR was designed with compilation in mind. It would be silly (though certainly possible) for a compiler to not use the register file and the stack pointer as they were designed to be used.

Edgar's got some great tips, and I'll reiterate one before giving a few more:
avoid dynamic memory allocation
Don't use malloc. When you're designing a system, budget out your RAM like you do your monthly budget. Make sure you're able to do everything at once.
And a couple other tips:
global statics
Make full use of the BSS block; try to block out space for as much as possible in global static arrays. You may shudder or scoff at the idea of putting everything at a global level, but embedded is a paradigm shift, with its own set of rules.
Since you'll have so many variables at a global level, static helps you to avoid polluting your namespace too much.
avoid fancy C++ features
In fact, try to not use C++ at all. C++ takes you "farther from the metal," with its RAII and its constructors and its implicit type conversion... It's much harder to keep a tight inventory of all of your resources when your language does so much behind the scenes. If you really want to use a certain C++ language feature, try to keep the tone of your code more like "C with bits of C++" rather than "C++ shoehorned into an embedded system." That never goes well.
Especially avoid generics/templates, which will eat up lots of your memory. Every time you use a new type with a template in your code, another copy of the template class is compiled into your program, just for that one type. Ever wonder why C++ binaries can balloon to 20, 50, even 100 MB? Templates, man. Templates.
const
This keyword should go on as many variables as it can. Keeping this habit will save on both execution time and space consumption. Learn the difference between const T* foo, T* const foo, and const T* const foo.

Too much of this is nonsense to ignore. Some of this is good, but recommending a bunch of global state is just bad advice and many people use C++ for this kind of programming. Embedded is not an excuse to write hard to maintain code.

Additionally, C++ templates need not be as heavy-weight as you make them out to be. The key is to make sure you compile with link-time optimization, to prevent each individual object file from having its own copy of each template specialization it uses. 10 different copies of vector<int>, one in each of 10 source files, gets a little unwieldy, but with LTO, the compiler/linker can deduplicate them down to a single shared copy. If you need the functionality, the template specialized code (especially after LTO inlining) is often pretty similar in size to what you'd write by hand.

Do not make a variable global if it is only used in one function. Make it static if the value needs to be remembered from invocation to invocation. Allocation-wise, a static local is the same as a global.

Thanks for the tips. I see the merit in some of this for small systems. Though I've seen C++ compilers come a long way, I'm still reluctant to use "pure" C++, and be 100% OOP in every corner of my code.  Sometimes its overkill. But still, building well established functionality into classes you can tuck away in a library does make your application a lot simpler to follow.


text:
what is welding plate?
I was looking at arduino nano boards here. Description says the arduino board is without welding plate. What does it mean for the user? If I buy this product will there be any issue? I understand that this board does not come with two headers soldered and I am OK with that.

Probably a mistranslation of soldering. As far as I can tell, it just means that the headers are not soldered on.
(see https://www.aliexpress.com/store/product/Nano-V3-0-ATMEGA328P-improved-welding-plate-without-wiring-module-board/630494_32807228948.html for one with "welding plate")

Google translates both Soldered and Welded to 焊接 - I deduce that Chinese uses the same word for both - hence the mistranslation.


text:
Can the DHT11 give reasonable readings?
I bought a batch of ESP8266-01 and DHT11 on ebay.
The sensors give data, but the datasheet say +/- 2 degrees. Who can live with that? Well, they claim the repeatability is 0.2 degrees, so I guess they could be calibrated.
But thet are not stable. They start a few degrees over room temperature, but gradually the reading is up to 33 degrees, more than 10 degrees too high.
Could it be the proximity of the ESP8266 giving off heat? Or are the sensors themselves heating up when reading at one read every two seconds?

I would suspect heat from the 8266.  Can you add a second sensor at a little bit of a distance and compare the two values as it runs for a bit

the sensor only uses microamps, it's not self-heating. you might try the DHT22; twice as good. try reading every 10 seconds and check the linearity.

I have ordered a handful of DS18B20 onewire sensors. I have had more success with these before, they are waterproof, and I can put more sensors on one ESP.

more than 10 degrees too high ... how do you know? ... you did not say that you used a thermometer to verify the reading

i'd suspect the physical placement of the sensor. perhaps its near an incandescent lamp or tube ?

@jsotola I know it's more than 10 degrees off, because I don't run my room temperature above 22C in winter. It's in the hallway now, near the front door, so no direct light either.

did you verify the reading with a thermometer?  ... strap the DHT11 to a thermometer and confirm the suspected discrepancy

It could be the ESP8266, try physically separating the DHT11, but I'm guessing that that will only help slightly.
Do you have some way of reliably calibrating the sensors? If not, then even if you are getting consistent readings, you'll have a hard time knowing how accurate your readings are.
While they're typically more expensive, it might be prudent to buy an infrared temperature sensor. If you have the budget, replacing the DHT11s with IR temperature sensors might just be a better solution, I saw that Sparkfun's MLX90614 was accurate within +/- 0.5 degrees Celsius. If you don't have the budget to replace your DHT11s, or don't want to be wasteful, perhaps you just buy one IR temperature sensor to use as a sanity check. These should be more reliable than DHT11s and you could even write a sketch to calibrate them based on the IR temperature sensor's readings.


text:
Can the arduino be recognized if the usb chip is broken?
My question might seem one of the million questions out there "Can't upload to arduino uno and receive error avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x01" but as I probably read all the million questions and didn't find the answer I am looking for I decided to write my own.
So my arduino is properly detected in device manager and in the arduino IDE but cant upload sketches to it. The main chip (atmega328p) seems well (13-pin LED blinks 3 times on reset) but the usb chip (ATmega16u2) is what I suspect as the RX and TX LEDs don't blink while uploading (and don't blink in any other situation) but again the arduino is detected and I am sure I chose the right board and port.
The serial monitor is always empty and I tried the loopback test and didn't get any echo at all or even any error message but I think that what I should have expected as the RX and TX not blinking means that there is no data transmission in the first place. Or am I wrong?
So is the USB chip broken or maybe corrupt? How can I be sure? And if not then what could the problem be?
I saw a tutorial in the answer of this question to test the usb chip using another arduino but I don't have that in hand right now or an ICSP programmer for that matter.

Have you tried the loopback test? Short TX and RX together on the Arduino, open the serial monitor, and see if you get back whatever you send?

Oh I forgot to mention that. I will edit the question to include it.

It could be dead, yes. Or the firmware may be corrupt. Try reflashing it with dfu: https://www.arduino.cc/en/Hacking/DFUProgramming8U2

But how can it be dead and the arduino is still detected? I am not arguing I really want to know and I am very new to this field.

@Majenko By the way thanks so much for that link. It is more detailed that any other source I found.

It sounds like the GPIO portion of the chip may be dead.  There is an unconfirmed (it's purely anecdotal at the moment) possibility that shorting 5V on an Uno can kill the U2. I don't know the full effects of it yet, but it could be related.

A microcontroller is like a car. Internally there's lots and lots of different sections, all fairly independent. Just like a car, if someone nicks the wheels it's still recognisably a car. The doors still open, the engine still runs, the radio works - you just can't get it to move any more.

It depends on the exact arduino product. An Arduino Uno has a USB programmer chip, that then programs the AtMega 328 Chip. If the programmer is broken, it will likely not register any device when you plug in an arduino uno to your PC.
if the micro-controller is dead, but the programmer is operational, you will get a device in your device manager, but not be able to reprogram the micro controller.
If both the programmer, and the micro-controller are broken, then figuting that out could be difficult. The AVR microcontrolers support other programing methods, and the AtMega 328 IC, supports DebugWire. you could attempt to reprogram the MCU out side of the programmer, if you thought the programmer, was defective.
Here is a great article on using DeBugWire.
https://awtfy.com/2010/02/21/modify-an-arduino-for-debugwire/
another nifty trick I learned, is to take your Digital MultiMeter, set it to diode test, or continuity. then, measure between the ground pin, and the positive voltage pins on the MCU.  If you get a shot, the chip is busted. You will expect to get roughly 0.7Volts, although an OL reading might indicate more about your multi-meter, than the MCU.
Other Arduino devices, that have integrated USB programing, may behave differently. Features of the specific MCU dictate how it can be debugged. You might want to read the datasheet for a specific MCU if you're having trouble.

I'm quite confident that the problem is not with the main chip but can you provide more detail on how to perform that test with the multimeter and what to expect in both cases.

Ground to VCC expect to get 0.5v, to 0.7 volts on a diode test. Short is a certain failed chip, and Open, is suspicious.


text:
Circuit works on breadboard but has power problems on protoboard
I'm building a simple circuit that takes data from an IMU (using MPU6050), sends it to a microprocessor (Arduino Pro Mini 5V) to apply data smoothing and averaging, and then this data is sent using an HC-08 BLE module for the data to be further processed on a mobile. The circuit is powered by a 9V battery (6LR61) connected to RAW (Vin on other Arduino boards).
When I build this circuit on a breadboard, it works well, but the Arduino is power hungry as expected. It runs for over an hour in this setting (I haven't tested it for longer), but I've build this circuit twice using protoboards and it can't stay on. One circuit is able to send data for a while, but the LED on my BLE module dims and eventually turns off after ~5m, and requires me to wait 30+m before I try to power the circuit again. The other circuit has all LEDs shine when power is switched on, but the IMU doesn't send any data (an LED on the Pro Mini blinks whenever I2C data is received).
The shitty thing is that, whenever I power these circuits via USB, they work as intended, just like when I power them using 9V to RAW on the breadboard.
I tested the circuit on the breadboard later and after BLE has connected and is sending data, the whole circuit draws 42.9mA, the BLE module draws 1.5mA, and the IMU draws 5.4mA.
What is the most effective way to fix this problem? Should I focus on finding a different battery, or focus on power-savings within the circuit?
These are my ideas so far:

replace all boards with 3.3V versions
reduce clock speed (might not be viable, I need a lot of IMU data?)
use external voltage regulator, connect Vout from regulator to 5V of pro mini
replace 9V battery with Lithium Ion battery
replace Pro Mini with an ATtiny85

I'd like to take the least time to maximize power savings, so while I could go through all these ideas, I just need the circuit to work at the end of the day.

Where do the other 36mA’s go? Try doing some more measurements. My guess is that it’s mostly due to the regulator(s), on the pro mini. If so using a separate voltage regulator would help. Also ditch the 9V. Those are just 6 AAAA batteries in a packed together, and can only supply 400mAh. Lastly, the might be an issue with not having enough bypass capacitors. Breadboard have some capacitance due to how the are constructed. Switch to protoboard, glitches may occur due to no longer having bypass capacitors. Not sure if that’s the case here, but that immediately came to mind reading only the title

36mA sounds about right for an Arduino.

I have a page about power saving.
To summarize some of the techniques you can use:

Run the processor at a lower frequency
Run the processor at a lower voltage
Turn off unneeded internal modules in software (eg. SPI, I2C, Serial, ADC)
Turn off brownout detection
Turn off the Analog-to-Digital converter (ADC)
Turn off the watchdog timer
Put the processor to sleep
Don't use inefficient voltage regulators - if possible run directly from batteries
Don't use power-hungry displays (eg. indicator LEDs, backlit LCDs)
Arrange to wake the processor from sleep only when needed
Turn off (with a MOSFET) external devices (eg. SD cards, temperature sensors) until needed

I've got a temperature and humidity sensor which has been running for years on 3 x AA batteries.

The circuit is powered by a 9V battery (6LR61) connected to RAW (Vin on other Arduino boards).

That's not a great choice for a start, as the voltage regulator has to turn the 9V into 5V (in the form of wasted heat). You'd be better off with 3 x AA batteries (around 4.5V) and put them straight into the 5V pin.
Those 9V batteries have notoriously low mAh because they are basically 6 coin cells stacked on top of each other.

What Nick said about wasted heat sound very much like the issue you are having. The tiny little regulator on the board has to drop ~4 volts (=9-5) at 50mA or 0.2 watts which is fine for a while, but then the heat builds up, it goes into thermal overload protection, and won't run until it cools down. The 30 minutes seems excessive, as it should cool faster than that, but perhaps you meant 30 seconds? Could be something else.


text:
Can't re-write Arduino Pro Mini
I am just getting started with arduino, but I am having an issue with some 3.3V, 8Mhz Arduino Pro Minis. I am using a SparkFun FT232RL USB to Serial breakout (https://www.sparkfun.com/products/12731) to communicate with the board, using Windows 7 and the Arduino IDE.
The Pro Minis were blank when I got them, I am able to upload a single program (Blink), which runs successfully, but I am unable to upload subsequent programs. I get the error:
avrdude: stk500_recv(): programmer is not responding

Any idea what might be going on?

How is the breakout connected to the Pro Mini?

Do you have auto reset hooked up?   If not and you are manually resetting, I found that activating verbose mode in the IDE makes the timing of pushing reset and hitting upload more forgiving.  Also make sure you have the correct baud rate for the upload, which might be different than for a 5v 16 MHz board.

The breakout is connected via Tx/Rx, GND, and VCC pins in the programming area at the edge of the pro mini. I have set the board to 3.3 8Mhz in the arduino IDE, i'll try hitting the manual reset again

Connect the DTR pin from the FT232 to the Promini as well, that will allow the software autoreset to work. Promini has a 0.1uF cap between the DTR pin and Reset already.


text:
parse intel hex into SPI commands for arduino ICSP AVR
I'm attempting to use the arduino as an ICSP AVR to flash hundreds of ATMEGA's 90USB162.  I'm having some difficulties when trying to do the actual flashing of the chip.  I've go all the wires done properly and I'm able to read the signature.  My source is an Intel hex file and I'm reading it properly as I'm able to see each by as it is read from the arduino's memory.  Where I'm getting lost is the documentation states that I need to set the low byte first before I set the high byte for the same memory address.  Using the following as an example (underscores to break the data up) could someone help me descern what my SPI transaction bytes would look like?
:_20_0000_00_16C100003CC100003AC1000038C1000036C1000034C1000032C1000030C10000_48

I know the colon is the start code, 20 is the hex value of number of data bytes,  0000 is the address, 00 is the record type,  the next 32 bytes is my data followed by the checksum.
I thought that I would loop over the data portion and increment the address every other byte
uint16_t addr = 0;

while (recordtype != endOfFile)
{
  auto data[] = parseData();

  for(uint8_t index = 0; index < 32;)
  {
    SPITask.Send(0x40, 0x00, addr, data[index++]);//send low byte
    SPITask.Send(0x48, 0x00, addr, data[index++]);//send high byte
    SPITask.Send(0x4C, addr, addr, 0x00);//commit new bytes to address
    addr++;
  }
}

I don't think this is right and some examples i'm loosely following comment that they are changing the address byte into a word, which makes some sense based on the command layouts of the data sheet (page 260) 90USB162 Data sheet.  Can anyone please provide some guidance in how to break up this data into high and low bytes.

I have some code that does exactly what you want on GitHub.
Amongst other processors, it supports the At90USB162 chip. The code reads from an SD card in Intel hex format and writes to the chip at the press of a switch. This effectively is what you are trying to do.
Arduino forum moderator "Crossroads" (who has recently also joined Stack Exchange) has made a board to do the programming, hold the SD card, and have some status LEDs:

Here is my code to write to the flash:
// execute one programming instruction ... b1 is command, b2, b3, b4 are arguments
//  processor may return a result on the 4th transfer, this is returned.
byte program (const byte b1, const byte b2 = 0, const byte b3 = 0, const byte b4 = 0)
  {
  noInterrupts ();
  BB_SPITransfer (b1);
  BB_SPITransfer (b2);
  BB_SPITransfer (b3);
  byte b = BB_SPITransfer (b4);
  interrupts ();
  return b;
  } // end of program

// write a byte to the flash memory buffer (ready for committing)
void writeFlash (unsigned long addr, const byte data)
  {
  byte high = (addr & 1) ? 0x08 : 0;  // set if high byte wanted
  addr >>= 1;  // turn into word address
  program (loadProgramMemory | high, 0, lowByte (addr), data);
  } // end of writeFlash

Your loop looks a bit strange, the page size (before you need to commit) is 128 bytes (64 bytes), not 2 bytes.
See the datasheet:

Are these boards available for purchase anywhere?

http://www.crossroadsfencing.com/BobuinoRev17/Programmer.html

Yes, boards are available as noted. I accept payment via paypal and can have one in the mail for you tomorrow. Send me e-mail at robert@crossroadsfencing.com.

(xtreampb  said in a comment under a now-deleted answer): I don't see where it also will flash the EEPROM of the target which is something I also desire with my final product - however this is not mentioned anywhere in the question.


text:
Arduino Reaction LED game
I have this code and it is a reaction light game. When you press the button on pin 11 it starts the game and the lights should osculate back and forth. The main goal is to press the button when it hits the middle led and the osculating will slow down. I cannot get the leds to turn on help?
    int ledPin;
    int direction;
    int isChanging;
    unsigned long lastChange;

void setup() {
   //set pins 2 to 10 to be output
  // and LEDs off
   int pin;
    for (pin = 2; pin <= 10; pin++) {
       pinMode(pin, OUTPUT);
       digitalWrite(pin, LOW);
    }
     //set pin 11 to be input
     pinMode(11, INPUT);

     ledPin = 2;
     direction = 1;
     lastChange = millis();
  }

 void loop() {
    if (isChanging) {
    if (millis() - lastChange > 500) {
        //turn off old LED
        digitalWrite(ledPin, LOW);
        //reset time
        lastChange = millis();
        //change the led
        ledPin = ledPin + direction;
        if (ledPin > 10) {
          direction = -1;
        ledPin = 9;
      } else (ledPin < 2); {
        direction = +1;
        ledPin = 3;
     }

       //turn on new LED
        digitalWrite(ledPin, HIGH);
     }
       //check for button
       if (digitalRead(11)) {
        isChanging = 0;
     }
     }
    else {
       //wait for them to let go of the button
       while (digitalRead(11)) {
     }
       //wait for it to be pressed again
       while (!digitalRead(11)) {
     }
       //wait for them to let go of the button
       while (digitalRead(11)) {
     }
    }
   }`

Are you using an external pullup for your button pin?

Your are not explicitly initializing the variable isChanging, so the compiler sets it to 0. This means, that your code will directly go to the last else statement and cannot at any time reach the LED code, because you are not changing the variable in the else statement.
But I don't really understand, why you were using this variable in the first place. Try to use purely non-blocking code. For checking the button you can do something like this:
boolean button_pressed = false;
unsigned long button_timestamp = 0;

void loop(){
  ...
  if(!button_pressed && digitalRead(11)){
    button_pressed = true;
    button_timestamp = millis();
  }
  if(button_pressed && millis() - button_timestamp > 50){
    if(digitalRead(11)){ // real button press
      button_pressed = false;
      // check, if the middle LED is ON and act accordingly
      // or, if the game hasn't started yet, start it
    } else { // just a bounce of the button, not a real button press
      button_pressed = false;
    }
  }

  // LED CODE
  if (millis() - lastChange > 500) {
    ...
  }
}

Note, that this code will not wait for the button to be released, but reacting, when the button was held down for 50ms. You can change this value, to a one, that is more fitting your used button, but it is a good start point.
Also in your LED code, you have to replace the 500 in the millis statement with a variable, since you want to change the speed.
For handling starting the game with the same button, you can use a state variable, which contains a value of means "Game Stopped" or "Game Started".