body:
Originally, C (from which C++ inherited the bulk of its syntax) was compiled by a single-pass compiler: the compiler only got one look at the code.

A multi-pass compiler could look over the code and collect function definitions in one pass, then in a later pass, compile the code that calls those functions, or detect errors in those calls, if there are any.

A single pass compiler couldn't do that so it needs either the function or its prototype to appear before any code that uses calls it, for the compiler to have that same information when it needs it.

The prototype provides the function's name, the number and types of its arguments, and the type of value it returns, which is what the compiler needs to confirm and compile a function call or to issue a diagnostic message if the call doesn't match the prototype.


sender: user

message:
Is there a test framework for Arduinos?

I'm working on big Arduino project that involves lots proprietary libraries. Ergo, we need test scripts to ensure each library works. Is there a testing framework for Arduino similar to CPPUnit, JUnit, Cunit, etc.? It should preferable also have the ability to simulate an Arduino.

EDIT: By "Arduino Simulator" I only want something that allows observation of local variables, global variables, the different register values (at a minimum the INPUT/OUTPUT status of the pins, what is being inputted or outputted), and fake inputs into the various pins. This way, only the Arduino itself needs to be simulated, not the external hardware components like LEDs, buttons, real time clocks, motors etc.

sender: assistant

body:
> It should preferable also have the ability to simulate an Arduino.

As said in the comments, only simulating the Arduino is mostly not enough, because you would also need to simulate all the connected components. Just simulating the Arduino is a rather hard task. You can find Arduino simulators, but they always only support a rather small collection of additional hardware (mostly things like switches, LEDs, buzzers, ...). I guess the proprietary libraries, that you use, are for connecting to some extra devices (maybe are also proprietary), which will be rather complex. These devices will most likely not be supported by any of the Arduino simulators.

Also: Arduino is a beginner and fast prototyping platform. The ones, that do professional things like designing a product (which are mostly the ones, that need such test suites), will fastly move away from the Arduino platform to program an abstraction layer lower directly on the AVR platform. So why would those people need a test suite for Arduino?

Simulating electronic circuits can be really difficult, so you won't see a program, that can handle all of your circuit, including the complex parts like sensors with communication interface. That means, that you can only test your circuit and the corresponding code (which interacts with the circuit) in the real hardware. Some IDEs (like PlatformIO) might give you the possibility, to write test sketches, but you would still need to upload them to the real hardware and observe the results yourself.

Code, that is independent from the Arduino hardware, could be unit tested on the PC, but that is mostly not the case, since Arduino/microcontrollers are so hardware near. Of course, you could write mocking code for the Arduino parts, but that is often even more tedious, than just using the hardware.

---

As no real Arduino testing framework exists, you are down to writing own testsketches and using a good IDE (not the Arduino IDE) to organize them.


message:
Arduino Nano IoT 33 Char Array size constraints

I would like to save data that I am receiving from API calls in a char array. The problem is the data is around 80KB however my Arduino IoT 33 has 32KB of memory. It will save data in a char array that 25000 bytes however when I go to 30000 or above the Arduino freezes. When I copy-paste the entire data to a char array without specifying the size it works fine, however, when receiving data over API in chunks of 10KB it won't save the entire 80KB. Is there a way to go around this? A response will be appreciated.

body:
You can use the flash memory of the SAMD21 MCU used on the Nano 33 IoT, if you don't write too often. Flash memories have a limited count of write-erase cycles. It is guarantied for 10000 writes.

For Arduino SAMD boards like the Nano 33 IoT you can use the [FlashStorage library][1]. The library is in the Library Manager.

  [1]: https://github.com/cmaglie/FlashStorage


message:
NodeMCU v2 with MH-Z19B CO2 sensor UART read problem

I'm trying to read data from MH-Z19B sensor to NodeMCU v2 board with a simple circuit like this.

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

Some key points, which could be not that obvious from picture:
 - sensor has separate power supply of 4 AAs, providing ~5,5V
 - sensor's TX connected to GPIO15 (TX D2) of NodeMCU
 - sensor's RX connected to GPIO13 (RX D2) of NodeMCU

And here is my sketch:

```
const byte readCommand[] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79}; // according to datasheet
unsigned char response[9];

void setup() {
  // according to datasheet, sensor uses 9600 baud, 8 databits and 1 stopbit
  // with parity NONE, which I believe corresponds to default config SERIAL_8N1
  Serial.begin(9600);
}

void loop() {

    //  ... check if it is time to measure

    Serial.swap(); // switch to sensor

    Serial.write(readCommand, sizeof(readCommand));

    memset(response, 0, sizeof(response));

    int attempts = 5;
    int available = Serial.available();
    while(available < sizeof(response) && attempts > 0) {
        delay(100);
        attempts--;
        available = Serial.available();
    }

    Serial.readBytes(response, sizeof(response));

    Serial.swap(); // switch back to console

    // print out the response in hex
    for (int i = 0; i < sizeof(response); i++) {
      Serial.print(String(response[i], HEX));
      Serial.print("   ");
    }

    // ...process the response according to protocol
}

```

**The Problem**

For some reason after sending command to serial I get an answer exactly the same as command is although the structure of answer expected to be different. Of course datasheet says nothing about situations like this.
Expectation
```
ff 86 .. .. 0 0 0 0 CRC
```
Reality (same bytes I sent as a command)
```
ff   1   86   0   0   0   0   0   79
```

Other notes:
 - I got exactly the same when tried to use `SoftwareSerial` with D1 & D2 pins
 - connecting TX to RX respectively on both sensor and MCU results in reading failure
 - I tried to pull everything while available from serial, there are only my expected 9 bytes
 - my soldering skills are far from ideal, but I'm pretty sure tx/rx on the sensor are connected properly

I'm new to all this stuff, so it is completely possible that there is ridiculously silly, but crucial mistake, so would appreciate any help on this. And I understand that sensor also has additional interfaces to obtain the value, but as I mentioned I'm a newbie and wanted to familiarize myself with UART as this is something new for me.

**UPD 1**:
I didn't use level conversion for sensor output as datasheet says:
[![enter image description here][2]][2]
Assuming this I thought that sensor provides logical level conversion itself. Did I get it wrong?

**UPD 2**:
I got back to proper TX - RX connection just to check out what is going on exactly to describe that "reading failure" problem with more details. It seems that `Serial.available()` returns 0 after I send command so this loop gets stopped after 5 attempts:
```
while(available < sizeof(response) && attempts > 0)
```

  [1]: https://i.stack.imgur.com/42cKt.jpg
  [2]: https://i.stack.imgur.com/qoP7I.png

body:
It says in your description that you have the Rx connected to Rx and the Tx connected to Tx.  That's backwards.  What one transmits the other needs to receive.  When you have a conversation with someone, do you talk into their mouth and listen to their ears?  You should have Rx-Tx and Tx-Rx.

You also need to be sure that it is OK to feed a 5V Tx into that Rx pin.  On some ESP8266 boards it is and on most it isn't.  If you don't have one of the boards that specifically has circuitry built in to handle 5V inputs then you will fry your NodeMCU


message:
How compile an Arduino program for a desktop PC

I have an arduino program that only does serial communications with a little bit of math, and I am writing another one to communicate with it on a second arduino.  For testing purposes I was hoping I could run the serial only program on my desktop.  I know it is possible to run on a raspberry pi but I have never done that.  Can I do something similar on windows?  If not, can anybody recommend the easiest way to do this with a regular C++ program that would require very little editing? Here is a copy of my code if it's helpful.  It basically increments a variable up and down between 0 and 100.

```
int pos = 60;
bool flag=0;
int dly=50;
int vel=0;

const int buttonPin =  12;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);

Serial.begin(115200);
}

void loop() {
    dly=50;
    buttonState = digitalRead(buttonPin);
    if (buttonState==0)dly=12;
    Serial.print(vel); //speed
    Serial.print(",");
    Serial.println(pos); //position
    delay(dly);
    if (pos==30)flag=1;
    if (flag==1) pos+=1;
    if (pos==100)flag=0;
    if (flag==0) pos-=1;
    vel=1000/dly;
    if (flag==0) vel*=-1;

}
```

body:
It depends on what exactly you wanna test. I guess you want to run the "Serial & math only" sketch on the PC, while communicating over Serial (via USB) with the other real Arduino. It can be done, but you would have to change quite a lot. The Serial libraries for a PC are different than for an Arduino. Also you cannot simply compile Arduino code for a PC, they are totally different devices.

Mostly the Serial code is better tested with the real hardware, by checking, what actually is send. You can do this by connecting to the Arduino over Serial/USB with a corresponding program (Arduino Serial Monitor, Putty, ...), so that you can test the functionality by hand. Or write a simple test sketch for the second Arduino.

For testing the math part, you could relatively easy write a so called unit test on the PC. A unit test tests a confined code part without or only with few dependencies. Most math is the same on Arduino and PC (as long as you use variables of the same size and type). So you could put all the math code into a function, which does not contain Arduino specific code, like `Serial` code. Just the math. Then you can copy that function into the source code of a C++ PC programm and use it, to test the math function unit without involving the Arduino.

A further option would be using an Arduino Simulator. But keep in mind, that these simulators can never be as good as the real hardware and you can see differences in the behavior of simulated and real Arduinos. Though it should work, as long as your program is simple and does not rely on too much outer hardware or events. Your current program is simple enough, so that a simulator should be able to work with it.

All in all: Testing your code outside of the real Arduino mostly only makes sense, when you have a complex program, that does not involve Arduino specific code, which would need the hardware to work. If your project is not very complex, you are mostly better off with testing directly with the real hardware.


body:
If you want to run the Arduino sketch on your desktop, you just have to
implement the Arduino core library for your PC.

It may not be as bad as it sounds. If your program makes only minimal
use of the Arduino core, you may implement only the parts you really
need. For example, this partial implementation is enough to run your
program:

```c++
#include <cstdint>
#include <iostream>
#include <unistd.h>  // for usleep()

using std::cout;
using std::endl;

#define INPUT_PULLUP 2

void pinMode(uint8_t, uint8_t) {}

uint8_t digitalRead(uint8_t) { return 0; }

void delay(int t) { usleep(t * 1000UL); }

struct {
    void begin(int) {}
    template<typename T> void print(T x) { cout << x; }
    template<typename T> void println(T x) { cout << x << endl; }
} Serial;

int main()
{
    void setup();
    void loop();
    setup();
    for (;;) loop();
}
```

I tested this on Linux, by simply appending your program right below
this. If you are using Windows, you will have to replace the `usleep()`
function with the appropriate Windows call (and `<unistd.h>` with the
appropriate header). The serial stream goes to the standard output. You
may redirect it to the USB serial port if you wish (trivial to do in
Linux, I assume it should be doable on Windows). You may also want to
replace `digitalRead()` with something that simulates a more realistic
user interaction.

Keep in mind that the sizes of the basic data types can be different on
the Arduino and on the PC. On an AVR-based Arduinos, `int` and pointers
are 16 bits while `long` is 32 bits. This is an “IP16” data model. An
ARM-based Arduino would typically be ILP32, whereas a 64-bit PC is LP64,
unless it runs Windows, in which case it's LLP64. This can make a
difference, especially if some of your calculations are prone to
overflow with the smaller data models.

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

