message:
about how to share one External serial EEprom using two microcontrollers?

**strong text**[![schematic**`strong text`**][1]][1]i have Vector nav100 IMU sensor that sends data serially UART.I want to receive data from it using ATmega32 and then store data in AT24c1024 EEprom using I2C,then using another ATmega32 to read the saved data on AT24c1024 EEprom using I2C to control a servo motor..so,the AT24c1024 EEprom is then shared between the two microcontrollers...i have serached the internet about how to share one  External serial EEprom,i found that......(On way would be for the two  mcrocontrollers to have an output line as an input to the other. A master that is "using" the EEPROM perhaps pulls his output low (or high - your choice) to say "I'm using it at the moment". The other reads his input first before going near the EEPROM if he finds the line active he backs off until it is set inactive by the other master.i tried this solution but i failed...can any one help me on this solution ?
Thanks in advance......
this is my code

    {

        //the first MCU fristly check the pin
        //if high,then write,then set it low to allow read
        //the second MCU fristly check the pin
        //if low ,then write,then set it high to allow write

        //for the MCu that will write
        //first it will check for the pin ,if it is LOW,
        //then it can write data to EEprom
                         DDRA=0x00;//configure portA as input
          if(PINA==0x00)//check for the pin, if LOw,then wirte
        {
         byte_write(data);
         _delay_ms(10);
        //After writing set the pin as high to allow the second MCU to read
         DDRA=0xff;//configure portA as output
         PORTA=0xff;//set the pin as high
         _delay_ms(10);}

        //for the MCu that will read,i set adelay of 10 ms
        // to allow the first MCU to write some data

                             _delay_ms(1000);//delay from the data to be written on the EEprom
                     DDRA=0x00;//configure portA as input
         if(PINA==0x01)//check for the pin, if HIGH,then read
        {
              y=byte_read(data);
             DDRA=0xff;configure portA as output
             PORTA=0x00;//set the pin as high

    }

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

body:
You didn't show us a complete, minimal, compilable example, so my answer will only cover some important points.

1. Your indention is way off. It is important to use the correct indention, since it help structure your code and will let you quickly see misplaced brackets. The Arduino IDE even has an autoformat function for this.

2. You are configuring and checking always the whole PORT A, but you have only connected one of the pins. When you configure the whole port as input (without pullup), the other pins will be floating. Also, if both devices have the pin on input (no pullup), this pin will also be floating. The check cannot work this way. You should only look at the first bit in the port registers, since that is the pin, that you connected. You can set all other bits to zero when reading, by performing a bitwise AND operation: `if(PINA & (1<<PA0))`. This will execute, when the first bit of PINA is 1. To set a single bit you can use the bitwise OR: `DDRA |= 1<<PA0;` will set the first bit of DDRA. To erase only that bit from the register, you can use `DDRA &= ~(1<<PA0);`. The rest of the port will stay untoched with this.

3. Your current protocol is, that the first MCU will check for LOW, do it' transmission, then drive the pin actively HIGH as a signal for the second MCU to start transmitting. The second MCU will do it's I2C stuff and then drive the pin actively LOW. So now we have an active LOW and active HIGH on the same pin, which in principle is a short. A rather big amount of current will flow from one MCU to the other, most likely destroying at least one of the pins (meaning the output hardware in the MCU, that serves that pin). To avoid this, you can use a principle like that, that the I2C port uses: Open Drain logic. You can start with the first MCU's pin configured as OUTPUT LOW, while the other is INPUT PULLUP. LOW means the first MCU can work. If the first MCU want's the second MCU to do a transmission, it will release the line by setting the PIN to INPUT PULLUP. The second MCU now sees a HIGH level on it's pin and starts it's transmission. When it is finished, it will drive the line actively LOW for a defined duration (enough for the first MCU to react) and then to INPUT PULLUP again. The first MCU will then see a LOW level on it's pin as a signal, that the second MCU is finished. It then itself drives the line actively LOW. Then the play starts again. The important thing is, that a HIGH state is only done by a pullup, not actively driven.

---

That said, I still don't see the necessity to share an external EEPROM for this use case. You are overthinking the problem. You wrote, that you don't want to miss a frame, if the second MCU is still processing the last frame. There are better ways to do that (especially when you consider the limited lifetime of EEPROM).

- You didn't tell us, why you are using 2 MCU's, so maybe your goal can be reached with only 1 MCU, which will eliminate the whole need for transmission.

- You could use another UART interface via `SoftwareSerial` or it's sibling libraries to let the MCU's communicate directly. "Not missing a frame" will still be the case, when you are not disabling interrupts. The library will read the data into a buffer in interrupts, while you are processing the previous frame. Depending on how much data you send, you might want to make the buffer bigger, but that is a simple change in the libraries definitions.

- If you want to use I2C to communicate between both MCU's, you have 2 ways of doing it. You can either go the same way as described above for UART, by just letting it fill a big enough buffer, or you can do this through the bus transmissions. The first MCU would be the master, that tries to send the data to the second MCU (slave), when there is new data available. The slave will receive the data normally. When the frame is finished receiving, the slave can leave the bus, until it is finished processing. So, when the master tries to send more data in this time, the transmission will fail at the start, since no slave with that address is on the bus (the slave MCU left the bus for this period of time). You can check the return value of `Wire.endTransmission()`, which will reflect the corresponding error code. If this error code is returned, the master should wait a bit and try to send this frame again, until it is received successfully. That also means, that the master needs a big enough buffer for storing new data, while waiting for the slave to be ready. Or another way: The master can request 1 byte from the slave, that indicates, if the slave is ready for new data. If not, the master will wait a bit and ask again. If yes, it will transmit the data.

Note: Either way the frequency of data reception and processing must be equal for continuous operation. The whole chain will be as fast as the slowest part. If you receive data faster, than it get's processed, the buffer will fill up fast, until you really have to drop frames. The prinicples above are more about the case, when the processing and receiving may misalign or vary a bit, but at the average staying at the same speed. And for this simple communication buffers, that all communication libraries use, with enough space for maybe 2 to 4 transmissions (depending on the variation) are way enough.


sender: user

message:
Powering Arduino with Thermostat Power

So I want to make an Arduino based thermostat controller. I'm good with the semantics behind this, there's just one detail I want to make sure I get right: Power

I know US thermostat power is 24VAC, but I'm not sure how to convert that to 12V 0.5A DC that the Arduino wants. I'd like to do this efficiently rather than generating a ton of heat in the process, too. I don't even know how many amps "24VAC" is, which is the only specification I can find on thermostat power.

I've found 24VAC to 12VDC converters (made for surveillance cameras) online, but most are rated for 1.5A, and I'd be concerned about frying the Arduino. I am not sure if the Arduino only pulls as much as it needs, or if it would try to pull the full 1.5A and destroy itself. I also do not know if these are relatively power efficient, either.

I'm generally hoping someone has been down this path before so that I don't have to reinvent the wheel.

sender: assistant

body:
>  I don't even know how many amps "24VAC" is

Exactly, because that's a voltage rating (24 Volts AC) and no information about the current capability is given.

>I've found 24VAC to 12VDC converters (made for surveillance cameras) online, but most are rated for 1.5A, and I'd be concerned about frying the Arduino. I am not sure if the Arduino only pulls as much as it needs, or if it would try to pull the full 1.5A and destroy itself

The Arduino, as a semiconductor, will consume only the current it needs. What current it needs is determined by the processor core (if it's e.g. in sleep-mode or not), the activated peripherals (ADC etc) and devices powered externally via the Arduino's +5V or +3.3V pins.

The [typical power consumption](http://www.home-automation-community.com/arduino-low-power-how-to-run-atmega328p-for-a-year-on-coin-cell-battery/) of an Arduino board running a sketch (no low-power mode + no external devices) is about 20mA, aka 0.020A.

Also note that what's happening is when you feed +12VDC into the VIN pin, it goes to a linear voltage regulator, which converts excess voltage into heat while keeping the current the same. The [official Arduino Uno](https://content.arduino.cc/assets/UNO-TH_Rev3e_sch.pdf) (not a chinese clone!) has a [NCP1117ST50T3G](https://www.onsemi.com/pub/Collateral/NCP1117-D.PDF), which is a 6.5V-20V (recommended limit:12V) to 5V linear regulator with I_out of minimum 1A, typical 1.5A (also note I_out is circa I_in, the regulator itself needs negligable current). Clones might use a cheaper (and worse) voltage regulator. Also note that this output capability might not be realisitically achievable without a heat-sink on the regulator; since excess voltage is converted into heat, converting +12V to +5V at 1A creates (12V-5V)*1A = 7W of heat(power). The package cannot sustain that for very long and the regulator shuts down due its built-in thermal protection.

In short it can be said that it's not a problem to connect a higher-rated power supply to an Arduino. The Arduino will pull what it needs to power itself and everything else on the +5V and +3.3V pins, if it's within the limits of the voltage regulator.

These videos might help your understanding of linear voltage regulators: https://www.youtube.com/watch?v=GSzVs7_aW-Y https://www.youtube.com/watch?v=giGRrODKJSE


body:
If you're just running an Arduino and a few low power components, feeding the Arduino's voltage regulator 12V would be fine. However, if the 24VAC to 12VDC power supply is unregulated, it may well put out more than 12V.

If your Arduino system draws a lot of current from the 5V regulator then it will generate a lot of heat, and might overheat. What else are you driving from the Arduino's 5V and 3.3V lines?

A buck style power supply would be a good choice for this setup.

Here is an example that should work very well:

https://www.amazon.com/SMAKN®-Converter-Voltage-Supply-Waterproof/dp/B00RE6QN4U

The picture on that supply says it will work with from 8-35V, so there is a **lot** of "wiggle room" in its supply voltage. Even if the doorbell draws enough current for the 24VAC to drop to 12VAC while the doorbell is ringing, the supply should still be able to keep the Arduino running just fine.

(You could feed the regulated 5V from that supply directly into the USB input on your Arduino)

That is a very high efficiency supply that will waste very little power as heat. You wouldn't need anything else other than that.


message:
Modular Coding - What types of code portions to convert into library files? Rationale and methods?

I'm working on documentation and combining 2 pieces of code for testing parts of a larger project.

I'm supposed to comment and make the code very clear to people who will use it later and make sure it's modular. I'm supposed to make header files, to reference function chunks in the main code from just the `#include(s)`.

I understand in C++, that the convention is that for each header files(?), `.h`, there is a `.cpp`, where the `.h` is the header file that declares all the content, and that the `.cpp` is where you define the `.h`, ie. implementation.

My supervisor told me to put more parts of the code into library files, because additional components will be added in the future -

> but confused because all the length comes from using already existing
> library files, just a specific pattern of calling pre-defined
> functions.

**If I put the files into a .h, how do I reference all the calls?
Make a `void setup () {}`**?

The compiled code is 348 lines right now. All it has are some `#include(s)`, code to calibrate and read from 2 different sensors using I2C and SPI protocols, with 1 shared master an Adafruit Bluefruit nRF52832, and comments with links to datasheets.

The bulkiness is in the set-ups and the different ways to  represent data (have 24 lines just to print out data from 1 sensor).

**Should the entire code be just calling built in functions from a library file? So people who read the code don't see the details so much?**

body:
It's very subjective what should and shouldn't be put in a library.

I use the simple rules:

* If it's an atomic piece of code like a hardware driver, it's a library.
* If it's something that could be used in multiple sketches, it's a library.

Maybe things like configuration options could be put in a header file (not a library - a header file in the sketch folder).

You could maybe split portions of your sketch into C++ files or INO files within the sketch (not a library - files in the sketch folder, and using INO files is easier since you don't need header files, the IDE does it all for you) to group things logically together and make it easier to manage (all the LCD code in one file, all the temperature sensor code in another file, that kind of thing).


message:
How to create array of references?

I have a class named `timeOut` dealing with timeout tasks.

I'm to write a sketch, common for Sonoff basic and Sonoff Dual, meaning that I may have 1 task for Basic and 2 tasks for Dual.

Declaring instances looks like:

    timeOUT timeOut_SW0("SW0",TIMEOUT_SW0);
    timeOUT timeOut_SW0("SW1",TIMEOUT_SW1);

for code simplicity I'd rather create an array of references and call it using a `for` loop:

    timeOUT TO[]={timeOut_SW0,timeOut_SW1};

is it the right way to call it as a reference ?

body:
You can't. The C++ language [doesn't support arrays of
references][refarray]. You have the choice to either create an array of
objects:

```c++
timeOUT TO[] = {timeOUT("SW0",TIMEOUT_SW0), timeOUT("SW1",TIMEOUT_SW1);}
```

or an array of pointers:

```c++
timeOUT *TO[] = { &timeOut_SW0, &timeOut_SW1 };
```

[refarray]: https://stackoverflow.com/questions/1164266/why-are-arrays-of-references-illegal


message:
Using an L298N driver together with servo motors on the same arduino

I'm using an L298N driver (powered by a 12V, 1.5A adapter) on a MEGA Sensor Shield (powered by a USB cable). Everything works fine and I can control the direction and the speed of the DC motor, however when I activate anything else on the shield - the motor will not spin unless I set the PWM to its highest frequency.

Please note that I am using Max/MSP to controls the motors, so when I say activate - I mean setting up the PinMode of pin 17 to "Servo". If I set up the Servo first and then the DC motor pins - it will again start spinning only at maximum PWM, there's no signal reaching the driver otherwise.

Am I missing something in my setup? I would use Arduino Mega on its own, however I need to use over 25 Servo motors together with the L298N driver, which makes the sensor shield inevitable.

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

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

body: It seems that the issue is with the fact that PWM is only supported on pins 2-13, so I shouldn't have connected it to pin 46.


message:
Using an NPN transistor as a switch to turn on/off a DC Motor

I am trying to control a 3V DC motor ([FA-130][1]) with my Arduino Uno, and am trying to do that using an NPN transistor ([2N3904][2]) as a switch, as shown in this diagram.

[![Diagram - Arduino, NPN transistor, DC Motor][3]][3]

I used the Blink example and modified the pin used for the output to be the one attached to the transistor's base (e.g. pin 2 in the diagram).

The motor does nothing. If I replace the motor with an external LED component it works, blinking on/off every 1 second. If I connect the motor directly to my Arduino's 5V and GND (or even 3.3V and GND) then the motor runs fine.

Why does the motor not run when connected using the transistor? Is there a significant enough drop in voltage/current/something else?

  [1]: https://product.mabuchi-motor.com/detail.html?id=10
  [2]: https://pdf1.alldatasheet.com/datasheet-pdf/view/15077/PHILIPS/2N3904.html
  [3]: https://i.stack.imgur.com/SF19I.jpg

body:
It depends on the transistor. You might not be driving it to full saturation, or it's "on resistance" may be too high to pass enough current to drive the motor. You'd need to tell us the specific transistor, as well as the specs on the motor before we could figure out what's going on.

An LED draws a whole lot less current than a motor, so the transistor may not have any problem powering your LED. (You usually need a current limiting resistor when you drive an LED from 5V to avoid burning it out.)

I would suggest using a MOSFET transistor instead. This one, for example, can drive up to 30A at 60V: https://www.adafruit.com/product/355

It has very low on resistance, and is fully turned on by a 5V CMOS logic output, and requires very little current through the base to turn it on.

As CrossRoads pointed out, if you're using an NPN or other BJT transistor you really need a current limiting resistor between the Arduino output and the gate so you don't draw too much current from the Arudino pin and fry it.

Note that regardless of what type of transistor you use, you need a "flyback diode" on the motor to protect the transistor from [back EMF][1] from the motor's inductive coils. Without a flyback diode you run the risk of destroying your transistor.

  [1]: https://en.wikipedia.org/wiki/Counter-electromotive_force


message:
Can you start/stop a code from the serial monitor?

pressing and number in the serial monitor to start code and stop code.

body:
This can be done by using the ```Serial.read()```command as referenced in the Arduino documentation [here][1].

Below is an example of how you might apply this.

```

/**
 * NAME: Serial interupt
 * DATE: 18/7/19
 * AUTHOR: Jeremy Fox
 * DESCRIPTION:
 *    FLashes LED until recives enter keystroke from serial monitor.
 */
int incomingByte = 0; // for incoming serial data
int LED = 13; // defines the LED to flash
boolean flash = true; // for flashing loop

void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {
  while (flash == true){
    // flash LED
    digitalWrite(LED, HIGH);
    delay(100);
    digitalWrite(LED, LOW);
    delay(100);
  }

  // record data if available:
  if (Serial.available() > 0) {
    // read the incoming byte:
    incomingByte = Serial.read();
  }

  // checks if enter key was pressed:
  if (incomingByte == 13) {
    flash = true; // enter loop
    incomingByte = 1; // reset incomingByte to avoid feedback loop
  }
}

```

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/read/


message:
What is this extender?

I recently got an Arduino starter kit from a friend that he wasn't using and this came with it but, i can't find anything about it, cause i don't know how to search for it.
Anyone can enlighten me what it is?

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

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

body:
Looks similar to:

"8 Channel 5V/3.3V IIC UART SPI TTL Logic Level Converter"

[![8 Channel 5V/3.3V IIC UART SPI TTL Logic Level Converter][1]][1]

Image above was screen capped from: https://www.aliexpress.com/item/32977711795.html

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


message:
Can I connect this LED Matrix to a ESP8266 Huzzah directly?

[This tutorial][1] for the 16x32 LED Matrix makes it sound like you have to use an Arduino Uno or Mega, but the tutorial was also written a few years ago.  I have a Huzzah ESP8266 (my project is about displaying information from the internet on the LED matrix) but I can't seem to get the <RGBmatrixpanel.h> library to work with the Huzzah.

I am wondering if it would be possible to somehow hook up the LED matrix directly to the Huzzah. Can anyone make suggestions on this front?

Or do I have to basically make the Uno a slave to the Huzzah ESP8266? Need to figure out how to do that.

Thank you.

  [1]: https://learn.adafruit.com/32x16-32x32-rgb-led-matrix/

body: The Huzzah is a great board but I don't think it is capable of driving a large led matrix by itself.  Adafruit also makes a led matrix feather wing which could enable the huzzah : https://www.adafruit.com/product/3090


message:
Is it possible to use WiFi and Bluetooth / BLE in the same ESP32 project?

@Majenko's answer works like a charm. I did have to make some changes as follows:

Per Majenko, you need to change the Tools > Partition scheme.  I used "No OTA (Large APP) as he suggested and it is now working.

However, the Partition Scheme option under Tools was not available for either of my devices (Huzzah32 or NodeMCU-32s).  I changed my board type (Tools > Board) to "ESP32 Dev Module" and several additional options appeared under Tools, including Partition Scheme.

**Original Question:** I am not able to use both the WiFi.h and BLE libraries at the same time.  Even the most minimal projects run out of memory during compile.  Am I doing something wrong?   I get identical results with both an Adafruit Huzzah32 and a NodeMCU-32S.

Does anyone know of a workaround, or barring that a suggested alternate board? A Raspberry pi zero W seems like overkill and the power consumption is ugly, so I don't want to do that unless I really have to.

    #include <WiFi.h>
    #include <BLEDevice.h>

    void setup() {
      WiFi.mode(WIFI_MODE_STA);             // use a WiFi function
      BLEDevice::init("Minimal BLE WiFi");  // use a BLE function
    }

    void loop() { }

The error I get is

> Arduino: 1.8.9 (Mac OS X), Board: "NodeMCU-32S, 80MHz, 921600"
>
> Build options changed, rebuilding all **Sketch uses 1443898 bytes (110%)
> of program storage space. Maximum is 1310720 bytes.**
>
> Global variables use 60208 bytes (18%) of dynamic memory, leaving
> 267472 bytes for local variables. Maximum is 327680 bytes. **Sketch too
> big**; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips
> on reducing it. Error compiling for board NodeMCU-32S.

body: Yes. Select a partition scheme that gives you more room. For example "No OTA (Large APP)" gives you 3MB of program space.


message:
Why do all analog pins measure the same value?

I measure 2 analog pins: A4 and A5. The A5 pin is connected to another Arduino's digital out (through a 10k resistor) which has a simple program: 5ms on and 100ms off. The A4 pin is not connected anywhere.

The analog pins are inited with pinMode(APIN, INPUT), reading is simply performed with the analogRead(APIN) function (there is no delay between the readings). I have tried with delays between the measurements but the results are the same.

The results: [![enter image description here][1]][1]

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

The A5 pin (which is connected) measures the correct value. However, the unconnected A4 pin is clearly interferred by the input of A5. It works like this with another pins, delays between the readings, double use of analogRead()... I even swapped the Arduinos (Arduino Nano and Uno) and the results are the same.

Is it because of that these Arduinos are clones? Or are these Arduinos damaged?

body:
If you want to measure a pin (i.e. defined as input pin, either digital or analog), you have to use a pull up or pull down resistor (either internal or external depending on what the MCU GPIOs have).

This resistor makes sure in case there is nothing attached, that the (mostly high ohm) resistor will make sure the nonconnected pin will either give a LOW or HIGH as input (or in case of analog, the minimum or maximum value).

When the pin is connected, the pull down/up resistor will change the result so marginally that it can be ignored.


body:
I believe what you are seeing is the effect of the *sample and hold* process used by the Arduino analog to digital converter (ADC).

The way the *sample and hold* circuit in the ADC works is

 1. Connect the pin to an internal, fixed size capacitor
 2. Disconnect the pin
 3. Compare the capacitor voltage against a fixed value

All the analog pins in the Arduino share the very same capacitor, so if such capacitor has no opportunity to discharge another reading will be influenced by the previous one.

Ref.

 1. https://en.wikipedia.org/wiki/Sample_and_hold
 2. http://ww1.microchip.com/downloads/en/appnotes/atmel-8456-8-and-32-bit-avr-microcontrollers-avr127-understanding-adc-parameters_application-note.pdf


message:
Arduino IDE monitor multiple USB ports simultaneously

Is it possible to monitor multiple USB ports simultaneously in Arduino IDE while running only ONE instance of the IDE?

If not, which solutions come alternatively to mind?

body:
Short answer : No.

Long answer : Noooooooooooooooooooooooooooooooooooooo, since one window can only work with one arduino.

That being said, if you open another file, or create new file (Ctrl + N) on existing window, it doesn't make another process.

It is still on the only javaw.exe process running on your computer (you kill that, both window gone for good.)

To make it simple :

Double click Arduino icon on your desktop, and double click it again, it will run as 2 separate process.

Double click Arduino icon on your desktop, and then use open file or new file, it won't make another process.

But I think I misunderstood your question. If you're asking for arduinos in multiple USB ports, yeah, one IDE can see wherever you plug it in.


body:
[Sloeber][1], an open source IDE based on Eclipse on which I am a proud contributor, does have this feature, but **the Arduino IDE does not**.

  [1]: http://sloeber.io


body:
If you are only interested in monitoring the output, a simply python script can be run to monitor the port. This sample takes an input of the port number(assuming they get named ttyUSB1, ttyUSB2, ect...  Or you can modify it to be a hard coded port.  Also make sure the baud rate matches with what your arduino is running (115200 in the example)

You can then run this script in two separate terminals, one for each port

    #!/usr/bin/env python3

    import serial
    import sys

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

    while True:
     try:
      print(str(ser.readline().strip()))
     except:
      print(sys.exc_info())
      ser.close()
      exit()

Start the program like so

`python3 ./programName.py 1` (or `./programName.py 0`, etc)

The number dictates which of the ttyUSBx devices you are trying to watch (will match with what you see in the arduino IDE).


body:
You can run multiple instances of the Arduino IDE to work with multiple boards at the same time. Start IDE second time with Start menu or desktop shortcut.

Of course you can monitor the COM/tty port with a common serial terminal program too.


message:
NodeMCU backup sketch

Is it possible to extract a backup of the sketch uploaded to a NodeMCU (as I know that it is possible to backup the firmware).

If so, using which tools?

body:
esptool.py is 'avrdude' for the esp8266. it can read the flash too. but you must know the addresses. tha first copy of the application always start at address 0x1000. the length of the application area depends on the size of the flash and the size of the SPIFFS.

    > esptool.py read_flash -h
    usage: esptool read_flash [-h] [--spi-connection SPI_CONNECTION]
                              [--no-progress]
                              address size filename

    positional arguments:
      address               Start address
      size                  Size of region to dump
      filename              Name of binary dump

    optional arguments:
      -h, --help            show this help message and exit
      --spi-connection SPI_CONNECTION, -sc SPI_CONNECTION
                            ESP32-only argument. Override default SPI Flash
                            connection. Value can be SPI, HSPI or a comma-
                            separated list of 5 I/O numbers to use for SPI flash
                            (CLK,Q,D,HD,CS).
      --no-progress, -p     Suppress progress output


message:
What is the call to cli(); routine in interrupt service routine for SPI?

I see this in examples of ISR code but what is it?

body:
Interrupts are normally turned off automatically when an ISR is called.

There are two instructions that allow software to turn off (cli) and on (sei) interrupts to create a sequence of non-interruptable instructions, i.e. an atomic operation or critical section.

In some MCU there are several levels of interrupt priority and an ISR with lower priority may be interrupted by an ISR with higher priority. An atomic operation may also be required in an ISR with lower priority.

There are also cases where an ISR may allow interrupts (with the same or lower priority) to occur after the critical section of the ISR.

Normally an ISR should not contain cli()-sei() especially for the AVR. The hardware will automatically turn off interrupts during the execution of the ISR.

Cheers!


message:
Error when HX711_Arduino_Library installed

First I'm getting this error #include <HX711.h> no such directory. Then HX711_Arduino_Library installed. Now getting following errors:
Arduino: 1.8.9 (Windows 7), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), 4M (no SPIFFS), v2 Higher Bandwidth, Disabled, None, Only Sketch, 115200"
sketch_jul18a:34:22: error: no matching function for call to 'HX711::HX711(int, int)'HX711 scale(DOUT, CLK);
                      ^
C:\Users\My Lappy\Desktop\sketch_jul18a\sketch_jul18a.ino:34:22: note: candidates are:In file included from C:\Users\My Lappy\Desktop\sketch_jul18a\sketch_jul18a.ino:23:0:
C:\Users\MyLappy\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note: HX711::HX711()
   HX711();
   ^
C:\Users\MyLappy\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note:   candidate expects 0 arguments, 2 provided
C:\Users\MyLappy\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note: constexpr HX711::HX711(const HX711&)
 class HX711
       ^
C:\Users\MyLappy\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note:   candidate expects 1 argument, 2 provided
exit status 1
no matching function for call to 'HX711::HX711(int, int)'

Help me with this.

body:
There are several HX711 Arduino libraries. Do you have the right one? I would guess no as the library you have installed does not have the constructor that the sketch is using. Either use the correct constructor from the installed library or install another library that has that constructor.

Cheers!


message:
Tone() conflicts with IRremote library (multiple definition of `__vector_7')

I have just started with Arduino and C++ so I apologise if my question is very basic.
I am trying to use tone() with a passive buzzer to create a sound while also using the IRremote library for a remote. However, whenever they are used together, it gives this error:

> Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
>
> (.text+0x0): multiple definition of `__vector_7'
>
> libraries\IRremote\IRremote.cpp.o (symbol from plugin):(.text+0x0):
> first defined here
>
> collect2.exe: error: ld returned 1 exit status
>
> exit status 1

> Error compiling for board Arduino/Genuino Uno.

This is the code required to recreate this error:
```c++
#include "IRremote.h"
#include "pitches.h"
int melody[] = {NOTE_C5, NOTE_E6};

void setup() {}

void loop() {
 for (int thisNote = 0; thisNote < 2; thisNote++) {
 tone(3, melody[thisNote], 300);
}
}
```
Please could you advise me on how to fix this issue and if necessary, on a different library or way to create a sound or to receive IR signals?

body:
Exactly as @MichelKeijzers wrote the issue is caused by "IRremote" using same timer as "Tone" and the solution to this problem is a little dirty.

Since Tone is included in ArduinoCore (and compiled) we can't easilly modify it so the only thing that worked for me is to modify boarddefs.h file of IRremote library. Since it's code is easilly available after downloading it using "Library Manager" included in ArduinoIDE.

In my tests I used ATmega328P settings.

[![arduino board setting][1]][1]

Edit `C:\Users\youruser\Documents\Arduino\libraries\IRremote\boarddefs.h` and look for your processor number.

For ATmega328 the definition is `#define IR_USE_TIMER2`

[![boarddefs.h code][2]][2]

I simply changed it to use #define `IR_USE_TIMER1`

[![boarddefs.h updated][3]][3]

And compilation was successfull.

    Sketch uses 2746 bytes (8%) of program storage space. Maximum is 30720 bytes.
    Global variables use 242 bytes (11%) of dynamic memory, leaving 1806 bytes for local variables. Maximum is 2048 bytes.

My code:

    #include "IRremote.h"

    #define NOTE_C5  523
    #define NOTE_E6  1319

    int melody[] = {NOTE_C5, NOTE_E6};

    void setup() {}

    void loop() {
      for (int thisNote = 0; thisNote < 2; thisNote++) {
        tone(3, melody[thisNote], 300);
      }
    }

  [1]: https://i.stack.imgur.com/oATAN.png
  [2]: https://i.stack.imgur.com/9C3he.png
  [3]: https://i.stack.imgur.com/c0l49.png


message:
request for a member "X" in something not a structure or a union

i was programming a Self Balancing    Robot, I am writing the code in vscode using platformio extension.

when i put the code i need to get the angle out of the gyro in another file (named angle.c) and including it in the main program, the ide throws with error, in every line I use the Wire library in the angle.c, however same code copy and paste it in the main program and it works.

P.S. the angle.c is just a file of functions and doesnot have any class.

body:
A .c file is compiled with C compiler. If you include Wire.h which contains a class definition, the C compiler doesn't understand it and generates errors.

If your angle.c file doesn't have C code not compatible with C++, then change the extension of the file to .cpp and it will be compiled with C++ compiler.


message:
Which is better millis() or timer?

I want to create a 30 minutes delay in my program (Arduino).

which is better `millis()` or timer for this purpose?

please give me an example to clarify my doubt ...

Thanks.

body:
It depends on your need:

**1. No other activities / main power**

If during those 30 minutes (I guess), the MCU does not have to do anything else (except maybe handling some short interrupts), than you can use a delay. You can use this if your power source is an adapter, but you waste a lot.

- Advantage: Easy to program
- Disadvantage: Power will continue to be used.

**2. No other activities / battery**

If you have the same conditions as above, but using a battery, than as Juraj mention, use the sleep functionality of the Arduino. You need an (external) real time clock or other circuitry to activate the wakeup signal after 30 minutes.

- Advantage: Very less power used during the 30 minute delay
- Disadvantage: Slightly more programming

**3. Other activities**

If you want to do now (or later) other code to be executed during the 30 minute wait, use `millis()`. For example, when you want to extend your project using other libraries that needs a faster than 30 minute response.

- Advantage: You can do other tasks meanwhile
- Disadvantage: More power usage, slightly more programming


message:
Detect if laptop is on or not?

How would I safely connect an Arduino so that it can detect if a laptop is on or off?

The Arduino would be powered separately by a normal USB charger, since it needs to be turned on even when the laptop is turned off. So I'm thinking I can connect an input on the Arduino to one of the USB ports on the laptop somehow, but how do I do this safely?

Even if I play it safe and connect a current-limiting resistor between the USB voltage and input pin, and perhaps a voltage divider, is there still a problem with connecting one device to another like this? I'm thinking that since each has its own power supply from mains, could there potentially be a problem if I connect the USB port of the laptop to a pin on the Arduino?

Do need to use an optocoupler or relay between them? Or is there an even better way of doing this that I didn't think of?

body:
The wall-wart type USB chargers are always double insulated - you'll typically see the square within a square symbol for European markets, though one for the US market alone may not have that marking.

That means that the secondary side is free to float, and can be safely connected to the ground connection of the laptop - whose power supply will typically also be double insulated.

That means you can just connect the 5V USB output to an input on the Arduino - put a high enough current limiting resistor in to allow for differences in voltages - especially in the case that the laptop output is on when the Arduino supply is off, to avoid the input feeding the Arduino through the protection diodes.

You can use an analog input, but if you're only looking for an on/off indication, a digital interpretation would work.

Check the output of the USB socket on the laptop - some are intended to remain live for charging accessories when the laptop is powered but not on. On one of my laptops all the ports are live like this and there's nothing that indicates this.


body:
I don't see any problems connecting the them together like you described.

Make sure not to forget to also connect the USB ground to the Arduino ground, so the electrons have a path to go back.

Adding a current limiting resistor is advisable, for the case that the Arduino isn't powered, but the laptop is. Resistor divider is only needed for Arduino's that run on 3.3V.


body:
If your chosen power supply is of a good quality and provides proper ground isolation then it *shouldn't* be a problem to connect the grounds of the two systems together.

However, since there are so many bad power supplies available on the internet (and even some "good" power supplies are somewhat iffy when it comes to grounding) it is safest to hedge your bets and add your own galvanic isolation.

The simplest method is to use an opto-isolator.  Use the +5V and GND from your computer's USB port (assuming it's not an always-on charging port - look for a lightning bolt symbol) along with a resistor (470Ω - 1kΩ is good) to drive the LED side of the opto-isolator. The other side then acts as a button to the Arduino:

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

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

<!-- End schematic -->

In this arrangement your input will be LOW when the PC is on. Also R2 could be replaced by the internal pullup of the GPIO pin (`pinMode(PIN, INPUT_PULLUP);`)

As I say, this most likely won't be strictly necessary, but for the minimal cost of an opto-isolator it's silly not to add that extra layer of protection. After all, an opto-isolator is cheaper than a new Arduino or (heaven forbid) a new laptop.


message:
How to detect patterns in an FFT output?

I have an FFT output from a microphone and I want to detect a specific animal's howl from that (it howls in a characteristic frequency spectrum). Is there any way to implement a pattern recognition algorithm in Arduino to do that? Thanks!

body:
It depends.

First you need to break the problem in steps:

1. If you can make a static analysis, than there is a chance. Meaning, if you can record a snapshot of the howl, and than spend some time processing it.
2. If you need to process it (almost) real time, than I am almost sure the Arduino is way too slow for that. In the next steps will be clear why, and otherwise you can use the next steps to get some idea how to do the analysis.
3. Assume you can do a snapshot of the sound, than you have to store it. The Arduino has only 2 KB of SRAM which is way too small. I assume you want a decent frequency (let's say 40 KHz) of mono (1 channel) samples, which is 40 KB of memory.
4. You need to record this (probably any sound sensor will be fast enough), and store it to some device, either external SRAM (fastest, most expensive), external EEPROM (somewhere in the middle) or SD card (might be slow). EEPROM/SD cannot be written 'forever' so if you want to process a sample every second, you might run in trouble.
5. Than you need to run your algorithm over the static data. I do not know this algorithm, if you have to iterate many times, forget about using SD, use SRAM or EEPROM.
Otherwise, read a few blocks (typically 2 or 3, to get 1 or 1.5 KB) and process it. I hope you can store the result also in the Arduino, otherwise write it (if you write much, probably SRAM is the only well feasible solution).

As you can see, you have to break your problem into smaller pieces, and check how the algorithm works (does it need a lot of data, or a snapshot), can it be processed in pieces, or does it need to iterate over the entire sample data a lot, are there intermediate results need to be stored etc.

Note there might be other solutions:

- If you need more speed, try an Arduino Due
- If you need more (internal) SRAM, try a Mega (8 KB) or Due (48 KB)


message:
Is it necessary to reduce the size of libraries?

For example RTClib library have codes for DS1307, DS3231, PCF8523 and softRTC. but I'm only using DS3231 and don't need the extra codes there to occupy my Arduino flash memory.

Does Arduino IDE only "upload" those parts of libraries that is being used in the sketch or just uploads the whole library?

body:
Normally a library supports various kinds of components; because mostly those components share a lot functionality, so it prevents to make very many different libraries.

Note that all functions that you do not call within your program (and are not called from within the library), will NOT end up in your sketch, thus also will not affect your flash memory usage.

If the library is full of `if` statements to make a difference between models, that code is in (if a function is called, the entire function is stored in flash). (Unless the `if` statement can be evaluated compile time, see remark of Edgar Bonet below about link time optimization).

So if you want to remove that 'unnecessary' code (for you at least), than copy the library into your project and remove the unnecessary code yourself.

However, I would not do that until you run out of flash memory.

You can do an easy test:

- Include a library, and compile your sketch. You will see (possibly) some difference.
- Now call a function from the library. Compile the sketch again, you will see the flash memory usage has increased. This means, before that, that function was not part of your compiled sketch.

A thing I would worry more about, is SRAM memory usage, but mostly buffers are created depending on the model, and SRAM is not wasted (since the Arduino Uno has only 2 KB for example).


body:
The Arduino IDE uses the gcc compiler.

Gcc is an optimizing compiler, and is quite good at it.  So basically it's going to do a good job of identifying and including only the functions you actually use in your code.

Unless you are quite experienced you will probably not do a better job than the compiler itself.


message:
APA106 random color when power applied

The APA106 RGB LED is usually blue when 5VDC is applied. Sometimes it is a random color when turning the power supply on and off. How to keep it a consistent color when power is applied?

Normal:
[![normal blue apa106][1]][1]

Sometimes:
[![sometimes random color apa106][2]][2]

It’s for an Arduino project, I’ve just isolated the problem to the LED. Dozens of these exhibit this behaviour. The PCB board in the pictures is just a breadboard power supply.

**Update:** DIN to GND still exhibits the same behaviour.

[![din to gnd still pink][3]][3]

Here is a demo of the problem. 90% of the time at power up the LEDs is blue, but occasionally the color is random like pink or white.

[YouTube link to a 38s clip of the problem manifesting][4]

**Update:** At Robert's suggestion, I modified the V-USB [bootloader][5] to send the control bits and timings to immediately turn off the APA106 LED. There is still an extremely brief blue pulse (or random color) because power applied to the LED is always faster than any CPU process. It's not perfect, but better.

  [1]: https://i.stack.imgur.com/QdAEk.jpg
  [2]: https://i.stack.imgur.com/xc1SO.jpg
  [3]: https://i.stack.imgur.com/gtHiQ.jpg
  [4]: https://youtu.be/bITeGnsc7T8
  [5]: https://github.com/ericdraken/micronucleus

body:
Wire it to the MCU such that power is first applied to the LED under control of the sketch when the sketch is prepared to immediately set the initial color you want. The time taken to accomplish the (power up, set initial color) will have to be less than the eye's ability to perceive the possible color glitch (which, being relatively slow compared to the Arduino, it should be pretty easy to do).

Update:
> There is still an extremely brief blue pulse

That remaining delay is probably the IDE's reset-pulse duration plus the Arduino board's R-C delay on the reset pin. It's probably the best you can do without a lot of hardware (e.g. a switch on every R/G/B pin, designed to power-up "off".)


message:
Write and read problem while interfacing 93LC46B EEPROM through SPI

I try to save and read data from 93LC46B EEPROM using SPI with Arduino UNO.
I'm following this article https://www.arduino.cc/en/Tutorial/SPIEEPROM .
So far I have correctly connected EEPROM pinout (as shown in 93LC46B EEPROM datasheet) with arduino MISO, MOSI, SS, CLK, I copied the code from link and here is the problem, I cant save data to EEPROM, it should be filled with buffer but it is not, whats more everytime I try to read data there are different values on same addresses. How can i solve this problem ? Thanks in advance

body:
The quick answer is that 93LC46B is not compatible with AT25HP512. You can not use that tutorial. There are many differences.

Have a look at this blog instead: http://owlsan.blogspot.com/2012/10/accessing-93c4693c46n-serial-eeprom.html


message:
Create one server in AP mode and another in station mode

I'm trying to connect one ESP8266 to WiFi as a WebServer in station mode and to another ESP8266 as a server (that has no web pages) in AP mode.

 The problem is both servers are being created in AP mode, between the ESP's, while one of them (the webserver) should be created in station mode and accessible from WiFi. The only way I can reach the webserver is connecting to the AP and accessing its IP (as access point) from my computer.

 What I wanted was to access the webserver connected to my WiFi using the IP that my router gave to the hosting ESP, while the two of them would communicate using the server without web pages.

 I've already tried using the same IP for both servers, inverting the order of creation of the servers and using both ```ESP8266WiFi.h``` and ```ESP8266WebServer.h```. I've read something about the later not working with too much code inside the loop and, since the web page I want is pretty simple, I'm using ```ESP8266WiFi.h```. Here's my code:

```arduino

#include <ESP8266WiFi.h>
//#include <ESP8266WebServer.h>

WiFiServer internalServer(81);
WiFiServer externalServer(80);
//ESP8266WebServer externalServer(80);
IPAddress IP(192, 168, 4, 15); // Default IP for the AP mode, the one I'm using.
IPAddress mask = (255, 255, 255, 0);
WiFiClient internalClient;
WiFiClient externalClient;

void setup() {

  Serial.begin(115200);

  pinMode(LED_BUILTIN, OUTPUT);

  WiFi.mode(WIFI_AP_STA);

  // Config. AP mode:
  WiFi.softAP("my-access-point", "my-password");
  WiFi.softAPConfig (IP, IP, mask);

    // This connection is ok:
  internalServer.begin();
  Serial.println("Internal server created.");
  while (!internalClient) { // waiting for the internal client to connect before continuing. This works fine.
    internalClient = internalServer.available();
  }
  Serial.println("Internal client found.");

  // Config. STA mode:
  Serial.print("Connecting to Wi-Fi");
  WiFi.begin("my-wifi", "my-wifi-password");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println(" Ready.");

  // Config. external server.
    // This connection isn't working
  externalServer.begin();
  Serial.print("External server created with IP: ");
  Serial.println(WiFi.localIP()); // This is the IP I expected to use to connect to the external server.
                                  // But it is accessible at 192.168.4.15.

void loop() {
  // handling external client:
  externalClient = externalServer.available();
  if(!externalClient) { return; } // proceed only when there is a request.
  String request = externalClient.readStringUntil('\r');
  Serial.println("Request: " + request);

  // The answer is just a hello world:
  String answer = "..."
  externalClient.println(answer)
  Serial.println("Answer: " + answer);

  handleInternalClient();
}

```

The internal client is supposed to turn on the builtin led when it receives "on" from the server and turn it off when it receives "off", and that is working fine so I think the code for it isn't necessary. If you need it, please ask.

What I want is the other ESP talking to this one through 192.168.4.15 in the AP network and my computer talking to it through whatever IP my router gives to it, in my WiFi.

body:
It is not documented, but you can construct WiFiServer or ESP8266WebServer with IP address. If you use the IP address of the AP, the server will be available only on the SoftAP. If you use the IP address of the station, the server will be available only on STA interface.

If the IP of the interface is known before `setup()`, you can simply define `WiFiServer internalServer(apIP, 81);` instead of `WiFiServer internalServer(81);`. But if the IP must be first evaluated in `setup()` (from DHCP, or config file), then the following example shows how to set WiFiServer IP and port in `setup()`.

    #include <ESP8266WiFi.h>

    WiFiServer internalServer(81);
    WiFiServer externalServer(80);

    void setup() {
      ...
      internalServer = WiFiServer(WiFi.softAPIP(), 81);
      externalServer = WiFiServer(WiFi.localIP(), 80);
      internalServer.begin();
      externalServer.begin();


message:
What is the difference between Tools > Board settings in Arduino IDE? ex: ESP32-Dev v. Huzzah32

I had a recent memory issue where the resolution was to change the Tools > Partition setting.  However this setting wasn't available in the Arduino IDE for the boards I was using (Huzzah32 and NodeMCU-32s).  I changed the board setting to ESP32-Dev Module, and the addition menu items under Tools appeared.  My project compiles and works fine now.

However it never occurred to me to set the Board to the "wrong" type.  What's the purpose of a vendor specific board setting when the more generic one appears to work fine?  What settings should you use and under what circumstance?

My guess is that the vendor specific board settings are more about the peripheral hardware on the boards (USB ports, LEDs, etc) and that the more of those you are using the more likely you'll need to use a board specific setting.   In my case, since my project uses just the WiFi and Bluetooth built into the ESP32 chip itself, that I'm ok, but if I was using a bunch of GPIO and other things I'd need to use the actual Huzzah32.  Is that right?

body:
For ESP32 boards the differences are very minor. In general an ESP32 is an ESP32. The only changes are name to pin mappings, and how to upload code.

There are a couple of different ESP32 modules, but in general all the boards use the same (cheapest) module.

If you look at the `pins_arduino.h` file for a variant you see that it is pretty much all in the format:

    static const uint8_t SDA = 21;
    static const uint8_t SCL = 22;

Just mapping names to pins. Note that some are special, like SDA and SCL above, which are used as defaults for the Wire library.

The biggest differences are in the boards.txt portion for the board. This is where any differences in the module will be defined.

In general though all the "specific" boards are just the "ESP32-Dev Module" with some options removed, and a new name give to it.  So you can usually use ESP32-Dev Module for any board as long as you select the right mode for things like flash.

One big benefit of using the correct board, though, is that a `#define` macro is provided identifying the board. If you want the same code to run differently on different boards (such as using different pins on different boards) you can use that macro to direct the flow of your code.


message:
Increasing distance of IR remote / transmitter

I am trying to set up my Arduino as a replacement remote control. The setup works and I can use it to turn on/off my things, for example my fan.

However, the working distance is quite short. Around a meter. The actual remote for my fan works across the distance of my apartment.

What can I do to improve the working distance of my Arduino remote? Does the LED need a back reflector or something? Does it need a different LED?

The LED I am using is this, it came in a bundle I purchased.
https://www.amazon.com/dp/B07PJC7WSQ/#detail-bullets

body:
I assume that the led you purchased just isn't as bright as the led that came with your remote.
As I've seen from your link you could quite easily swap the led from the board.
If the new led has the same voltage, the board should work just fine with any other led. Maybe just search for a brighter led with the same wavelength.

I don't think that a back reflector would have such a big effect to boost the range to the distance you need. Also I think it would be rather complicated to install one on the tiny board.


body:
Judging form the picture of the IR breakout board you shown, it seems that the board is drive the LED directly via Arduino GPIO pin. The current of the GPIO pin could supply is typically around 20mA @5v (and about 10mA @3v3) which is not sufficient. A typical 940nm IR LED has the spec like this:

    Max. Continuous forward current: 100mA
    Max. Forward Voltage: 1.5 typ., 1.8V max.@50mA

In order to drive the LED, a circuitry like this would be required:

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

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

<!-- End schematic -->

Assuming the LED has a voltage drop of 1.8v, and you are supply the circuit with 3.3v, the 18 ohm resistor should limit the LED current to about 83 mA ((3.3 - 1.8)/18 = 83mA) - safely under its maximum rating of 100 mA. Use a 20 ohms if want to be on the safer side. The transistor's emitter must be connected to the Arduino ground.


message:
Can I power 25 LED via USB?

So I'm currently working on a project where I build a WordClock. To display the current time I use WS2812B LEDs which should be white when turned on. Only about 25 leds per time will be turned on, the rest will be off. If my calculation is correct that should result in 1,5A (25leds x 60ma = 1500ma = 1,5A).
With the little power consumption of the Arduino Nano I think it won't exceed 2 amps at a time.
Is it safe to power this from a standard USB port or do I need some of the relatively overpriced (at least here in Germany) led power supply? What's the worst that could happen if I would exceed the amperage of the power supply? Would the LEDs just be dimmed or would it be dangerous in any way?

Thanks in advance

body:
Your calculation is correct. 25 LEDs on full white will draw 1.5A.

You cannot drive this from a standard USB port on your PC. These ports can give up to 500mA (higher currents for USB3.0 ports will only be available after additional negatiations - not possible with a Nano). When powering from such a port, the port will either go into emergency shutdown (reenabling after the next reboot), or you will damage the USB port beyond repair.

But you don't need an overpriced power supply, that is meant for these LEDs. The WS2812B LEDs work on 5V, so you can use any 5V DC wallwart power supply, for example a standard USB charger, that gives you at least 2A.

> What's the worst that could happen if I would exceed the amperage of the power supply?

In general you risk to damage the power supply, so that it won't work anymore. Drawing more power than allowed from a power supply is like a short, which is never good. Also too hot wires and such can cause fires.

But that is not always true. I tested a big strip of those LEDs on a simple USB charger myself one time. The charger was not rated high enough for all the LEDs. So the LEDs lit up for a very short time (like a flash) again and again with about 1s between each flash, as the USB charger tried to supply the voltage and did go into emergency shutdown again. This didn't hurt the USB charger, though I would not do this for very long. Also you cannot be sure, that your USB charger will do the same. (I also live in germany, so it might be the same case). Also look at the description of the chargers. Sometimes they write a high current into the title of multiple port chargers, but this current is distributed between the ports, so that you need multiple cables to draw the full current.

As USB chargers are quite cheap, I would suggest to use one of these. Pay extra attention to the current rating and stay well above your requirements (2A should be enough).

**Very important:** Be sure, that you don't draw the LEDs current through the Arduino. This would fry it's protection diode. Instead connect the LEDs power lines directly to the power supply, in parallel to the Arduino.


message:
Memory size issue with the struct

I am working on a project where I have to build an IR program that works with all of the AVR/Arduino boards to control the IR devices such as TV, DVD, etc. I am building a struct that can carry the Pronto code information and this is what I have so far:

    struct Pronto {
        char* code;
    public:
        Pronto(){}
        Pronto(char* code) {
            bool isValid = validateProntoCode(code);
            if(isValid)
                this->code = code;
        }
        Pronto toPronto(char* code) {
            Pronto cde(code);
            return cde;
        }
        void setPronto(char* code){
            bool isValid = validateProntoCode(code);
            if(isValid)
                this->code = code;
        }
        char* toString(){
            return code;
        }
        private:
        bool validateProntoCode(char* code) {
            if(!isInHex(code[strlen(code)-1]))
                return false;
            for (int i = 0; i < strlen(code); i++) {
                if (!isInHex(code[i]) && !(i % 5 == 4 ))
                    return false;
                if (i % 5 == 4 && code[i] != ' ')
                    return false;
                if (i % 5 == 0 && (!isInHex(code[i]) || !isInHex(code[i] + 1) || !isInHex(code[i] + 2) || !isInHex(code[i + 3])))
                    return false;
            }
            return true;
        }
        bool isInHex(char c) {
            char list[22] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','a','b','c','d','e','f'};
            for (int i = 0; i < 22; i++) {
                if (c == list[i])
                    return true;
            }
            return false;
        }
    };

This struct code
I can set the Pronto code, validate it, and get the string value from it.
Now, whenever I declare the struct inside the Arduino IDE:

    pronto.setPronto("0000 006D 0000 00BF 009F 0031 0030 0010 0010 0031");

I get this following message:

_____________________________________
Sketch uses 4082 bytes (12%) of program storage space. Maximum is 32256 bytes.

Global variables use 2137 bytes (104%) of dynamic memory, leaving -89 bytes for local variables. Maximum is 2048 bytes.

Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint.
________
Pictures:

https://prnt.sc/ohu4d9

https://prnt.sc/ohu4io

https://prnt.sc/ohu4m8

https://prnt.sc/ohu4pr

https://prnt.sc/ohu4tn

Basically, I just showed all my work on code I did. I commented out any global vars, nothing changed. BUT, when I comment "pronto.setPronto("0000 0000");", I get free space.
_________

So, how can I modify this struct in-order for it not to take allot of space?

---

The char* code right? That's the problem. Now can you help me modify code or at least tell me how I can resolve this.

body:
Based on your question I prepared a fresh sketch (single file) to test the issue.

The code:

    struct Pronto {
        char* code;
      public:
        Pronto() {}
        Pronto(char* code) {
          bool isValid = validateProntoCode(code);
          if (isValid)
            this->code = code;
        }
        Pronto toPronto(char* code) {
          Pronto cde(code);
          return cde;
        }
        void setPronto(char* code) {
          bool isValid = validateProntoCode(code);
          if (isValid)
            this->code = code;
        }
        char* toString() {
          return code;
        }
      private:
        bool validateProntoCode(char* code) {
          if (!isInHex(code[strlen(code) - 1]))
            return false;
          for (int i = 0; i < strlen(code); i++) {
            if (!isInHex(code[i]) && !(i % 5 == 4 ))
              return false;
            if (i % 5 == 4 && code[i] != ' ')
              return false;
            if (i % 5 == 0 && (!isInHex(code[i]) || !isInHex(code[i] + 1) || !isInHex(code[i] + 2) || !isInHex(code[i + 3])))
              return false;
          }
          return true;
        }
        bool isInHex(char c) {
          char list[22] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f'};
          for (int i = 0; i < 22; i++) {
            if (c == list[i])
              return true;
          }
          return false;
        }
    };

    Pronto pronto;

    void setup() {
      pronto.setPronto("0000 006D 0000 00BF 009F 0031 0030 0010 0010 0031");
    }

    void loop() {}

The verification procedure for ATmega328P returns:

    D:\Extra\Arduino\BatteryRestorer\BatteryRestorer.ino: In function 'void setup()':

    D:\Extra\Arduino\BatteryRestorer\BatteryRestorer.ino:50:71: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

       pronto.setPronto("0000 006D 0000 00BF 009F 0031 0030 0010 0010 0031");

                                                                           ^
    Sketch uses 844 bytes (2%) of program storage space. Maximum is 30720 bytes.
    Global variables use 83 bytes (4%) of dynamic memory, leaving 1965 bytes for local variables. Maximum is 2048 bytes.

Can you check if this one file sketch is still experiencing the issue? Maybe you installed and linked a library that allocates a lot of global variables.


body:
In your screen shots you are using string literals that are waaaay longer than in your sample code. I suspect using PROGMEM could be a way to work around. But why bothering with constant strings and verify and convert them at run time and not store them as raw data instead? (Also the outcome of the verification for a constant string literal will be always the same. So consider removing verification of your production code.)

```
uint16_t myParsedProntoCode[] = {
    0x0000, 0x006D, 0x0000, 0x00BF, 0x009F, 0x0031, 0x0030, 0x0010, 0x0010, 0x0031
};
```

This is much more space efficient as storing a nibble (4 bits) requires only 4 bits instead of 8 bits. So just half the space, not even taking the pointless whitespaces into account.


message:
Arduino communication protocol with python - beyond pyserial and Arduino example

TL;DR does someone know of a advance and reliable/redudent USB protocol for communicating between a raspberry pi and Arduino due (native port)

I am trying to learn how to build a little robot which I hope could be autonomous at some point. In terms of hardware I am using an Arduino Due and a raspberry pi 3. The former is connected to DC motors, servos, ultrasonic sensors, light sensors, etc... The pi is responsible for running the picam and sending controlles from an Xbox controller to the Arduino as well as running a django web interface.
Long story short, I am trying to have python reliably communicating with the Arduino over serialusb (using the native port) but with no luck. The simple communication protocol shown in the Arduino example is too weak. I found a GitHub project named arduino-robust-serial https://github.com/araffin/arduino-robust-serial which worked at first but for reasons which are quite long to discuss here was not enough.

My question is as follows: does someone know of a reliable serial protocol around which could be used to have a raspberry pi communicating with an Arduino over usb?

I hope I'm not too vague. But looking online I'm struggling to find resources regarding Arduino which are not beginner blinking light examples.

Thx

body:
Ok, after quite some time looking for something that would allow me to easily control an arduino with the raspberry pi, I found the [FIRMATA protocol][1] which allows one to communicate with the arduino through many languages. (a snippet from the github page for SEO purposes is shown at the end of this message).

From there I looked for through the python frameworks, and had a long chat with [MrYsLab][2] who helped me integrate the arduino Due to his [pymata][3] and [pymataExpress][4] frameworks. They work quite well and enable you to have a script that quickly and efficiently communicates with the arduino. I'm sure proper frameworks from [ros.org][5] or [gobot][6] are better. But [pymata][3] worked for me hence my answer to my own question.

 1. processing
    -  https://github.com/firmata/processing
    - http://funnel.cc
 2. python
    -  https://github.com/firmata/pyduino
    -  https://github.com/lupeke/python-firmata
    -  https://github.com/tino/pyFirmata
    -  https://github.com/MrYsLab/PyMata
    -  https://github.com/MrYsLab/pymata-aio
 3. perl
    -  https://github.com/ntruchsess/perl-firmata
    -  https://github.com/rcaputo/rx-firmata
 4. ruby
   -  https://github.com/hardbap/firmata
   -  https://github.com/PlasticLizard/rufinol
   -  http://funnel.cc
 5. clojure
   -  https://github.com/nakkaya/clodiuno
   -  https://github.com/peterschwarz/clj-firmata
 6. javascript
   -  https://github.com/jgautier/firmata
   -  http://breakoutjs.com
   -  https://github.com/rwldrn/johnny-five
 7. java
   -  https://github.com/4ntoine/Firmata
   -  https://github.com/kurbatov/firmata4j
   -  https://github.com/reapzor/FiloFirmata
 8. .NET
   -  https://github.com/SolidSoils/Arduino
   -  http://www.imagitronics.org/projects/firmatanet/
   -  https://github.com/wbadry/FirmataCSharpClientClass
 9. Flash/AS3
   -  http://funnel.cc
   -  http://code.google.com/p/as3glue/
 10. PHP
   -  https://bitbucket.org/ThomasWeinert/carica-firmata
   -  https://github.com/oasynnoum/phpmake_firmata
 11. Haskell
   -  http://hackage.haskell.org/package/hArduino
 12. iOS
   -  https://github.com/jacobrosenthal/iosfirmata
 13. Dart
   -  https://github.com/nfrancois/firmata
 14. Max/MSP
   -  http://www.maxuino.org/
 15. Elixir
   -  https://github.com/kfatehi/firmata
 16. Modelica
   -  https://www.wolfram.com/system-modeler/libraries/model-plug/
 17. golang
   -  https://github.com/kraman/go-firmata
 18. Qt/QML
   -  https://github.com/callaa/qfirmata
 19. Android/Kotlin
   -  https://github.com/xujiaao/android-firmata
 20. Smalltalk
   -  https://github.com/pharo-iot/Firmata

  [1]: https://github.com/firmata/protocol
  [2]: https://github.com/MrYsLab
  [3]: https://github.com/MrYsLab/pymata-aio
  [4]: https://github.com/MrYsLab/pymata-express
  [5]: http://www.ros.org
  [6]: https://gobot.io


message:
How can I pass multiple variables to a function?

Using the FastLED library, I want to light up multiple lights at once.

Currently I am passing in just one light to the function.

    spell( int LEDNumber )
    {
      FastLED.clear();
      leds[LEDNumber] = CRGB (255,255,255); //white
      FastLED.show();
      time = 500;
      delay(t);
    }

I would like to pass in more than just 1 light at a time.

body:
Easier than I thought. Found it while reading the docs. Imagine that. :)

To pass in multiple variables, just separate them with a comma.

Docs: https://www.arduino.cc/en/Reference/FunctionDeclaration

Relevant code:

    int myMultiplyFunction(int x, int y){
      int result;
      result = x * y;
      return result;
    }


body:
You may create a `struct` with "x" elements, one for each LED:

    struct ArrayOfBooleans {
       bool array[4];
    };

    ArrayOfBooleans myOutputArray;
    myOutputArray.array[0] = true;
    myOutputArray.array[1] = true;
    myOutputArray.array[2] = false;
    myOutputArray.array[3] = true;

    lightEmUp(myOutputArray);

    void lightEmUp(ArrayOfBooleans myOutputArray) {
       bool isFirstLightOn = myOutputArray.array[0];
       // etc
    }

NoTE: If you run into `Exception 9` issues (using this logic on another board), please check [this answer to another post][1]

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


message:
Is low memory warning based on a fixed number of on the actual sketch?

I have the following output of my sketch for the Arduino Mega so far:

    Sketch uses 25020 bytes (9%) of program storage space. Maximum is 253952 bytes.
    Global variables use 6919 bytes (84%) of dynamic memory, leaving 1273 bytes for
    local variables. Maximum is 8192 bytes.

    Low memory available, stability problems may occur.

I think 1273 bytes is not so less for most sketches, although mine is quite big (several thousand of lines, and I'm about half).

I was wondering if the IDE is so smart to statically analyze my code to see what my dynamic storage is (about 600 bytes) and/or calculates some expected stack size (several hundred bytes at least).

Or is it just a (very) safe fixed or percentage-based value?

body:
I just did some tests and found the answer.

    char a[6135];

    void setup()
    {
      a[0] = 0;
    }

    void loop()
    {
    }

This sketch does not give a warning:

    Sketch uses 660 bytes (0%) of program storage space. Maximum is 253952 bytes.
    Global variables use 6144 bytes (75%) of dynamic memory, leaving 2048 bytes for local variables. Maximum is 8192 bytes.

If I increase the array with 1, I get an error:

    Sketch uses 660 bytes (0%) of program storage space. Maximum is 253952 bytes.
    Global variables use 6145 bytes (75%) of dynamic memory, leaving 2047 bytes for local variables. Maximum is 8192 bytes.
    Low memory available, stability problems may occur.

Conclusion: below 2 KB (2048 bytes) of free space, the warning is shown.

I did the same test for the Uno, and there the warning is shown when less than 1536 bytes are free.

Both percentages are 75%, so the end conclusion is that the value is based on 75% of memory.


message:
maximum interrupt-based PWM frequency at 500 Hz

I need to control a 24 kHz ultrasonic transducer and decided to use an arduino uno I have lying around.

Using `tone()` or the atmega's hardware pwm is not very suitable because I need two 50/50 square waves with a phase difference of pi (which is equal to two XOR'ed pins) to switch the output polarity of the h-bridge synchronously. As the uC dosen't have anything else to do I wrote the following sketch where I just wait for an interrupt and toggle pins 2&3:

    bool do_task=false;
    void timer_init () {
      TCCR0A |= (1 << WGM01);
      OCR0A = 83;
      TIMSK0 |= (1 << OCIE0A);
      TCCR0B |= (1 << CS01);
    }
    ISR (TIMER0_COMPA_vect) {
      do_task=true;
    }

    bool state=false;
    void toggle() {
      state=!state;
      digitalWrite(2,state);
      digitalWrite(3,!state);

    }

    void setup() {
      pinMode(2,OUTPUT);
      pinMode(3,OUTPUT);
      timer_init();
    }

    void loop() {
      if(do_task) {
        do_task=false;
        toggle();
      }
    }

I expected the output to have a frequency of ~24 kHz, but it is 500 Hz instead.

From my understanding:

  - 16 MHz CPU frequency
  - timer0 prescaler is 8 (`TCCR0B |= (1 << CS01)`)
  - output compare value (`OCR0A`) is 83

would result in a frequency of `16 MHz / 8 / 83 = 24096,4 kHz` -but as I mentioned- it's 500 Hz and doesn't seem to depend on the prescaler.

body:
> what exactly is it that makes a simple function like digitalWrite() so damn slow??! Why isn't it just a wrapper function for direct port manipulation?

Well, it can take a variable as an argument. And the contents of the variable have to be looked up in a table to see which port and which bit.

If you use the [DigitalWriteFast](https://github.com/NicksonYap/digitalWriteFast) library then that turns your writes into direct port manipulation *providing you use constants*.

So you can use:

    digitalWriteFast(2,HIGH);  // or LOW

But not:

    digitalWriteFast(myPort,someState);  // assuming they are not constants

In fact you *can* send variables, but it degrades into the same slow calls that digitalWrite uses.

---

> I now decided not to use the arduino core

The core is absolutely fine. However you need to understand what it is doing. To be nice to newbies things like digitalWrite can take variables as arguments, so this sort of thing is possible:

    for (int i = 0; i < 13; i++)
      digitalWrite (i, HIGH);

---

As I hinted in a comment, you could do it all in the ISR:

    ISR (TIMER0_COMPA_vect) {
      static bool state;
      if (state)
        {
        digitalWriteFast(2,HIGH);
        digitalWriteFast(3,LOW);
        state = false;
        }
      else
        {
        digitalWriteFast(2,LOW);
        digitalWriteFast(3,HIGH);
        state = true;
        }
    }  // end of TIMER0_COMPA_vect

---

> Initially, I planned to read the frequency from a potentiometer after each interrupt, wouldn't this be easily possible in 8×83=664 cycles?

Analog reads (reads from the ADC) take around 104µs using the default ADC prescaler. That is, 1664 clock cycles. So, no, you can't read in that time. That is a hardware limitation. You can reduce the prescaler without losing much accuracy.

See [my page about the ADC](http://gammon.com.au/adc). Making the prescaler 16 rather than 128 will significantly increase speed with minimal accuracy loss.

To do that on the Uno:

    ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
    ADCSRA |= bit (ADPS2);                               //  16


body:
You wrote:

> Using [...] the atmega's hardware pwm is not very suitable because I
> need two 50/50 square waves with a phase difference of pi

I believe hardware PWM is the best solution to your problem. The PWM
outputs can be set to either “inverting” or “non-inverting” mode.
Set the two channels of a single timer to the same duty cycle, with one
in non-inverting mode and the other one in inverting mode, and you have
your complementary outputs.

Example using Timer 1:

```c++
const float SIGNAL_FREQUENCY = 24e3;
const uint16_t HALF_PERIOD = round(F_CPU / SIGNAL_FREQUENCY / 2);
const uint16_t PERIOD = 2 * HALF_PERIOD;

int main()
{
    /* Set the PWM pins as outputs. */
    DDRB |= _BV(PB1);  // digital  9 = PB1 = OC1A
    DDRB |= _BV(PB2);  // digital 10 = PB2 = OC1B

    /* Configure Timer 1. */
    ICR1   = PERIOD   - 1;
    OCR1A  = PERIOD/2 - 1;
    OCR1B  = PERIOD/2 - 1;
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(COM1B0)  // inverting PWM on OC1B
           | _BV(COM1B1)  // ditto
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)  // ditto
           | _BV(WGM13)  // ditto
           | _BV(CS10);  // clock at F_CPU, start timer
}
```


message:
Header file or library to test i2c FRAM?

I found a header file to test a i2c eeprom [24LC256][1], but I used this to test my eeprom [CAT24C32][2].The test sketch works fine. I modified the line BLOCKSIZE 8 because my eeprom have 32byte page write only.

I have also a FRAM [MB85RC256V][3], I am wondering if can I use the same header to test the FRAM. I saw the command byte write are same like eeprom, but the page write have a different side of buffer, it says have 32Kbytes. Can I use it?

If I made a mistake please help me. Thanks very much!

Here the .h
<!-- language-all: lang-cpp -->
```
#ifndef  EEPROM_ROUTINES
#define  EEPROM_ROUTINES

#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif
#include <Wire.h>

#define BLOCKSIZE 8
#define I2CADDR 0x57
#define BLOCKSIZE_READ 30

template <class T>
uint16_t writeObjectSimple(uint8_t i2cAddr, uint16_t addr, const T& value){

      const uint8_t* p = (const uint8_t*)(const void*)&value;
      uint16_t i;
      for (i = 0; i < sizeof(value); i++){
            Wire.beginTransmission(i2cAddr);
                  Wire.write((uint16_t)(addr >> 8));  // MSB
                  Wire.write((uint16_t)(addr & 0xFF));// LSB
                  Wire.write(*p++);
            Wire.endTransmission();
            addr++;
            delay(5);  //max time for writing in 24LC256
      }
      return i;
}

template <class T>
uint16_t readObjectSimple(uint8_t i2cAddr, uint16_t addr, T& value){

            uint8_t* p = (uint8_t*)(void*)&value;
            uint8_t objSize = sizeof(value);
            uint16_t i;
            for (i = 0; i < objSize; i++){
                  Wire.beginTransmission (i2cAddr);
                        Wire.write((uint16_t)(addr >> 8));  // MSB
                        Wire.write((uint16_t)(addr & 0xFF));// LSB
                  Wire.endTransmission();
                  Wire.requestFrom(i2cAddr, (uint8_t)1);
                  if(Wire.available()){
                        *p++ = Wire.read();
                  }
                  addr++;
            }
            return i;
}

template <class T>
uint16_t writeObject(uint16_t addr, const T& value){
      const uint8_t* p = (const uint8_t*)(const void*)&value;

      Wire.beginTransmission(I2CADDR);
      Wire.write((uint16_t)(addr >> 8));        // MSB
      Wire.write((uint16_t)(addr & 0xFF));      // LSB

      //in the loop: counts the bytes we may send before
      //our block becomes full
      //but initialise it to the number of bytes up to the
      //next 16-byte aligned address
      uint8_t blockBytes = (addr/BLOCKSIZE + 1)*BLOCKSIZE - addr;
      uint16_t i;
      for (i = 0; i < sizeof(value); i++){
            if (blockBytes == 0){
                  //block is full;
                  Wire.endTransmission(); //dispatch the buffer
                  delay(5);
                  //restart new block
                  addr = (addr/BLOCKSIZE + 1)*BLOCKSIZE;
                  blockBytes = BLOCKSIZE;
                  Wire.beginTransmission(I2CADDR);
                  Wire.write((uint16_t)(addr >> 8));  // MSB
                  Wire.write((uint16_t)(addr & 0xFF));// LSB
            }
            Wire.write(*p++); //dispatch the data byte
            blockBytes--;     //decrement the block space
      }
      Wire.endTransmission();
      delay(5);   //required write delay 5ms
      return i;
}

template <class T>
uint16_t readObject(uint16_t addr, T& value){
      uint8_t* p = (uint8_t*)(void*)&value;

      Wire.beginTransmission(I2CADDR);
            Wire.write((uint16_t)(addr >> 8));        // MSB
            Wire.write((uint16_t)(addr & 0xFF));      // LSB
      Wire.endTransmission();

      //counts the bytes we may read before buffer is depleted
      uint8_t   blockBytes = 0;
      uint16_t  objSize = sizeof(value);
      uint16_t  i;
      for (i = 0; i < objSize; i++){
            if (blockBytes==0){
               //we need a new block
               blockBytes = BLOCKSIZE_READ;
               if (objSize < blockBytes) blockBytes = objSize;
               //get the new block
                Wire.requestFrom((uint8_t)I2CADDR, blockBytes);
            }
            if(Wire.available()){
                  //read a byte from buffer
                  *p++ = Wire.read();
                  blockBytes--;
            }
      }
      return i;
}

#endif

```
Here the skecth to test eeprom

```
#include <Wire.h>
#include "eeprom_routines.h" //definitions of the functions:
                             //writeObject, readObject,
                             //writeObjectSimple, readObjectSimple
#define BLOCK_OPERATIONS 0

#if BLOCK_OPERATIONS>0
  #define __WRITE__(ad, obj) writeObject(ad,(obj))
  #define __READ__(ad, obj) readObject(ad,(obj))
#else
  #define __WRITE__(ad, obj) writeObjectSimple(0x57,ad,(obj))
  #define __READ__(ad, obj)  readObjectSimple(0x57,ad,(obj))
#endif
#define MEM_ADDR_MULTI 3458

//This is the structure we write and read from EEPROM
class MyData{
      long result;
public:
      float  f1;
      float  f2;
      double f3;
      int    i1;
      long   i2;
      long   i3;
      bool  negative;

      long getResult(){
            return result;
      }
      long calcResult(){
            //makes a calculation with its data
            //and stores the result to a private variable
            long    i = (i2+i3)/i1;
            double  f = f3/(f1+f2);
            result = f/i;
            //round off
            result += result>0 ? 0.5 : -0.5;
            if (negative) result=-result;
            return result;
      }
      MyData() : result(0){   }
};

void setup(){
      Serial.begin(9600);
      Wire.begin();

      MyData data[5];

      //data[0] - result should be 20
      data[0].i1 = 10;
      data[0].i2 = 150000;
      data[0].i3 = 350000;
      data[0].f1 = 0.5;
      data[0].f2 = 2.5;
      data[0].f3 = 3.0E+6;
      data[0].negative = false;

      //data[1] - result should be -40
      data[1].i1 = data[0].i1;
      data[1].i2 = data[0].i2;
      data[1].i3 = data[0].i3;
      data[1].f1 = data[0].f1;
      data[1].f2 = data[0].f2;
      data[1].f3 = 2*data[0].f3;
      data[1].negative = true;

      //data[2] - result should be 80
      data[2].i1 = data[0].i1;
      data[2].i2 = data[0].i2;
      data[2].i3 = data[0].i3;
      data[2].f1 = data[0].f1;
      data[2].f2 = data[0].f2;
      data[2].f3 = 4*data[0].f3;
      data[2].negative = false;

      //data[3] - result should be -20
      data[3].i1 = data[0].i1;
      data[3].i2 = -data[0].i2;
      data[3].i3 = -data[0].i3;
      data[3].f1 = data[0].f1;
      data[3].f2 = data[0].f2;
      data[3].f3 = data[0].f3;
      data[3].negative = false;

      //data[4] - result should be -2
      data[4].i1 = data[0].i1;
      data[4].i2 = -data[0].i2;
      data[4].i3 = -data[0].i3;
      data[4].f1 = data[0].f1*10;
      data[4].f2 = data[0].f2*10;
      data[4].f3 = -data[0].f3;
      data[4].negative = true;

      Serial.println ("Data before writing to eeprom");
      for (int i=0; i<5; i++){
            data[i].calcResult();
            Serial.print("data-"); Serial.print(i);
            Serial.print(": result = ");
            Serial.println(data[i].getResult());
      }
      Serial.print("Size of each object: ");
      Serial.println(sizeof(MyData)) ;

      Serial.println ("Writing data to eeprom");
      int memaddr = MEM_ADDR_MULTI;
      long t0 = millis();
      for (int i=0; i<5; i++){
            memaddr += __WRITE__(memaddr, data[i]);
      }
      long t1 = millis();
      Serial.print ("...writing finished. Elapsed time: ");
      Serial.println(t1-t0);
      delay(1000);

      Serial.println ("Reading data from eeprom");
      MyData read[5];
      t0 = millis();
      memaddr = MEM_ADDR_MULTI;
      for (int i=0; i<5; i++){
            memaddr += __READ__(memaddr, read[i]);
      }
      t1 = millis();
      Serial.print ("Time to read: "); Serial.println(t1-t0);

      for (int i=0; i<5; i++){
            Serial.print ("Read object: #");
            Serial.println(i);
            long storedResult = read[i].getResult();
            Serial.print ("  >stored result = ");
            Serial.println(storedResult);
            long newResult = read[i].calcResult();
            Serial.print ("  >recalculated result = ");
            Serial.println(newResult);
            if (storedResult== newResult &&
                  storedResult==data[i].getResult() )
                  Serial.println ("SUCCESS");
            else  Serial.println ("FAIL");
      }
}

void loop() {
}

```
Here the serial output of eeprom CAT24C32 test

```
Data before writing to eeprom
data-0: result = 20
data-1: result = -40
data-2: result = 80
data-3: result = -20
data-4: result = -2
Size of each object: 27
Writing data to eeprom
...writing finished. Elapsed time: 126
Reading data from eeprom
Time to read: 15
Read object: #0
  >stored result = 20
  >recalculated result = 20
SUCCESS
Read object: #1
  >stored result = -40
  >recalculated result = -40
SUCCESS
Read object: #2
  >stored result = 80
  >recalculated result = 80
SUCCESS
Read object: #3
  >stored result = -20
  >recalculated result = -20
SUCCESS
Read object: #4
  >stored result = -2
  >recalculated result = -2
SUCCESS

```

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/20001203U.pdf
  [2]: https://www.onsemi.com/pub/Collateral/CAT24C32-D.PDF
  [3]: https://www.fujitsu.com/us/Images/MB85RC256V-DS501-00017-3v0-E.pdf

body:
At Fujitsu's [site](https://www.fujitsu.com/global/products/devices/semiconductor/memory/fram/lineup/i2c-1m-rc1mt/press-new.html) is said

> Furthermore, applications that have used other products with I2C interfaces, such as EEPROMs and microcontrollers, can now replace EEPROMs, with the new FRAM products

So you can use it without any modifications in your code.


message:
src folder in sketch structure and include library from subfolder

My Arduino/PlatformIO libraries folder

    libraries
    └── cleaner_robot
        └── TB6612_Dual
            ├── tb6612_dual.h
            └── tb6612_dual.cpp

I used this code to innclude it:

    #include <TB6612_Dual/tb6612_dual.h>

But the compilation has errors like "undefinded variables, undefinded reference,...etc"

This is my sketch folder

    Cleaner_Robot
    └── src
        └── TB6612_Dual
            ├── tb6612_dual.cpp
            └── tb6612_dual.h

If i use this code, all is ok

    #include "src/libs/TB6612_Dual/tb6612_dual.h"

So the question is how to include if header file is in a sub folder of a folder in libraries folder of Arduino/PlatformIO ?, i has searched for many things, but cant help.
I also read about src folder allowed in Arduino, but where can find an official announcement/manual for this structure ?, cant find much about this

Thanks  :)

body:
I could include header files in subfolder after including root header file.

```
#include <TB6612_Dual.h>
#include <TB6612_Dual/tb6612_dual.h>
```

```
TB6612_Dual
└── src
    ├── TB6612_Dual.h << Add this empty file.
    └── TB6612_Dual
        ├── tb6612_dual.cpp
        └── tb6612_dual.h
```

Examples:

- [utils_asukiaaa/examples/string/string.ino](https://github.com/asukiaaa/utils_asukiaaa/blob/d3e59913ba2bcb2f6866865791baa71592b01456/examples/string/string.ino#L1-L2)
- [utils_asukiaaa/src/utils_asukiaaa/string.h](https://github.com/asukiaaa/utils_asukiaaa/blob/d3e59913ba2bcb2f6866865791baa71592b01456/src/utils_asukiaaa/string.h)
- [utils_asukiaaa/src/utils_asukiaaa/string.cpp](https://github.com/asukiaaa/utils_asukiaaa/blob/d3e59913ba2bcb2f6866865791baa71592b01456/src/utils_asukiaaa/string.cpp)
- [utils_asukiaaa/src/utils_asukiaaa.h](https://github.com/asukiaaa/utils_asukiaaa/blob/d3e59913ba2bcb2f6866865791baa71592b01456/src/utils_asukiaaa.h)


message:
Sending multiple byte data from Arduino as Slave on SPI

I have been working around the teardown of an induction cooktop and thought of having a tweak in the system. So far, I have deduced following circuitry out of the cooktop-
There are two devices communicating with each other in 3-wire SPI mode. The master, which controls power management and Induction circuitry, continuously sends commands and data to the slave. The slave, which is [TM1628][1], receives the master commands and data, then accordingly displays the data on the seven segment or responds with the switch pressed, if any.[![enter image description here][2]][2]

The above picture explains it better. Now, I thought of replacing TM1628 with an Arduino. So far so good. I gathered all the data that was being sent by the master and the reply sent by the slave.

But, when I started to code, I got stuck in one place. So the data as sent by the master and its response looks like this -

**(Master to Slave)**Command1 - Command2 - Data1 - Data2 - ... - Data 14 - Command1 - Command2 - **(Slave to master)**Data1 - Data2 - ... - Data5 - **(And now the repetition)**

When the master is sending the data, I have no issues as the data will continuously be read by Arduino and I can take the action accordingly.
But when the Arduino (Working as a slave) needs to send continuously 5 streams of data, depending only on the clock input timing from the master, how could I know that one stream has been written and now the next data has to be written to the SPDR register.

  [1]: http://aitendo3.sakura.ne.jp/aitendo_data/product_img/ic/LED-driver/TM1628english.pdf
  [2]: https://i.stack.imgur.com/p3kSt.jpg

body:
With SPI there is no such thing as "sending" and "receiving".  It is a full duplex operation every time. Whenever the master runs the clock the slave both receives bits from the master *and simultaneously* sends bits *to* the master.

These operations are inseparable.

Whatever mechanism you are using to recognise "A byte has arrived from the master" is the *same* mechanism that you use for filling the SPDR register. The bytes where you "send" data to the master are actually bytes where the master is sending *you* data, but you don't care about what that data is. Just like when the master is sending you "commands" you are sending the master data (which you haven't specified) and the master "doesn't care" what that data is.

It's up to you to keep track of how many bytes the master has clocked in and out, and to say "For bytes 19-23 the master is expecting valid data, so I need to make sure that I put data into the SPDR for those bytes".


message:
Optimizing code to use less Flash Memory and SRAM

I'm trying to reduce my sketch size and managed to reduce both SRAM and Flash memory.

    From:
    1570 SRAM - 32144 Flash memory
    To:
    644  SRAM - 19458 Flash memory

This are what I've done so far:

**✓** Enabling LTO

**✓** Using PROGMEM

**✓** Dropping `string` and using `char`

**✓** Dropping bootloader

**✓** Using port manipulation

**✓** Using registers to declare pins output/input

**✓** Removing/Optimizing/Combining; unnecessary/repeated codes in the sketch

*Using EEPROM is not an option for me.*

What else i can do to take optimization one or two step further?

body:
What you can do in addition to the items you mentioned:

**SRAM reduction**

- Use the smallest amount of data type for integers, e.g. use an 8 bit data type instead of the default integer, this saves you one byte for every variable. See remark below about types. I made my own types (if not existing) for int32_t, uint32_t, int16_t, uint16_t, int8_t and uint8_t and always use the smallest possible.
- Use unsigned instead of signed for types that cannot be negative. This might save you one byte if you can prevent using an unsigned byte instead of a signed int because a value can be in range [128..255]. The same for unsigned int instead of signed long.
- Use bit fields if you use multiple booleans inside a struct or class. Make sure the bit fields are declared consecutively.
- Pack data in smart structures ... I.e. if you have two variables, where one can be 0..7 and another can also be 0..7, store this together using bit fields (in combination with boolean to bit field above).
- Prevents float/doubles (see KIIV's comment below), instead:
- Instead of using a float, multiply the value by the needed accuracy and store it in an integer (if you don't need high accuracy and it fits in the integer type).
- In case you need a lot of strings to be stored, and those strings do not have characters above 128, you can save 1 bit per byte, of course this means quite some programming work to handle 7 bits 'ASCII' characters.
- The same, if you have to store a lot of values that can be e.g. 0 to 50, you can use 6 bits instead of 8 bits; you cannot use bit fields, but you can make a smart array and program your own get/set functions to access the 6 bit values.
- If you use libraries which declare big buffers, try to minimize those buffers, this might cause to copy them and manually change them yourself.
- Prevent your own buffers to be made global, instead use them as a local variable temporarily when you need them. If you have two of such buffers, you don't have both buffers allocated at the same time; note however, that during execution, that buffer still needs space (so you have to calculate or make a guess/estimation what the maximum stack size will be).

**Flash Reduction**

- Don't use duplicated code blocks, but make functions with parameters to differ between the differences of the duplicated code.
- Instead of lookup tables, create a function that calculates it (if possible). Of course the gain depends on the length of the lookup table and the length of the function.
- Instead of debugging strings, use numbers.

**Both SRAM/Flash Reduction**

- Split your application over multiple MCUs, of course this adds some kind of communication protocol (UART, I2C, SPI).


body:
*I'm having flashbacks to my early days as a C programmer in the 80's.*

Some thoughts in addition to all of the excellent advice already given ...

- Depending on how much data your application uses, you may want to
   read / write data to an SD card (or other external storage).
   While there is a certain amount of
   overhead for the libraries, the payoff is you then have virtually
   unlimited storage.  This is the equivalent of how we used to store
   data on 5 1/4" diskettes back in the old days.

-  Avoid static variables whenever possible.

-  Keep the scope of a variable as small as possible.

-  As a philosophy you should consider `unsigned char` to be your
   default data type and only 'upgrade' to a bigger footprint when your
   code requires.


message:
serial port through Rx and Tx want work

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

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

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

  [1]: https://i.stack.imgur.com/mvjGw.png
  [2]: https://i.stack.imgur.com/pRcWv.png
  [3]: https://i.stack.imgur.com/UxNUe.jpg

my serial connection prints rubbish, but it systematic, so it's not just random as you see on image 1, any help would be appreciated

other info:

the first image of the serial monitor of COM6 is my own serial connection, image nr. 2 is the serial monitor of COM4 which already uses the onboard serial to USB
the last image shows how I made my own serial connection

the 2 black cables are providing around 4 volts, I know these are not necessary cause the USB already provides 5 volts and ground

and oh ye, normally the USB on the last image would be connected to my pc ofc

body:
You're using a USB to RS-232 adaptor. That is wrong.

RS-232 is not (electrically) the same as UART.  Not only is the logic inverted, but it uses ±10V NRZ signalling.

That means that when the UART expects a 3.3V HIGH signal the adapter is sending it a -10V signal. When it's expecting a 0V LOW signal it's being sent a +10V signal.

So yes, it's gibberish - it's getting the opposite of what it expects to see - and the excess and negative voltages risk damaging your ESP. Fortunately the currents involved are usually so low that it doesn't damage it straight away, but with prolonged use you can probably kiss your ESP goodbye.

Disconnect that dongle immediately and get a proper USB to UART adapter.


body: Just check the code by running on all different Baud-rates (in the serial monitor) ..It should normally work on the rate u have declared in the code.


message:
How can I assign a variable to a function output in Arduino?

I'm trying to assign the output of my function (which adjusts a DAC output) to a variable so I can print and display it in my serial monitor. Here's the code

    #include <Wire.h>
    #include <Adafruit_MCP4725.h>

    Adafruit_MCP4725 dac;

    int volza;

    void setup() {
      Serial.begin(38400);
      Serial.println("Hello!");
      dac.begin(0x60);
    }

    void loop() {
        volza = dac.setVoltage(1095, 1); // THIS IS THE PROBLEM
        Serial.println(volza);
    }

I am receiving an error because of the commented line. I think it's because I am trying to return a value while inside a void loop. How do you fix this?

body:
The `setVoltage` method has the following prototype:

    void setVoltage( uint16_t output, bool writeEEPROM );

This means it does not return a value.

If you expect to return 1095, why not write:

    volza = 1095;
    setVoltage(volza, 1);
    Serial.println(volza);

Some background information:

Assume you want to have the library a `getVoltage` method, than this is possible (you have to make a copy in your own project of the file and add the method. However, I'm not sure how easy it is to get the value from the EEPROM. If it is not easy, there is some programming work to do. Another solution is to store the value in memory, but that means some extra bytes from the scarce free SRAM. Also, in theory the content could be changed already (if another MCU would have access to the EEPROM too).