**Edit**: I recently stumbled upon [NCORE, a native core for
Arduino][ncore]. It may be a good fit for what you are trying to do.
From the page description:

> The native core allows you to compile and run Arduino sketches on the
> PC, generally with no modification. It provides native versions of
> standard Arduino functions, and a command-line interpreter to give
> inputs to your sketch that would normally come from the hardware
> itself.

[ncore]: https://github.com/maniacbug/ncore


body:
There is also [arduino_ci](https://github.com/ianfixes/arduino_ci), a framework for running unit tests against an Arduino library (maybe also sketch) on your computer. It contains mock implementations of most Arduino functions and some libraries, and gives the unittest control of things like Serial buffers and I/O pin values.

For your example, you could maybe write a unittest that just use stdin/stdout as a serial port and then connect two of these programs together, or maybe you could generalize your communication code a bit into an object and then instantiate that twice.


message:
Rechargeable USB "AA" Batteries. Has anyone used them?

I have a cosplay project where I'm creating a "Megaman" aka Rockman type of arm cannon (it's actually based on DC's Cyborg). Anyhoo, I've been weighing options like using 3xAA alks or 4xAA nicd (or otherwise 1.2V)--inclcuding various combinations of less or more cells with a voltage regulator; boost up or step down as appropriate.

there are 4 lighted segments (15 leds of WS2812B x 4). I also of course have to power the Arduino Nano as well. I'm flexible on led brightness so I'm just going to tune it [code it] to whatever looks adequate for my purpose. I am aware of the 50ma draw of these units at full brightness

My original plan was to just keep it easy (read lazy) and use 3 AA alks per 2 segments, and another 3 so the nano can have it's own supply. So 9 cells in total (without any additional regulation). Before you judge me--weight, volume, and especially area are definitely big factors in my decision.

So that's a long way to get to my actual question. Has anyone used these new types of USB rechargeable batteries? They seem to have the best of both worlds with the power of an alkaline but the consistency and sustainability of a NiMH /NiCD as they have internal regulators that produce a steady 1.5v (until they don't--which I'm more than cool with)

Short of having a properly regulated 5v power supply, are these a good option if I want to be slightly more responsible than throwing in whatever other AAs I have lying around? They definitely check the box on my space/mass requirements. I'm sure they do fine with most consumer electronics, but as far as arduino and any other custom/hobby 4.5-5v applications how reliable are these? Even if you haven't used them before I'd be curious of your thoughts. I'm a novice at best when it comes to elec engineering.

Yes, they are expensive. Thanks all!

examples:
https://www.amazon.com/Rechargeable-Batteries-Quick-Charge-Integrated-Protection/dp/B07F27PK2M/ref=sr_1_5?crid=1RTQUCZYG4KBM&dchild=1&keywords=usb+aa+batteries+1.5v&qid=1588280164&sprefix=usb+aa,aps,242&sr=8-5

https://www.amazon.com/Blackube-Rechargeable-Batteries-Lithium-1500mAh/dp/B07D9K2H9H/ref=sr_1_11?dchild=1&keywords=usb+aa+batteries+1.5v&qid=1588282813&sr=8-11

body:
Those "batteries" are actually a 3.7V¹ ~750mAh Lithium rechargeable cell with a 1.5V switching regulator and 5V charge circuit built in.

In about the same space as one of those, if you throw away the charge circuit and switching regulator, you can get a single 18650 Lithium rechargeable cell at 3.7V¹ (nominal) and three times the capacity. Two of those plus a small 5V switching regulator² would give you more power capacity and longer run time in a smaller space than the equivalent voltage of these strange "batteries".

----
¹ Nominal

² Use a good one with a Li-Ion battery protection circuit and maybe a built in 2S charger too for convenience


message:
Arduino Turn on a led with the PCA9865

I am using the PCA9865 to light a led

**My circuit** [![enter image description here][1]][1]

**Arduino to PCA9865**
A5 > SLC A4 > SDA 5V > 5V GND > GND and
5 volts from a battery

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

**My code:**

    #include <Wire.h>
    #include <Adafruit_PWMServoDriver.h>

    // called this way, it uses the default address 0x40
    Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

    void setup()
    {
      pwm.begin();
      pwm.setPWMFreq(60);  //~60 Hz updates
    }

    void loop()
    {
      int pin = 0;
      pwm.setPWM(pin, 4096, 0);
    }

**the led does not light**

  [1]: https://i.stack.imgur.com/QgMwO.png
  [2]: https://i.stack.imgur.com/AkRGy.jpg

body:
As written in the comments check resistor/led AND make sure you get power/GND to the terminal on the PCA board as this is needed for powering servos/leds/motors hanging on the board. I use about 10 on my layout and they are fantastic for powering all kind of appliancies. I patched the lib but in your case this is overkill. Instead of

 void setPWM(uint8_t num, uint16_t on, uint16_t off);

you could also try

 void setPin(uint8_t num, uint16_t val, bool invert=false);

but that is not the problem here

**EDIT**

Thanks for the foto now its clear why not. You have to connect A4 (UNO SCA) -  SCA (PCA9865)  AND A5 (UNO SCL) - SCL (PCA9865) see diagram:

[![UNO to PCA9865][1]][1]

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


message:
Backup an ATMEGA16

I have an ATMEGA16 lying around that was in an old robot I'd bought. It was in a socket, so I pulled it out and was thinking of using [this page](url=https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard) to use it with Arduino IDE. Is there a way for me to backup the chip's current state, so as to be able to restore it if I mess up?
I don't have an SPI programmer with me, but I do have a Arduino Uno available at hand

body:
A [detailed how to is here](https://hardwarefun.com/tutorials/use-arduino-as-an-isp-programmer-to-program-non-arduino-avr-microcontrollers) its for the ATMega16 but check connections with the circuit diagram.
[![Flash ATMEGA16 with UNO][1]][1]

Use this command for backup of flash

     avrdude -c avrisp2 -p m16 -P /dev/ttyUSB0 -b 115200 -U flash:r:Old_flash_backup_file.hex:h

Backup EEPROM (just in case there is something stored there)

    avrdude -c avrisp2 -p m16 -P /dev/ttyUSB0 -b 115200 -U eeprom:r:eeprom_backup_file.hex:h

and this for writing the new bootloader / backup back

     avrdude -c avrisp2 -p m16 -P /dev/ttyUSB0 -b 115200 -U flash:w:New_BootLoader.hex:i -v

and this for EEPROM writing back

    avrdude -c avrisp2 -p m16 -P /dev/ttyUSB0 -b 115200 -U eeprom:w:new_eeprom_file.hex:h

As your avr-dude outputis

    lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

there seems to be no lock on the chip. As you are on LINUX when reading youhave tospecify the format :h hex when reading

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


message:
Serial.flush() in arduino

I am new to Arduino and I have the following:

    int     delaynum;
    char    cval[12];

    void setup()
    {
     Serial.begin(9600);
     Serial.print("Enter Number");
     Serial.flush();

     int i=0;
     while(i<12)
     {
      if(Serial.available()>0)
      {
        char ch=Serial.read();
        if(ch>='0'&&ch<='9')
        {
          cval[i]=ch;
          i++;
        }
        else
        {
          cval[i]=0;
          delaynum=atoi(cval);
          break;
        }
      }
     }
    }
    void loop()
    {
       Serial.println(delaynum);
       exit(0);
    }

The code output in virtual bread board:(i Entered 100)

[![Output 1][1]][1]

But when i remove `Serial.flush()` The output like (i Entered 100)

[![Output 2][2]][2]

I am Expecting the output:

Enter Number (I want to enter number 100 after the output)

100

Why the code not working ?

I am using Arduino IDE with virtual bread board(ATMega328p)

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

body:
Not knowing what virtual breadboard does on a normal Arduino it would do the following:

Serial.flush() clears the buffer  and this needs some time normaly you wait minimum for around 100 ms to write/read to that buffer again.
As your code runs in setup (so just once) the serial is not available as its still flushing and so your result.

As the name setup says this should only be used to setup HW/SW but not to run routines as you may get all sorts of weird results.
 If you use "\n" aka newline terminators in your communication you can go for them and flushing would be only necessary if the connection is interrupted and you have to resend data.

**EDIT**

>     Waits for the transmission of outgoing serial data to complete.

If you send a character, it is placed in a buffer for transmission. It takes time for each character to be sent because serial is slow. Once it is in the buffer, it will be sent automatically in the background while the program immediately moves on to the next statement. This is done so the program won't waste time waiting for characters to be sent.

flush() is a way to wait for it to be sent, instead of immediately moving on in the user program.

So after calling flush() you can be sure that all data has been sent, and the buffer is empty. So in your case where you placed it it makes no sense.


message:
how to get esp32 ip address ,which is being connected to local network

I need to know the IP address of ESP32 on the local network(without printing ip on serial monitor ). The idea is to do mDNS or UDP broadcast to send the IP to the android application. The app will then use that IP to do the communication. Is there someone who has already done it?

body:
You don't. You configure mDNS (as you already suggested in your question...!) and the client device then queries mDNS to find the device by the name you allocated it.

Look at the ESPmDNS library examples for how to use mDNS.

Edit: if you really want the IP, you can do `WiFi.localIP()` (station mode) or `WiFi.softAPIP()` (access point mode).


message:
Adafruit Metro Mini FTDI chip overheating

I have an Adafruit Metro Mini board that I am using. After soldering the board and accessories to a perfboard the FTDI chip is overheating, the COM port will not show up on the PC, and the 3V pin does not produce any power while the board is plugged in.

Is there a way to fix this? Have I nuked my board?

body:
> Is there a way to fix this?

Yes. Undo whatever short circuit you have created with your soldering.

> Have I nuked my board?

Possibly, possibly not. Most likely the short is making the regulator go into thermal shutdown and no lasting damage has been caused. But you can't be sure.


body: The 3.3V output of the FTDI chip might be shorted to Gnd, or overloaded by your circuit. Start by checking that.


message:
Problems running Arduino project off a 9V battery

I have been working on an [Arduin Uno Rev2][1] project for a while now. I have been developing using my MacBook, downloading code through the USB jack running it, monitoring the serial output on my MacBook, etc.

The Arduino is being powered from my MacBook through the USB jack which is also carrying the serial output back to the MacBook.

But now I want to make this project portable. IE: instead of powering it off a wire from my Macbook, I want to power it off a battery. So I followed [these instructions #4][2] and connected up a 9V battery to the VIN pin.

At first it seemed to work. But very soon started noticing great instability. There are many serious problems I need to solve working off this battery:

 1. As soon as I connect up the battery, I loose the Serial Monitor connection (even though the USB cable is still connected). So I can no longer see what's going on inside the Arduino for debugging purposes. Why? How can I continue to see the Serial Monitor? Is there a way to see the serial output from somewhere other than the USB jack?
 2. I can tell by the lights on the board and by the behavior of the outputs that the software is malfunctioning. But I can't tell exactly why (because of #1). Why would changing the power source cause this?
 3. I know that the VIN pin needs 7-12 volts. The battery I plugged in is a new 9V battery. But what happens as it wears down? Does it still push 9 volts? Or does the voltage drop? Can I tell my Arduino to stop functioning if the voltage drops below acceptable levels? Because ceasing altogether is better than malfunctioning.
 4. I have read that I need to ensure that the current from the battery remains around 500mA. But how can I measure that in hardware/software? This ties back into question #3.

  [1]: https://store.arduino.cc/usa/arduino-uno-wifi-rev2
  [2]: https://www.technobyte.org/2016/07/power-up-the-arduino-uno/

body:
> As soon as I connect up the battery, I loose the Serial Monitor connection (even though the USB cable is still connected). So I can no longer see what's going on inside the Arduino for debugging purposes. Why? How can I continue to see the Serial Monitor? Is there a way to see the serial output from somewhere other than the USB jack?

Probably because although the voltage is high enough to cut off the power from the USB port it's not got enough current to run the main MCU properly.

> I can tell by the lights on the board and by the behavior of the outputs that the software is malfunctioning. But I can't tell exactly why (because of #1). Why would changing the power source cause this?

Because 9V batteries can't provide enough current.

> I know that the VIN pin needs 7-12 volts. The battery I plugged in is a new 9V battery. But what happens as it wears down? Does it still push 9 volts? Or does the voltage drop? Can I tell my Arduino to stop functioning if the voltage drops below acceptable levels? Because ceasing altogether is better than malfunctioning.

No. The voltage drops rapidly to about 8V then down and down and down until it's below what the regulator can regulate. You can see this curve in any battery datasheet.

> I have read that I need to ensure that the current from the battery remains around 500mA. But how can I measure that in hardware/software? This ties back into question #3.

That's nonsense. The current demands will be whatever the circuit needs at any moment in time. There will be an upper limit to that demand (defined by your circuit and what you are doing at any one time - the *peak* current draw) and your power source has to be able to provide *at least* that amount of current.  If you try to draw more current than the battery can handle then the output voltage will drop to a level where it can no longer power the circuit properly. It is at this point you get "brownouts" and the board resets randomly and strange unpredictable things happen.

**In short: never use a 9V battery for an Arduino project. It's fine for vert low power operations, which take careful design, but for general use stay away from them. Also the Arduino's built-in regulator is a very inefficient and will waste about 25%-40% of a 9V batteries power before you even begin. Instead you should use a more efficient switching regulator to provide 5V directly to the 5V pin (or USB port) from suitable higher capacity batteries (such as AA cells).**

----

As a comparison here's some typical battery discharge graphs comparing alkeline AA to PP3 (9V). These are both Duracell Ultra.

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

As you can see the PP3 drops its voltage very rapidly even under a light load. Under a "heavy" load (what would be considered a very light load to an AA) it tumbles away to next to nothing in no time at all.

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


message:
Pulse generator with varying width

I am trying to generate a square pulse with a fixed delay of 5 second between pulses and varying width of the pulse. The code I wrote so far generates a sequence of pulses every 5 seconds. Is it possible to generate one pulse (with varying width) every 5 seconds instead? Could you please help me with it?

```c++
const int pin =  11;

int i  = 0;

void setup() {
    Serial.begin(9600);
    pinMode(pin, OUTPUT);
}

void loop() {
    i = random(0 , 255);
    analogWrite(pin, i); // turn on LED
    delay(5000);
}
```

body:
Simple but not fully accurate:

- Turn on LED
- Delay for the amount of pulse width (e.g. 20)
- Turn off LED
- Delay 5000 ms - pulse width (20) thus 4980 in this example

However, since turn on/off a LED will also take some time, this will take slightly more than 20 + 4980 = 5000 ms.

Thus better is:

- Set time to a variable (use `millis` function).
- Turn on LED
- Wait until time >= pulse width
- Turn off LED
- Wait until time >= 5000


message:
Individually addressing LEDs in a multiplexed matrix

I have created my first LED project with a hand made 4X4 LED matrix. The cathodes are joined horizontally to make the rows and the anodes are joined vertically to make the columns the columns. It is controlled by a shift register with the cathodes (rows) connected to pins 0-3 and the anodes (columns) connected to pins 4-7 of the register controlled from an Arduino Nano.

It all works but I have hit upon a limitation that I have not seen in the various videos and tutorials about making LED matrices so I suspect I am missing something.

This code will light up the bottom left LED which I will call position (0,0).

    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00011110 );
    digitalWrite(latchPin, HIGH);

This code will light up the LED at position (1,1), so one up and one to the right.

    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00101101 );
    digitalWrite(latchPin, HIGH);

If I then combine the two as below:

    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00111100 );
    digitalWrite(latchPin, HIGH);

it of course lights up 4 LEDs: (0,0),(0,1),(1,0) and (1,1).

This feels like a limitation of wiring the LEDs in this way because once you power a row in a given column, you cannot unpower it in subsequent columns or vice versa. i.e. lighting (X,Y) and (A,B) means that you cannot have (X,B) and (A,Y) unlit.

However, in the videos I have seen that accompany tutorials on how to make similarly constructed matrices, I can see them lighting up in ways I can't replicate.

How can I light up an LED at positions (0,0) and (1,1) without also lighting up (0,1) and (1,0)?

Is this possible with this configuration?

body:
Thanks to [KIIV][1] in the comments I figured it out. Apparently the trick is to rapidly switch between columns or rows without ever having two on at the same time.

With the below code running in the main loop it appears that (0,0) and (1,1) are lit at the same time even though they are actually switching rapidly.

    void loop()
    {
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, B00011110 );
      digitalWrite(latchPin, HIGH);
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, B00101101 );
      digitalWrite(latchPin, HIGH);
    }

  [1]: https://arduino.stackexchange.com/users/23841/kiiv


message:
Securing ESP8266 connections

In my setup, I've got a number of ESP8266 devices around my home controlling various devices like my boiler and some lights.

They're all controlled by a central smart hub on a Raspberry Pi with a static's IP address.

This works great, but I'm increasingly concerned of the security implications of this. Communication between the Pi and the various ESP8266s is currently done over HTTP, with all the commands simply in the URL the Pi requests from the web servers.

As such, anyone on my network could theoretically control these smart devices using a simple `curl` request.

Whilst I have a strong Wi-Fi password, and am using WPA2 encryption, I would feel much more comfortable if communication with the ESP8266s was controlled in some way. E.g. in the same sort of way you can only connect to an SSH server using public key encryption if you have the right private key.

Is something like this possible to implement on an ESP8266? I've done some searching and only found articles about HTTPS which doesn't seem like it would solve my problem.

Thanks in advance,
Rocco

body:
The simplest method is to encrypt your communication channel using some secret key.  You could use the built-in AES encryption functionality, which would mean that only people that know the key could encrypt a request in such a way that the device at the other end could decrypt it.

You would think that SSL (HTTPS) would do the job, but that only provides interception security, not authentication. Of course for even more security you can combine both HTTPS *and* AES encryption.  One for overall encryption, and the other for encryption-based authentication.


message:
Attiny85 SoftwareSerial not working on battery power

I have a very small test project running on an Attiny85 (set to internal 8MHz).

Everything works when powering the circuit from an Arduino (3.3 or 5.0 volt). But when changing the  power to a 18650 battery with a voltage of around 4.0v the Attiny85 still works, because the LED blinks, but nothing is coming through via the UART. What could be the reason for this?

    #include <SendOnlySoftwareSerial.h>
    #define PHOTO_RESISTOR_PIN A1
    #define UART_TX_PIN 0
    #define LED_PIN 1

    SendOnlySoftwareSerial esp(UART_TX_PIN);

    void setup() {
      esp.begin(9600);
      pinMode(PHOTO_RESISTOR_PIN, INPUT);
      pinMode(LED_PIN, OUTPUT);
      pinMode(UART_TX_PIN, OUTPUT);
    }

    void loop() {
      digitalWrite(LED_PIN, HIGH);
      int light = analogRead(PHOTO_RESISTOR_PIN);
      esp.println(light);
      delay(1000);
      digitalWrite(LED_PIN, LOW);
      delay(1000);
    }

[![circuit][1]][1]

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

body:
Unless you connect the ground of your ATTiny to the ground of your USB UART interface there is no circuit for the electrons to flow around.

It works when powered from the computer because everything shared the same ground connection.


message:
MEGA 2560: Simple program - One analogWrite turns off the other

I'm using Windows 10, Arduino 1.8.12 (Windows Store 1.8.33.0)

I have an Arduino MEGA 2560 and a red LED connected to pin 4.

```
#define RED 4
#define GREEN 2

void setup() {
  analogWrite(GREEN,  0);
  analogWrite(RED,  100);
}

void loop() {

}
```
This code lights up the red LED.
[![led on][1]][1]
However, when I write 1 to the GREEN pin `analogWrite(GREEN,  1)`, the red LED goes off. I'm expecting the red LED to stay on.
```

#define RED 4
#define GREEN 2

void setup() {
  analogWrite(GREEN,  1);
  analogWrite(RED,  100);
}

void loop() {

}

```

[![LED off][2]][2]

The red LED stays on when both written values are the same, e.g.
```
  analogWrite(GREEN,  25);
  analogWrite(RED,  25);
```

I also found that adding some "garbage" code at the beginning fixes the issue. I wasn't able to get the garbage into a simpler form without both pins shutting off.
```

#define RED 4
#define GREEN 2

void setup() {
  // GARBAGE BEGIN ===
  unsigned long t = millis();
  const unsigned long period = 10;
  float progress = float(t % period)/period;
  float r = progress * 0;
  // GARBAGE END ===

  analogWrite(GREEN,  100 + r);
  analogWrite(RED,  50 + r);
}

void loop() {

}
```

[![two leds on][3]][3]

**Update:** Thanks all for your comments. Setting the pinMode to output did not fix the issue. However, changing the function declaration to `__attribute__((optimize("-O0"))) void setup() {` fixed the issue. `-O1` also works, but `-O2` fails.

  [1]: https://i.stack.imgur.com/1RJUt.jpg
  [2]: https://i.stack.imgur.com/SStZY.jpg
  [3]: https://i.stack.imgur.com/rleHS.jpg

body:
As you are using using ArduinoIDE >=1.8.10 its an "optimization" problem by the compiler for the Mega try to replace the line

     void setup()

with

     void setup() __attribute__((optimize("-O0")));

// also -O1 works the default -Os and -O3,-O4 not

Actually the problem is not the IDE version but the included AVR boards package version.<br>  You can install any AVR boards package in any IDE with Boards Manager. Last good AVR boards package is 1.6.21. If your compiler (tool chain) shows 7.03 in the output window you  are affected. I have examples where the compiler even optimizies the loop away, which ends in funny results - I dont know wether other boards are also affected but the MEGA is for sure.


message:
Web page using bluetooth?

I have a project where I read 2 sensors using an esp32 and also have an web server. I can connect using mobile phone and display the page where I see info about the sensors (using web sockets to update the info on the page very quickly ) and also send some commands back to esp32. Is working fine, just the issue that when I am connected to esp I don t have internet on my phone anymore (which is a normal thing:) ).
My question is if I can achieve same but using bluetooth instead wifi ? Is there any way to have a "web page" using bluetooth ?
Thank you

body:
No. There is no such facility in Bluetooth to provide such a feature.  That's not to say that technically it can't be done, there just isn't any software (a web browser) that would support it.

Instead you would need to use a Bluetooth-enabled app on the smartphone to communicate with the ESP32 over Bluetooth and display the data / provide control natively.  Such an app would probably have to be written by you since it would be specific to the way you are working, unless you can find a generic app that lets you design an interface for your project and then communicate using a documented protocol that you would then have to implement on the ESP32.

----

An alternative is to just reverse everything. Instead of having your phone connect to the ESP32 then connect to a webserver on it just have the ESp32 connect to your phone when your phone is set to WiFi Hotspot mode. You can still then get your phone to connect to the webserver on the ESP32, and your phone also has mobile internet. If course, if you are wanting internet through a WiFi connection for your phone then you can't do that. However, your ESP32 can then just also connect to your WiFi router so there is nothing to change on your phone. You just browse to the webserver on the ESP32 through your local WiFi network.


body:
Program your ESP32 to connect to your wifi - it then gets its own IP address on your LAN (e.g. 192.168.1.123 ) - then connect to your ESP from your phone (or anything else on your LAN).

Have you tried micropython? Works amazing on esp32 - makes everything super easy


body:
There is an experimental feature called the [Web Bluetooth API][1]. You could host a single file on a Webserver which then interacts via Bluetooth with your ESP. Keep in mind that aside from localhost you have to use https as protocol. [Here][2] is a Tutorial that shows how you can read and write to Bluetooth caracteristics using JavaScript.

  [1]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API
  [2]: https://developer.chrome.com/articles/bluetooth/


message:
An array of existing arrays

I have a bunch of 3D arrays in the following form:

    byte lines[][4][2] {
                         { {B00000000, B11110000 },
                           {B00000000, B11110000 },
                           {B00000000, B11110000 },
                           {B00000000, B11110000 } },
                         { {B11110000, B00000111 },
                           {B00000000, B11111000 },
                           {B00000000, B11111000 },
                           {B00000000, B11111000 } },
    // continues for numerous elements
                        }
They are a bunch of values to push out to a pair of shift registers controlling an LED matrix. Each array is essentially an animation that plays across the LED matrix.

I would like to put my collection of arrays into an array so I can iterate through them. I know I can just combine them into one big array but the code is already opaque and I would at least like to keep separate named arrays so I can sequence and rearrange a series of animations by rearranging a series of named arrays in another array rather than one massive array of opaque binary values.

I want to do something like this

    sometype* sequence[] = { lines, circles, squares } ;
or if that's not possible then:

    sometype* sequence[3];
    sometype[0] = lines;
    sometype[1] = circles;
    sometype[2] = squares;

Can I do this or some approximation thereof? If so what is "sometype"? I can't figure out how to say "an array of pointers to 3d byte arrays" or whatever it is I am trying to do. What is the syntax for deeclaring the array and dereferencing the pointers?

body:
Yes, you can ( both ways )

You need

    typedef byte sometype[4][2];

However, you'll probably need the size of lines, circles, etc. , which is lost by a pointer.

One way might be an end marker (A special element, indicating there are no more)
Another might be a

    struct sometype {
      size_t n;
      byte [][4][2] data;
    } lines ;

IMO, even 2D arrays are reaching the limits of human intelligence, and I'd prefer even more user defined types:

    typedef byte Pattern[4][2]; // or a more appropriate name

    Pattern lineArray[] {
                 { {B00000000, B11110000 },
                   {B00000000, B11110000 },
                   {B00000000, B11110000 },
                   {B00000000, B11110000 } }
              , { {B11110000, B00000111 },
                   {B00000000, B11111000 },
                   {B00000000, B11111000 },
                   {B00000000, B11111000 } }
    };

    typedef struct {
      size_t count;
      Pattern* data;
    } PatternCollection;

    PatternCollection lines = {sizeof(lineArray)/sizeof(Pattern), lineArray };

    PatternCollection sequence[] = {lines /* , circles, squares */ }; // if you ever need to iterate them


body:
Try this:

```c++
byte (*sequence[])[4][2] = { lines, circles, squares } ;
```

**Explanation**: The identifiers `lines`, `circles` and `squares` decay
to pointers to the first element of each array. Their decayed types are
then “pointer to array of length 4 of array of length 2 of byte”. This
type could be declared as

```c++
typedef byte (*pointer_to_2d_array)[4][2];
```

The sequence is then an array of this type, which can be declared as

```c++
pointer_to_2d_array sequence[] = { ... };
```

or, if you appreciate the obscure elegance of the C syntax, as in the
beginning of this answer.


message:
strcat gives error when I try to add a char to a char array

I have

    char c;

where

    int bt_available = Serial2.available();
    if (bt_available) {
      c = Serial2.read();
    }

and later in the code I try to

    strcat(some_char_array, c);

and it gives me this error

> initializing argument 2 of 'char* strcat(char*, const char*)' [-fpermissive]<br>
error: invalid conversion from 'char' to 'const char*' [-fpermissive]

My best guess why the error appears would be that strcat can only accept strings and char arrays, but not single characters, so a solution I can think of would be to create a char array like *char test[1]* where *test[1] = '\0'* and then *test[0] = c* but I'm not sure if that's the best way to go about the problem and if that's a solution. Does 'const char*' mean 'char[]'?

P.S I read Majenko's blog thingy and I'm turning all Strings to char arrays and it's a bit of suffering :P

body:
A `char` is a single character. A `char *` and a `char[]` are both arrays of characters (more correctly `char *` is a pointer to an array of characters).

`strcat` expects two arrays or pointers to arrays of characters. If you want to add a single character you can either fool the compiler into thinking that the character is an array of characters of size 1 (but it lacks the required NULL termination) or manually manipulate the target array.

For the former you could use `strncat` and casting:

    strcat(some_char_array, &c, 1);

That gives you a pointer to the character, which is as far as the compiler is concerned, indistinguishable to a pointer to an array of characters. You use the "n" variant of strcat  to limit it  to just one character (plus an added NULL character) so it doesn't rely on the missing NULL termination.

For the second you could do:

    int n = strlen(some_char_array);
    some_char_array[n] = c;
    some_char_array[n+1] = 0;

That just sets the Nth character in the target array to whatever is in c, then adds a new NULL termination character to the end.


message:
Serial communication arduino mega and D1 Wemos Mini

Can anyone help me connecting arduino mega to D1 Wemos Mini serially? Please let me know most efficient and easy steps to setup a communication.

Using that following tutorial:

https://engineeringprojectshub.com/serial-communication-between-nodemcu-and-arduino/amp/

Following is the circuit diagram:
https://i.stack.imgur.com/oOKwL.png

body:
Apart from ensuring you're wiring TX -> RX and connecting all grounds, you can use [SerialTransfer.h][1] to automatically packetize and parse your data for inter-Arduino communication without the headace. The library is installable through the Arduino IDE and includes many examples.

Here are the library's features:

> This library:
>
>  - can be downloaded via the Arduino IDE's Libraries Manager (search "SerialTransfer.h")
>  - works with "software-serial" libraries
>  - is non blocking
>  - uses packet delimiters
>  - uses consistent overhead byte stuffing
>  - uses CRC-8 (Polynomial 0x9B with lookup table)
>  - allows the use of dynamically sized packets (packets can have payload lengths anywhere from 1 to 254 bytes)
>  - can transfer bytes, ints, floats, and even structs!!

Example TX Arduino Sketch:

    #include "SerialTransfer.h"

    SerialTransfer myTransfer;

    void setup()
    {
      Serial.begin(115200);
      Serial1.begin(115200);
      myTransfer.begin(Serial1);
    }

    void loop()
    {
      char buff[] = "hi";

      myTransfer.txObj(buff, sizeof(buff));
      myTransfer.sendData(sizeof(buff));
      delay(100);
    }

Example RX Arduino Sketch:

    #include "SerialTransfer.h"

    SerialTransfer myTransfer;

    void setup()
    {
      Serial.begin(115200);
      Serial1.begin(115200);
      myTransfer.begin(Serial1);
    }

    void loop()
    {
      if(myTransfer.available())
      {
        char buff[40];

        myTransfer.rxObj(buff, sizeof(buff));

        Serial.println("New Data: ");
        Serial.write(buff, sizeof(buff));
        Serial.println();
      }
      else if(myTransfer.status < 0)
      {
        Serial.print("ERROR: ");

        if(myTransfer.status == -1)
          Serial.println(F("CRC_ERROR"));
        else if(myTransfer.status == -2)
          Serial.println(F("PAYLOAD_ERROR"));
        else if(myTransfer.status == -3)
          Serial.println(F("STOP_BYTE_ERROR"));
      }
    }

  [1]: https://github.com/PowerBroker2/SerialTransfer


message:
How to create and edit fonts for the Adafruit GFX library?

I noticed that the TomThumb.h font included in the Adafruit GFX library has characters that have different widths, which is a problem for me because I'm doing text processing that requires characters to have the same dimensions (width and height). I also noticed that the TomThumb.h font misses some characters (such as ') and so on. I need a way to create/edit fonts for the Adafruit GFX (where I'm using the Adafruit_ST7735 on a 1.8" TFT Display). I've looked around the internet but I couldn't find anything decent.

body:
One possible solution you might already have: There’s a small utility called `fontconvert` that’s part of the Adafruit GFX library. The source code is installed by default together with the Adafruit GFX library in `Arduino/libraries/Adafruit_GFX_Library/fontconvert` You need Linux to compile it from the provided source code. It also compiles and runs on a Raspberry Pi.

It takes care of converting TrueType fonts (completely or partially) to Adafruit GFX format. There’s some documentation on compiling and using it in the fontconvert directory.


body:
I found an online editor that can parse Adafruit GFX font headers, modify, and export the result to create a new font header.  It works very well.  May be a bit late to help OP, but for anyone else looking...

It uses regexes to extract info from the header files, so it's pretty strict on following the layout of GFX font headers provided by Adafruit.

webpage: https://tchapi.github.io/Adafruit-GFX-Font-Customiser/
github: https://github.com/tchapi/Adafruit-GFX-Font-Customiser


body:
I have used this website to generate various fonts, sizes, etc. with success.

http://oleddisplay.squix.ch/#/home


message:
Large number into variable

Probably something easy but I’ve not resolved it.

I’m extracting data from a JSON string and all the values are correct accept for two.

They are referring to two date time values and are in milliseconds.

One is the date refreshed and the other is date updated.

Problem is they are both very large and I’m having difficulty assigning them in the IDE.

One is 1588447162117 which is showing as 020-05-02 20:19:53.948  on the dashboard using the JSON.

Here is the code I have thus far to get the data from JSON:

    #include <ArduinoJson.h>

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

      const char* input = "{TotalCases:3308678,TotalCasesToday:4458,TotalDeaths:234123,TotalDeathsToday:293,TotalRecovered:1042991,TotalTerritories:124,CurrentUpdatedMS:1588312648603,CurrentChangedMS:1588312648603}";

      StaticJsonDocument<512> doc;

      DeserializationError err = deserializeJson(doc, input);

      if (err) {
        Serial.print("Error: ");
        Serial.println(err.c_str());
        return;
      }

      unsigned long TotalCases = doc["TotalCases"];
      unsigned long TotalCasesToday = doc["TotalCasesToday"];
      unsigned long TotalDeaths = doc["TotalDeaths"];
      unsigned long TotalDeathsToday = doc["TotalDeathsToday"];
      unsigned long TotalRecovered = doc["TotalRecovered"];
      unsigned long TotalTerritories = doc["TotalTerritories"];
      unsigned long CurrentUpdatedMS = doc["CurrentUpdatedMS"];
      unsigned long CurrentChangedMS = doc["CurrentChangedMS"];

      Serial.print("Total Cases: ");
      Serial.println(TotalCases);
      Serial.print("Total Cases Today: ");
      Serial.println(TotalCasesToday);
      Serial.print("Total Deaths: ");
      Serial.println(TotalDeaths);
      Serial.print("Total Deaths Today: ");
      Serial.println(TotalDeathsToday);
      Serial.print("Total Recovered: ");
      Serial.println(TotalRecovered);
      Serial.print("Total Territories: ");
      Serial.println(TotalTerritories);
      Serial.print("Update time in ms:");
      Serial.println(CurrentUpdatedMS);
      Serial.print("Change time in ms:");
      Serial.print(CurrentChangedMS);
    }

    void loop()
    {

    }

    **Serial monitor output**

    Total Cases: 3308678
    Total Cases Today: 4458
    Total Deaths: 234123
    Total Deaths Today: 293
    Total Recovered: 1042991
    Total Territories: 124
    Update time in ms:0
    Change time in ms:0

Should be good to manipulate it once I can work with it in a variable.

Thanks for any input,

Shane

body:
I didn't try myself, but just by looking at the docs I suggest you try:

1. Adding
   ```c++
   #define ARDUINOJSON_USE_LONG_LONG 1
   ```
   at the top of the sketch, before including ArduinoJson.h.

2. Declare `CurrentUpdatedMS` and `CurrentUpdatedMS` as either
   `unsigned long long` or `uint64_t`.

**Edit**: To answer the question in the comment:

> When you said you looked at the docs where did you check?

I had to follow a (not so simple) path: [Deserialization tutorial][1] →
[JsonDocument::operator[]][2] → [JsonVariant][3] →
[JsonVariant::as<T>()][4]. This last page states that the method
`as<unsigned long long>()` “may require ARDUINOJSON\_USE\_LONG\_LONG”.
Unfortunately, the macro is not linked, so I have to search for it and
found [`ARDUINOJSON_USE_LONG_LONG`][5].

[1]: https://arduinojson.org/v6/doc/deserialization/
[2]: https://arduinojson.org/v6/api/jsondocument/subscript/
[3]: https://arduinojson.org/v6/api/jsonvariant/
[4]: https://arduinojson.org/v6/api/jsonvariant/as/
[5]: https://arduinojson.org/v6/api/config/use_long_long/


message:
How long does my digital pulse need to be for it to be read?

I have the following really simple code. On every iteration it'll read the first pin, and if it's high - do some serial IO. Then do the same with the second pin. Nice and simple, works during my tests.

My concern is that (in production), the digital pulse I'm receiving (and trying to mimic during testing) would be too quick for the arduino to read. So, for example, the race condition could be:

 1. *First pin is low* Read first pin - result is low.
 2. *First pin is now high* Read second pin - result is low.
 3. *Fist pin now low again* Read first pin - result is low again (missed the 'high')

How much of an 'edge case' is this? Am I worrying about something that's likely to be a non-issue here? In production, each single pulse would represent a significant amount of product (I multiply it elsewhere) - so even skipping one could throw my data off.

    boolean count1High = false;
    boolean count2High = false;
    int count1 = 7;
    int count2 = 8;
    int a = 1;
    void setup() {
      pinMode(count1, INPUT);
      pinMode(count2, INPUT);
      Serial.begin(9600);
    }

    void loop()
    {
      if (digitalRead(count1) == HIGH)
      {
        if (!count1High)
        {
          count1High = true;
          a++;
          Serial.println(a);
        }
      }
      else
      {
        count1High = false;
      }

      if (digitalRead(count2) == HIGH)
      {
        if (!count2High)
        {
          count2High = true;
          a++;
          Serial.println(a);
        }
      }
      else
      {
        count2High = false;
      }
    }

EDIT:
------

I know best approach here might be to attach an interrupt but I've been advised to avoid serial IO from within interrupts, I don't see an alternative here.

body:
This is exactly the reason interrupts were invented. They can respond a lot faster than a simple digital read. By "a lot" I mean orders of magnitude.

When an interrupt is triggered your interrupt handler for that interrupt executes. If another interrupt occurs whilst your interrupt handler is running the interrupt controller remembers it and the interrupt handler for that interrupt will execute as soon as the previous one is finished.

So you won't miss that pulse while the other pulse is processing.

However note that you shouldn't use Serial in interrupts, since Serial itself uses an interrupt internally to control the transmission, so transmission can't happen properly if your interrupt is already running. So instead your interrupt routine should just set a flag which you then check for in your main loop. You then benefit from the ability to notice a pulse while processing another pulse and still be able to use Serial. In fact, if you arrange it right, you can recognise and remember a pulse on the *same* input as the one you're currently processing.


body:
**It depends** where the signal comes from and on other code in your sketch.

Typically, a sketch is rather way too fast for a mechanical switch, and you have to debounce it.

If your fear to lose events is _realistic_, interrupts are the way to go. But an ISR is some very special code: You won't do more than collect the information that there was an event. And you have to assert your main sketch won't interfere with the ISR.


body:
As explained by Majenko's answer, you should detect the pulses from an
interrupt and print the result from the regular code. However, instead
of just setting a flag in the interrupt handler, I suggest you instead
_count_ the pulses within the handler. This will make the handler a tiny
bit slower, which is often something you want to avoid. However, the
extra overhead is really tiny, and you gain the ability to count
not only pulses that are short but also pulses that are closely spaced.

There is, however, something to be aware of when sharing a variable
between interrupt code and regular code. If the variable cannot be read
in a single CPU instruction (which is the case of an `int` on an
AVR-based board), there is some risk that the value gets changed in the
middle of you reading it. To void this problem, you have to disable
interrupts when reading the variable from regular code.

Here is an implementation of this strategy highlighting this point:

```c++
const uint8_t intPin1 = 2;
const uint8_t intPin2 = 3;

// This is volatile because it is shared between interrupt context
// and regular code.
volatile unsigned int sharedCount = 0;

// Interrupt handler.
void countPulse() { sharedCount++; }

// A variable shared with interrupt context should be accessed from
// regular code with interrupts disabled, in order to avoid race
// conditions.
unsigned int getCount() {
    noInterrupts();
    unsigned int countCopy = sharedCount;
    interrupts();
    return countCopy;
}

void setup() {
    pinMode(intPin1, INPUT);
    pinMode(intPin2, INPUT);
    attachInterrupt(digitalPinToInterrupt(intPin1), countPulse, RISING);
    attachInterrupt(digitalPinToInterrupt(intPin2), countPulse, RISING);
    Serial.begin(9600);
}

void loop() {
    static unsigned int previousCount = 0;
    unsigned int count = getCount();
    if (count != previousCount) {
        Serial.println(count);
        previousCount = count;
    }
}
```

Note that if the pulses come very fast, you may miss _printing_ the
value, but you will not miss _counting_ it (up to some limit, of
course). Thus you may see non-consecutive numbers being printed.


message:
NodeMCU V3 and MPU6050 strange values

I am new to this platform, so please if I do something against the regular rules please let me know so I can learn.
Now my problem: I have a nodeMCU V3 connected to a MPU6050. Using my Arduino Uno I do get sensible values in the order of 0 degrees when the device is flat. Using the same code and the same setup I get very strange values in the order of 45 degrees when the device is flat. I have tried the following:

 1. Using the I2C scanner I do get a valid address.
 2. Testing with the Arduino Uno the values are correct.
 3. The GY 521 breakout uses 3V3 datalines with 2k2 pull ups. Datalines are short. Eg on the same breadboard.
 4. The GY 521 has a voltage regulator on board for 5V, so I feed the device with 5V in order to overcome a voltage drop problem.
 5. I have tried to stretch the stretchClock function but no luck.

I have read about people with a similar kind of issue, but I could not find a solution. Anyone that can help me?
Apoligies. It would be more handy to attach my code:
''
/*
 * I2C example sketch for ESP8266
 */

    #include <Wire.h>

    const int DevID = 0x68;
    const int PWR_MGT1_REG = 0x6B;

    const int DataReg_AX = 0x3B;
    const int DataReg_AY = 0x3D;
    const int DataReg_AZ = 0x3F;
    const int AccConfigReg = 0x1C;
    const int GyrConfigReg = 0x1B;
    const int SelfTestReg = 0x0D;

    const int TempReg = 0x41;

    const int DataReg_GX = 0x43;
    const int DataReg_GY = 0x45;
    const int DataReg_GZ = 0x47;

    const int CalibrationConfigAcc = 0xF0;//set this value for calibration
    const int CalibrationConfigGyr = 0xE0;//set this value for calibration
    const int NormalConfigAcc = 0x00;//set this value for calibration 2G
    const int NormalConfigGyr = 0x00;//set this value for calibration 250dps

    /*
      int16_t Acc_X;
      int16_t Acc_Y;
      int16_t Acc_Z;
    */
    float Acc_X, accAngleX, accAngleY, Yaw_Angle;
    float Acc_Y;
    float Acc_Z;

    //double Acc_X, accAngleX, accAngleY, Yaw_Angle;
    //double Acc_Y;
    //double Acc_Z;

    int8_t X_selfTest;
    int8_t Y_selfTest;
    int8_t Z_selfTest;
    int8_t Acc_X_Y_Z_selfTest;

    int16_t Temp;
    /*
      int16_t Gyro_X;
      int16_t Gyro_Y;
      int16_t Gyro_Z;
    */
    float Gyro_X;
    float Gyro_Y;
    float Gyro_Z;

    int16_t Gyro_X_selfTest;
    int16_t Gyro_Y_selfTest;
    int16_t Gyro_Z_selfTest;

    //int SDApin = 3;//create I2C pinouts for ESP8266;
    //int SCLpin = 4;

    unsigned long elapsedTime, previousTime, currentTime;

    void setup() {// put your setup code here, to run once:
      Serial.begin(115200);
      Wire.begin ();
     // Wire.setClock(400000);
    //  Wire.setClockStretchLimit(40000);
      Wire.beginTransmission(DevID);
      Wire.write(PWR_MGT1_REG);
      Wire.write(0x0);// wake up the sensor
      Wire.endTransmission();
      CalibrationProcedure();// enter calibration procedure
    }

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

    previousTime = currentTime;
    currentTime = millis();
     elapsedTime = (currentTime - previousTime) / 1000;

      Wire.beginTransmission(DevID);
      Wire.write(DataReg_AX);
      Wire.endTransmission();

      Wire.requestFrom(DevID, 14);
      if (Wire.available() == 14) {
        Acc_X = ((Wire.read() << 8) | (Wire.read())) / 16384.0;// divide by 16384 for 2G setting according to datasheet
        Acc_Y = ((Wire.read() << 8) | (Wire.read())) / 16384.0;
        Acc_Z = ((Wire.read() << 8) | (Wire.read())) / 16384.0;
        Temp = (Wire.read() << 8) | (Wire.read());
        Gyro_X = ((Wire.read() << 8) | (Wire.read()))  / 131.0; // divide by 131.0 according to datasheet for setting 250 dps
        Gyro_Y = ((Wire.read() << 8) | (Wire.read())) / 131.0;
        Gyro_Z = ((Wire.read() << 8) | (Wire.read())) / 131.0;
        delay(500);
      }

      //The formulas below have been extracted from another program and uses mathematical
      //values for calulation of pitch roll and yaw. For the moment only pitch is calibrated
      //The next purpose of this program is follow a calibration procedure to take approx 200 samples
      //and average the total value to correct the pitch roll and yaw value
      accAngleX = (atan(Acc_Y / sqrt(pow(Acc_X, 2) + pow(Acc_Z, 2))) * 180 / PI);
      accAngleY = (atan(-1 * Acc_X / sqrt(pow(Acc_Y, 2) + pow(Acc_Z, 2))) * 180 / PI);
      Yaw_Angle = Yaw_Angle + Gyro_Z * elapsedTime;

      float Gyro_X_axis = (float)Gyro_X / 131.0;
      float Gyro_Y_axis = (float)Gyro_Y / 131.0;
      float Gyro_Z_axis = (float)Gyro_Z / 131.0;
      float Temperature = (Temp / (340.0)) + 36.53;
      //Serial.print(" Accelero X \t" );
      //Serial.print(Acc_X);
      //Serial.print(" Accelero Y \t" );
      //Serial.print(Acc_Y);
      //Serial.print(" Accelero Z \t");
      //Serial.print(Acc_Z);
      //Serial.println("");
      //Serial.print(" Gyro X \t" );
      //Serial.print(Gyro_X);
      //Serial.print(" Gyro Y \t" );
      //Serial.print(Gyro_Y);
      //Serial.print(" Gyro Z \t");
      //Serial.print(Gyro_Z);
      //Serial.print(" Temperature \t");
      //Serial.println(Temperature);
      //Serial.println(Temp);
      Serial.println ("Angle X");
      Serial.println(accAngleX);
      Serial.println ("Angle Y");
      Serial.println (accAngleY);
      Serial.println("Yaw Angle");
      Serial.println(Yaw_Angle);
      delay(500);
    }

    void CalibrationProcedure() {
      Serial.println("Keep sensor steady until calibration process is complete!");
      Wire.beginTransmission(DevID);
      Wire.write(AccConfigReg);//8 g
      Wire.write(CalibrationConfigAcc);
      Wire.endTransmission();
      delay(250);
      Wire.beginTransmission(DevID);
      Wire.write(GyrConfigReg);
      Wire.write(CalibrationConfigGyr);//250 deg/s
      Wire.endTransmission();
      delay(500);
      Serial.println("Selftest enabled, reading data...");

      Wire.beginTransmission(DevID);
      Wire.write(SelfTestReg);
      Wire.endTransmission();

      Wire.requestFrom(DevID, 4);
      if (Wire.available() <= 4) {
        X_selfTest = Wire.read();
        Y_selfTest = Wire.read();
        Z_selfTest =  Wire.read();
        Acc_X_Y_Z_selfTest = Wire.read();
        delay(500);
      }

      //extracting factory trim values after self test
      //unsigned integers for accelero variables
      uint8_t XA_selfTest;
      uint8_t YA_selfTest;
      uint8_t ZA_selfTest;
      //unsigned integers for gyro variables
      uint8_t GX_selfTest;
      uint8_t GY_selfTest;
      uint8_t GZ_selfTest;
      //Factory Trim variables
      float FTGX;
      float FTGY;
      float FTGZ;
      float FTAX;
      float FTAY;
      float FTAZ;

      float SelfTestPercentage_GX;
      float SelfTestPercentage_GY;
      float SelfTestPercentage_GZ;
      float SelfTestPercentage_AX;
      float SelfTestPercentage_AY;
      float SelfTestPercentage_AZ;

      GX_selfTest = X_selfTest & 0x1F; // 0x1F is a bit mask to extract the first 5 bits. unsigned format
      GY_selfTest = Y_selfTest & 0x1F;
      GZ_selfTest = Z_selfTest & 0x1F;
      XA_selfTest = (X_selfTest >> 3) | (Acc_X_Y_Z_selfTest & 0x30) >> 4; //shift the first 3 bits and extract bits with a mask depending on the LSB postion in the last received mixed byte
      YA_selfTest = (Y_selfTest >> 3) | (Acc_X_Y_Z_selfTest & 0x0C) >> 2;
      ZA_selfTest = (Z_selfTest >> 3) | (Acc_X_Y_Z_selfTest & 0x03);

      Serial.println ("XA_selfTest");
      Serial.println (X_selfTest, HEX);
      Serial.println("YA_selfTest");
      Serial.println(Y_selfTest, HEX);
      Serial.println("ZA_selfTest");
      Serial.println(Z_selfTest, HEX);
      Serial.println("Acc_X_Y_Z_selfTest");
      Serial.println(Acc_X_Y_Z_selfTest, HEX);

      //calculate the factory trim settings
      FTGX = (25.0 * 131.0) * (pow(1.046, ((float)GX_selfTest - 1.0)));// Factortrim Gyro X
      FTGY = (-25.0 * 131.0) * (pow(1.046, ((float)GY_selfTest - 1.0)));// Factortrim Gyro Y
      FTGZ = (25.0 * 131.0) * (pow(1.046, ((float)GZ_selfTest - 1.0)));// Factortrim Gyro Z
      FTAX = (4096.0 * 0.34) * (pow((0.92 / 0.34), (((float)XA_selfTest - 1.0) / 30.0)));
      FTAY = (4096.0 * 0.34) * (pow((0.92 / 0.34), (((float)YA_selfTest - 1.0) / 30.0)));
      FTAZ = (4096.0 * 0.34) * (pow((0.92 / 0.34), (((float)ZA_selfTest - 1.0) / 30.0)));
      Serial.println("Selftest ended...please copy data");
      Serial.println(" GX trim value\t" );
      Serial.println(FTGX);
      Serial.println(" GY trim value\t" );
      Serial.println(FTGY);
      Serial.println(" GZ trim value\t");
      Serial.println(FTGZ);
      Serial.println(" AX trim value\t" );
      Serial.println(FTAX);
      Serial.println(" AY trim value\t" );
      Serial.println(FTAY);
      Serial.println(" AZ trim value\t");
      Serial.println(FTAZ);
      SelfTestPercentage_GX = 100.0 + 100.0 * ((float)GX_selfTest - FTGX) / FTGX;
      Serial.println("SelfTestPercentage");
      Serial.println(SelfTestPercentage_GX);
      SelfTestPercentage_GY = 100.0 + 100.0 * ((float)GY_selfTest - FTGY) / FTGY;
      Serial.println("SelfTestPercentage");
      Serial.println(SelfTestPercentage_GY);
      SelfTestPercentage_GZ = 100.0 + 100.0 * ((float)GZ_selfTest - FTGZ) / FTGZ;
      Serial.println("SelfTestPercentage");
      Serial.println(SelfTestPercentage_GZ);
      SelfTestPercentage_AX = 100.0 + 100.0 * ((float)XA_selfTest - FTAX) / FTAX;
      Serial.println("SelfTestPercentage Acclero x, y, z");
      Serial.println(SelfTestPercentage_AX);
      SelfTestPercentage_AY = 100.0 + 100.0 * ((float)YA_selfTest - FTAY) / FTAY;
      Serial.println("SelfTestPercentage Acclero x, y, z");
      Serial.println(SelfTestPercentage_AY);
      SelfTestPercentage_AZ = 100.0 + 100.0 * ((float)ZA_selfTest - FTAZ) / FTAZ;
      Serial.println("SelfTestPercentage Acclero x, y, z");
      Serial.println(SelfTestPercentage_AZ);

      // get data outputs with self test enabled
      Wire.beginTransmission(DevID);
      Wire.write(DataReg_AX);
      Wire.endTransmission();

      Wire.requestFrom(DevID, 14);
      if (Wire.available() <= 14) {
        Acc_X = (Wire.read() << 8) | (Wire.read());
        Acc_Y = (Wire.read() << 8) | (Wire.read());
        Acc_Z = (Wire.read() << 8) | (Wire.read());
        Temp = (Wire.read() << 8) | (Wire.read());
        Gyro_X = (Wire.read() << 8) | (Wire.read());
        Gyro_Y = (Wire.read() << 8) | (Wire.read());
        Gyro_Z = (Wire.read() << 8) | (Wire.read());
        delay(500);
      }
      //print values with self test enabled
      Serial.println("Self test enabled values");
      Serial.println(" Accelero X " );
      Serial.println(Acc_X);
      Serial.println(" Accelero Y " );
      Serial.println(Acc_Y);
      Serial.println(" Accelero Z ");
      Serial.println(Acc_Z);
      Serial.println(" Gyro X " );
      Serial.println(Gyro_X);
      Serial.println(" Gyro Y " );
      Serial.println(Gyro_Y);
      Serial.println(" Gyro Z ");
      Serial.println(Gyro_Z);
      delay(500);

      //setup the device for normal OPS
      Wire.beginTransmission(DevID);
      Wire.write(AccConfigReg);
      Wire.write(NormalConfigAcc);
      Wire.endTransmission();
      delay(50);
      Wire.beginTransmission(DevID);
      Wire.write(GyrConfigReg);
      Wire.write(NormalConfigGyr);
      Wire.endTransmission();
      delay(50);

      //request data with self test not enabled
      Wire.beginTransmission(DevID);
      Wire.write(DataReg_AX);
      Wire.endTransmission();

      Wire.requestFrom(DevID, 14);
      if (Wire.available() <= 14) {
        Acc_X = (Wire.read() << 8) | (Wire.read());
        Acc_Y = (Wire.read() << 8) | (Wire.read());
        Acc_Z = (Wire.read() << 8) | (Wire.read());
        Temp = (Wire.read() << 8) | (Wire.read());
        Gyro_X = (Wire.read() << 8) | (Wire.read());
        Gyro_Y = (Wire.read() << 8) | (Wire.read());
        Gyro_Z = (Wire.read() << 8) | (Wire.read());
        delay(500);
        //print values with self test not enabled
        Serial.println("Self test not enabled values");
        Serial.println(" Accelero X " );
        Serial.println(Acc_X);
        Serial.println(" Accelero Y " );
        Serial.println(Acc_Y);
        Serial.println(" Accelero Z ");
        Serial.println(Acc_Z);
        Serial.println(" Gyro X " );
        Serial.println(Gyro_X);
        Serial.println(" Gyro Y " );
        Serial.println(Gyro_Y);
        Serial.println(" Gyro Z ");
        Serial.println(Gyro_Z);
        delay(5000);
      }
    }
    '''

body:
I had the same issue sometime back.I was able to get good results using the example given for the ESP8266 in the MPU6050 library itself.You can make the necessary changes starting from that sketch.Hope this helps.

Heres the github link to the library [https://github.com/ElectronicCats/mpu6050][1]

  [1]: https://github.com/ElectronicCats/mpu6050


message:
Using RST pin as external power switch

I have Arduino Nano with powered over USB. I have the request for external (physical) slide switch acting as power on/off for Arduino even if USB is always connected.

Looking at documentation and various posts, it seems the RST button could do just that. So when the "power" switch is on, RST is disconnected (= pulled high) and everything runs like normal. When the "power" switch is switched, it will pull RST low. As long as RST is pulled low, the board is stopped (the PWR led is lit, which is true and okay). Once released, the board will boot again.

Even though I agree this is not terribly elegant, is it going to work? I tried manually with the reset switch. Any side-effects I am overlooking?

body:
That is a perfectly legitimate use of the RESET pin. Holding the chip in reset perfectly valid. Everything in the chip will be stopped.

Releasing it will start your sketch from the start again perfectly fine.

The only negative point is that your switch will be pulling power through the reset pin's pullup resistor, so will waste a little power.


message:
Scrolling an I2C text

I want tried to make a programm to display a text on an I2C LCD-Display.
The text should be scrolled for one position every time the function is called.

On the internet I saw a lot of solutions but there were all diffrent from what I need.

So I tried to make my own code.
The code works well except of the part where I try to scroll in the Text from the left.

```#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 16, 2);

char Str[12] = {'T', 'r', 'u', 'e', 't', 'z', 's', 'c', 'h', 'l', 'e', 'r'};
int pos = 0;
int posretry = 0;
bool ledon = false;

void setup()
{
  pinMode(13, OUTPUT);

  lcd.init();
  lcd.backlight(); //lcd.noBacklight();
}

void scroll()
{
  for (int i = 0; i < 12; i++)
  {
    //Print text
    lcd.setCursor(i + pos, 0);
    lcd.print(Str[i]);

    //Move in text from the left

    if (pos >= 6)
    {
      lcd.setCursor(i + pos, 0);
      lcd.print(Str[i]);

      lcd.setCursor(posretry, 0);
      lcd.print(Str[11 - posretry]);

      posretry++;
    }
  }
  delay(500);
  lcd.clear();

  pos++;
}

void changeled()
{
  if (ledon == false)
  {
    digitalWrite(13, LOW);
  }
  else
  {
    digitalWrite(13, HIGH);
  }

  ledon = !ledon;
}

void loop()
{
  scroll();
  changeled();  //Example Event
}
```

The goal is to move the text to the right and show the not displayed letters on the left.

Example:

```
|er    Truetzschl|  -->
|                |
```

A Video about the error can be found here:
https://data.jonas-heinze.de/shares/stackexchange/lcd/

Thanks for your help.

body:
You do some strange things that I, at least, don't understand (e.g. I don't see what you need `posretry` for), but you might have a reason for doing so.
But you don't reset `posretry` and `pos`, which means they will very soon be out of a reasonable range. At some point the `int` will actually overflow to negative values, which is definitely not going to work!

To make it less complicate, you should write a function that prints the char array shifted by a desired value as a beginning.

The below code is completely untested as I don't have your hardware and I'm aware that it does not include all your desired features. But it should give you an idea of how scrolling can be implemented **in principle** and it's up to you to improve/fix it.

    #define LCD_SIZE 16
    #define STR_LEN 12
    char str_to_print[STR_LEN]={'T', 'r', 'u', 'e', 't', 'z', 's', 'c', 'h', 'l', 'e', 'r'};

    void print_scrolled (uint8_t scrolled_by) {
      for (uint8_t i=0;i<LCD_SIZE;i++) {
        lcd.set_cursor(i,0);
        if (scrolled_by>=LCD_SIZE) scrolled_by=0;

        if (scrolled_by<STR_SIZE) lcd.print(str_to_print[scrolled_by]);
        else lcd.print(' ');
        scrolled_by++;
      }
    }

You could call it like this:

    for (uint8_t i=0;i<STR_LEN;i++) {
      print_scrolled(i);
      delay(500);
    }

Once you are familiar with my approach you should be able to enhance it with additional features (end of text coming in from the other side, spaces between end and beginning, etc).


message:
Data transmission rate of accelerometer mpu6050 to arduino uno vs Sampling rate of mpu6050

mpu6050 has sampling frequency of 1kHz (mentioned in datasheet). But when i interface it with arduino uno via I2C communication (400Khz bus speed), i only get 50 raw data (each of x,y,z). There is no delay in the program. why is this happening. Why am I not getting 1000 or at least 800 samples. What is the concept I am missing here. Please explain in detail. I have also attached the code and output for 1 second.

```
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"
//#include <SoftwareSerial.h>
//SoftwareSerial BTserial(10,11);
MPU6050 accelgyro;
char ch;
int incomingbyte = 0;
int16_t ax, ay, az;
int16_t gx, gy, gz;

void setup() {

  Wire.begin();
  Serial.begin(115200);

  accelgyro.initialize();
  accelgyro.setXAccelOffset(542);
  accelgyro.setYAccelOffset(-835);
  accelgyro.setZAccelOffset(1651);
  accelgyro.setXGyroOffset(6);
  accelgyro.setYGyroOffset(-18);
  accelgyro.setZGyroOffset(23);
}
void loop()
{
  accelgyro.getAcceleration(&ax, &ay, &az);
  accelgyro.getRotation(&gx, &gy, &gz);

  Serial.print(ax); Serial.print("\t");
  Serial.print(ay); Serial.print("\t");
  Serial.println(az);
}
```

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

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

body:
The reason is that Serial.print() is mush slower compared to reading a sample from the sensor.

If you comment the print(), then read sensor data for a certain time repeatedly and calculate the output data rate accordingly, you will find that the sampling rate is indeed 1000 Hz.

If what you wanted is merely to store the data and use it afterwards (instead of real-time processing), you can store the sensor readings in a SD card, which is always much faster than serial printing. A useful trick is that do not write data to the sd card whenever you get a new sample, but use a software buffer (i.e., array) to store the samples (the buffer size depends on the RAM of microcontroller) and then write the whole buffer to the sd card when it's full.

However, as long as you want to store the data (either print in serial or write in a file), you'll always have to 'sacrifice' some data rate and cannot get 1kHz as mentioned in datasheet.
Hope this helps.


message:
Confused as to how 2 of my interrupts are firing from just 1 pin input?

I have the following code which uses interrupts to set a flag for whether serial IO should happen to update my PC about a particular pin input. So I have interrupts on pins 2 and 3.

I am using the arduino's pin 13 as an output, and every 2 seconds send a pulse. On my arduino, I have 1 wire running from 13 to pin 3. **Note: I have nothing at all inserted into pin 2.**

Somehow, I get the following input every 2 seconds:

`Pin 2`
`Pin 3`

How is my interrupt for pin 2 firing??

    boolean serialCommsQueue1 = false;
    boolean serialCommsQueue2 = false;

    void setup()
    {
      pinMode(2, INPUT);
      pinMode(3, INPUT);
      attachInterrupt(digitalPinToInterrupt(2), pin2Fired, RISING);
      attachInterrupt(digitalPinToInterrupt(3), pin3Fired, RISING);
      Serial.begin(9600);
      pinMode(13, OUTPUT);
    }

    void loop()
    {
      digitalWrite(13, HIGH); // sets the digital pin 13 on
      delay(1000);            // waits for a second
      digitalWrite(13, LOW);  // sets the digital pin 13 off
      delay(1000);            // waits for a second

      if (serialCommsQueue1)
      {
        serialCommsQueue1 = false;
        Serial.println("Pin 2");
      }

      if (serialCommsQueue2)
      {
        serialCommsQueue2 = false;
        Serial.println("Pin 3");
      }
    }

    void pin2Fired()
    {
      serialCommsQueue1 = true;
    }

    void pin3Fired()
    {
      serialCommsQueue2 = true;
    }

EDIT:
-----

If I take the wire out of 3, pin 2 constantly (every 2 seconds) writes to serial. If I put the wire back in pin 3 regularly writes every 2 seconds - which itself is a problem too, since it should only be detecting a 'change'?

body:
The interrupt on pin 2 triggers, because the pin is floating. Since nothing is connected to the pin, it reacts to whatever noise is flying by (for example from pin 3). That can lead to the pin changing its state together with pin 3, or to just erratically randomly changing state.

You need to connect a pullup or pulldown resistor (one rather big resistor going from the pin to either Vcc or ground), which sets the pins state, when it is not actively driven otherwise. If you need a pullup or pulldown depends on your wanted behavior.

If a pullup is ok for you, you can activate the Arduinos internal pullup resistor by using

    pinMode(2, INPUT_PULLUP);


message:
MKR Zero not showing up in WIN10 device manager / Arduino IDE cannot detect port / COM

I'm new to Arduino and hope you guys can give some advise.

I bought MKR Zero a few days before and tried to connect to my Win10 laptop. I can see the LED on the board is on, but the Arduino IDE cannot detect it. the "Port" is grey out. I tried 2 laptops which also Win10 but same situation happen. I tried different USB cables I had.

I checked the device manager in the control panel, there is no "Unknown device" under the USB port but also no MKR showing up. I don't know what to do.

I'm not sure if it is Win10 problem...Please kindly advise, thank you very much!!

body: Hardware itself problem. Went to the shop and changed the board to me and now works.


message:
HID with bidirectional communication

I want to build a gamepad [HID][1] using the Arduino Micro, and intend to use [Nico’s HID library][2] for that.

But I would like to send some config info from the PC to the Arduino HID as well.

Can you have a gamepad that not only sends state to the PC, but also receives a configuration from the PC?

I intend to use this with a Linux PC as host.

  [1]: https://en.wikipedia.org/wiki/USB_human_interface_device_class
  [2]: https://github.com/NicoHood/HID

body: Yes, but the configuration side of things will not be part of the gamepad HID.  You will need to set up a second communication channel - be that serial or raw HID - to do the configuration.


message:
Can i exchange my arduino nano for an atmega328p-pu in my project?

Im currently trying to make a smart light switcher that is attached in front of my rooms light switches. It basically mostly consists of two servos (to turn on or off either switch), two button (to turn the servo manually), an esp8266 esp-01 module (to be able to use with a google home) and my arduino nano. I really need to make it as small as posible and i also want to keep my only arduino not attached to the wall. Would it work if i use an atmega328p or like an attiny84a to replace the arduino?

Im not finished with connecting the esp-01 to the arduino but i was thinking of using the arduino's 3.3v output pin. Would i need extra components to run the microcontroller on its own?

Im really new to arduino and im trying to learn the most I can and to try to make my little project as good as i can.

Would really appreciate some help please, thank you!

body:
Sure you can - as long as you include the rest of the support circuitry.

However the ESP-01 beats the Arduino hands-down and can do everything the Arduino does by itself - except it lacks IO so connecting to the servo and button could be tricky.

So using some kind of extra MCU as an IO expansion over serial would be a good idea, but a 328P is rather more than you need. Maybe you should look at something smaller, such as one of the ATTiny chips.


message:
Is it dangerous to connect two output pins together?

If I have two output pins, one set high and the other set low with digital or analog write like this
```
digitalWrite(PIN1, LOW);
digtialWrite(PIN2, HIGH);
```

and then I short them together using a wire, will current flow through the wire?

body: You can connect but requires resistor between two pins to limit the current.


body:
Yes. It is dangerous. You can imagine what would happen when you [understand how a GPIO pin works in output mode](https://majenko.co.uk/blog/what-exactly-gpio-pin).

You are effectively connecting VCC to GND via two small and weak MOSFETs which will overheat and break down.


body:
That's out of spec for any arduino microcontroller.

The behavior of a broken Arduino is "undefined" :)

I guess there will not flow current (after an initial peak), but _at least_ one of the two pins is not working properly any more. But, this is just a guess.

And it's probably not dangerous for you or the connecting wire (Other than @jsotola's comparison with a shorted battery in a comment to your question). I guess the arduino will die before it gets dangerously hot.


body:
Shorting the output pins together is a bad idea that will likely result in damage to your Arduino. According to specifications, the I/O pins are able to source (provide current to a load) or sink (accept current from an external source) up to 40mA. In almost all cases, you will want to use a current-limiting resistor. In some cases, an external circuit that you connect your Arduino to may intrinsically limit the current.

In the case of lighting up an LED, you can do this in two ways:

 - Set the I/O pin HIGH to source current to the LED through a current-limiting resistor to ground. The I/O pin provides the current to light up the LED. LOW turns it off.

 - Set the I/O pin LOW to sink current from the LED and current-limiting resistor where the power to the LED is provided by the external source. In this case, the LED floats and the I/O pn serves as ground. HIGH turns it off.

The internal pullup resistor is useful if you want to be able to drive an external transistor or logic level device.

This [Arduino tutorial](https://www.arduino.cc/en/Tutorial/DigitalPins) goes into more detail about the specific modes of operation.


message:
MPU-9250 compass always returns to zero

I am trying to build a 9-DOF IMU using the MPU-9250 chip which contains a gyro, accelerometer and compass. I have successfully realized 6-DOF sensor fusion using the DMP chip and Sparkfun's library, but I still have some yaw drift which is why I want to use its onboard compass for 9-DOF.

The DMP unfortunately can't do that so I tried [kriswiner's work][1] on 9-DOF sensor fusion which seemed to work but after I rotate the PCB, the yaw moves in the correct direction but it then slowly returns back to where it started, without me moving the PCB any more. This happens with many different sensor fusion libs, some more some less severe.

I have also tried just reading the raw `mx` and `my` values and reading the heading using `atan2(my, mx)` which made things a little better but still a 360° real-life rotation did not correspond at all to a 360° rotation on the chip.

Is this a known problem with the MPU-9250 and I am missing something completely obvious, or what could be wrong here?

Thank you for any help!

  [1]: https://github.com/kriswiner/MPU9250

body:
Ok, I have finally found the issue, and I am feeling very, very stupid.

1. I needed to calibrate the magnetometer with the figure-8 movement
2. I put a gigantic solid-metal 18650 Li-ion cell right next to the magnetometer chip...

EDIT: after replacing the 18650 with a polymer battery that is far away from the chip, things got a little better but both sensors in both devices still return garbage values.


message:
What current is safe for Wemos d1?

I've got 12V / 400mA power supply for my Wemos D1 R1, and I'm using VIN output(I need 12V for led strip). I need to change this power supply because of color, and I can't find similiar with the same parameters. The question is - Is power supply with 12V / 1A - 2A safe to use?

body:
With very few exceptions, electronic devices only draw as much current as they need, limited by their resistance.

The current rating on a power supply is the MAX current it can provide before the voltage drops. Having a higher current power supply may waste energy, but won't hurt anything.

According to Ohms law, V = IR

Where V = Voltage
I = current, in amps
R = resistance, in ohms

(voltage = current times resistance.)

Or, solving for current:

    I = V/R

current = voltage divided by resistance.

So if you have a 12 volt power supply, and a 100 ohm resistor, you'll get 12/100, or 0.12 amps, flowing through the resistor.


body: I am a bit confused you state:  VIN output, that is the voltage input to the onboard regulator. For the power supply use one of the same voltage but capable of more current. Current is the maximum a power supply will give reliably. Current is the current needed by a load so if the load is less then the source and the voltages are the same it is a go. The answer is yes either is ok but be sure you have enough current from the power supply + some to cover all of the LEDS.


message:
Getting external data to the Arduino

I have a new Uno R3, it's pretty cool and I've enjoyed playing with it.

Now I want to build a couple of things:

1) a market price LCD tracker.

2) a servo motor type thing to open my electric gate.

Both of these either require input from an external website or some kind of message to initiate the action on the Arduino.

How do people generally get data onto the Arduino, I found a lot of conflicting information online.

Does this thing have Wifi or Bluetooth??

I got this [pack](https://www.elegoo.com/product/elegoo-mega-2560-project-the-most-complete-starter-kit/), it doesn't seem to have either Wifi or Bluetooth, if not how do ppl generally get data onto the Arduino?

I have a raspberry pi spare, can I just use that, sending data from pins?

body:
> How do people generally get data onto the Arduino, I found a lot of conflicting information online.

There are various ways depending on what the data is and how you access it.

> Does this thing have Wifi or Bluetooth??

Not unless you add WiFi or Bluetooth to it, no.

> I have a raspberry pi spare, can I just use that, sending data from pins?

Yes, there are ways.

----

How you go about getting data on to an Arduino depends very much on how the data is accessed.  It is possible to add a WiFi interface to an Arduino, either through an official WiFi shield or through adding something like an ESP8266 on a breakout board (ESP-01 is popular) although interacting with the ESP8266 can be tricky.

You can do the same with Bluetooth or any number of other wireless protocols.

The simplest method of getting data to the Arduino, though, is through the USB serial port. Since you have a Raspberry Pi available the most logical option would be to plug the Arduino directly into the Pi's USB port. The Pi can then communicate through `/dev/ttyACM0` (or `/dev/ttyUSB0` for some clones) and the Arduino receive the data through the `Serial` object. Exactly how you arrange all that is entirely up to you.


body:
It depends on the kind of data and where it will be coming from. Trigging your gate really only needs a signal to start moving, though a directional signal would be better ("Open" or "Close"). What is the source of that signal and far from from the gate will it originate?

If you're willing to press a button on the gate, it's a simple matter of sensing the button with one of the Arduino's pins. If you want to operate it from your phone from right in front of the gate, a Bluetooth module on the Arduino could pick up the phone's signal. If you also need to operate it from further away - more than 5-10 meters, a pair of RF modules with stick-antennas like the ones on a WiFi router, might get you 100m.

For the market-price tracker, your data is probably coming from the internet, in which case you'd need either an ethernet module or a WiFi module that would link it to the internet through your local network. Or if this device has to be portable, you could use a cellular module to link it to the internet through the cellular network. This latter is usually expensive - the price of adding an additional line to your cellular plan, for instance.


message:
Can I Interrupt on any keypress on this keypad?

I'm learning how to write code interrupt code. I just experimented with my first toy example that I got from [here][4]:

 const byte ledPin = 13;
 const byte interruptPin = 2;
 volatile byte state = LOW;

 void setup() {
   pinMode(ledPin, OUTPUT);
   pinMode(interruptPin, INPUT_PULLUP);
   attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
 }

 void loop() {
   digitalWrite(ledPin, state);
 }

 void blink() {
   state = !state;
 }

Now I'm trying to incorporate interrupts into my own project. I have a circuit that looks like this using an [Arduino Uno Wifi Rev2][1], [Membrane 3x4 Matrix Keypad][2], a buzzer, some resistors and an RGB LED:

[![][3]][3]

Can I write code such that it interrupts any time any of the keys is pressed (and I can still tell which key is pressed)? How would I do that?

  [1]: https://store.arduino.cc/usa/arduino-uno-wifi-rev2
  [2]: https://www.adafruit.com/product/419
  [3]: https://i.stack.imgur.com/MASN3.png
  [4]: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

body:
No, you can't. Owing to the fact that you have to manually cycle through each row (or column, depending on which way you are holding your head at the time) in order to read which keys are pressed there is no way to relate a button to an interrupt.

The only possible way would be to use an external keypad interface chip (you could roll your own with another Arduino) which has an interrupt signalling facility in it.


message:
TLE9879 BLDC shield won't communicate

I just got the [TLE9879 BLDC shield](https://www.infineon.com/cms/en/product/evaluation-boards/bldc_shield_tle9879/), which I connected to an Arduino Leonardo. Compiling the example sketch (bldc_shield_blinky_test) went fine, however, upon flashing it to the board the LED on the shield doesn't change the color (it stays white) and the following line is repeatedly printed to the Serial console:

> WARNING: Board[1]; Command[901]; Answer[0]

I have initially tried the shield in its out of the box state. I have since then flashed it with the HALL version of the shield software, using the project included in the SW distribution that comes with the shield. In both cases, the shield behaved as described above when connected to the Arduino.

Does anybody know what this warning message is about?

body:
I never use TLE9879, but I could guess of why it doesn't work as expected.

For ATMega328p-based Arduino boards (i.e. Uno, Nano and Pro Mini), it has pin 11, 12 and 13 as SPI’s MOSI, MISO and SCLK signals, but at the same time these signals are also available on those board’s In-Circuit Serial Programming (ICSP) header pin 4, 1 and 3, except for Pro Mini which does not have a dedicated ICSP header.

This however is not the case for Arduino Leonardo and Arduino Micro which are based on ATMega32U4, for those boards, the SPI is only available on ICSP header. This is one of the reasons that some of the Arduino shields designed for Arduino Uno does not work with Arduino Leonardo when SPI communication is involved.

Based on the information of TLE9879, the SPI port is connected to pin 11-13 so it is designed to work with Arduino Uno but will not work for Arduino Leonardo.


message:
Writing elegant applications for Arduino

Coming from a C background, I was taught that tight loops that just burn CPU aren't desirable.

Is there any programming style guides on Arduino? Is it common practice to just let loop iterate as a tight loop forever?

body:
On a multiprocess system, like your typical desktop, you usually have
way more processes than logical CPUs. When programming such systems you
therefore have to avoid burning more CPU cycles than needed. Instead,
when your program has nothing to do, it should just _sleep_, and leave
the CPU available for other processes.

On an Arduino, you only have one single program running at a time. It is
then not that useful to keep the CPU idle. Also, the power dissipation
is so low that you will not notice the microcontroller getting even
slightly warm. The extra complexity of getting into and out of sleep
mode is therefore not that useful. Only when running on batteries do you
care about saving every possible milliamp: then learning about sleep
modes starts getting useful.


body:
A microcontroller's execution path is a tight loop whether you like it or not.

If you take a CPU and connect it to empty memory the CPU will execute each empty cell in turn and loop back to the beginning of memory when it reaches the end (assuming empty memory cells equate to NOP and covers the whole memory space).

With no operating system, no scheduler, nothing except your specific code running, the CPU is always executing something.

The only time the CPU stops executing is when you manually send it to sleep to be woken by some external source (such as a timer, or a sensor sending an interrupt signal). You'd only do that, normally, to reduce power consumption.

On Arduino the `loop()` function is in fact executed from within a `while(1)` loop.

On microcontrollers when `main()` exits, or you call `exit()` it just disables interrupts and drops out to a `while(1)` loop.