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

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

Thank you @Majenko. Will look into code examples more and try some stuff out.

When you say header file, you mean C++ .h and .cpp files. I have to define some of the functions in a .h and then do the implementation in the .cpp like normal C++. I don't know why, but when I heard header file, it sounded to me like just one file. https://www.youtube.com/watch?v=2pxYEwaMtaI

.h and .CPP files are not bound together in pairs. You can have one without the other. .h files are a convenient way of sharing chunks of code between .c and .CPP files. .CPP files get compiled.

C++ has no concept of "header file". That is all handled by the C Preprocessor (confusingly called CPP). When you #include a file it is literally included verbatim at that point. C++ doesn't know about it - it only sees the content.

Thanks - Majenko. Looked up more stuff on preprocessing and https://www.tutorialspoint.com/cprogramming/c_header_files.


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

a few questions back I answered a similar question with example https://arduino.stackexchange.com/questions/67170/hardwareserial-indexing-array

is this a school assignment?

@jsotola No it is not

You can't. The C++ language doesn't support arrays of
references. You have the choice to either create an array of
objects:
timeOUT TO[] = {timeOUT("SW0",TIMEOUT_SW0), timeOUT("SW1",TIMEOUT_SW1);}

or an array of pointers:
timeOUT *TO[] = { &timeOut_SW0, &timeOut_SW1 };

timeout_Switch:243:34: error: request for member 'remain' in 'TO[i]', which is of pointer type 'timeOUT*' (maybe you meant to use '->' ?)                          if(TO[i].remain()>0) {                                   ^

I upvoted this answer, and going to delete mine since it's wrong.

I chose 2nd option you offered

source: Stack Exchange

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

sort: votes


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

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.

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


text:
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) with my Arduino Uno, and am trying to do that using an NPN transistor (2N3904) as a switch, as shown in this diagram.

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?

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 from the motor's inductive coils. Without a flyback diode you run the risk of destroying your transistor.

The transistor is 2N3904. The motor is FA-130, I will update the question with that info. What specs do I compare? Arduino "Output Current Limit", transistor "peak collector current", and DC motor "Stall current"?

Collector current is 200mA, its peak is 300mA. DC motor's "no load current" is 150mA, and Arduino's "output current limit" is 500mA~1A. It seems like the motor should draw enough current to at least start turning?

Arduino has no output current limits. If you attempt to draw too much current, the 5V regulator may just overheat and shutdown, or it may fail catastrophically, or the reverse voltage protection diode may die.  If current is coming from the USB connection, the USB polyfuse may overheat and open, or the PC for example might complain of a surge and shut down the port.

The IO pins are similarly not current limited.  You may have blown the pin driving the transistor base.  The base pin acts like a diode to Gnd, with Vbe from 0.6V to 0.85V  https://www.mccsemi.com/pdf/Products/2N3904(TO-92).pdf  If the '328P is hot to the touch, that's an indication you blew the output pin's internal protection diodes.  Replace the chip.  If not, try a different pin and put a 120 to 150 ohm resistor between the Arduino pin and the transistor base to limit current flow.

@CrossRoads I thought the Arduino's 5V regulator had a protection circuit and would shut down if you drew too much current. I was mistaken?

I would say you are partially mistaken.  I have answered numerous questions in the Arduino.cc forum where the regulator failed outright from overheating. At the same time, I have personnally seen it work as intended. I made a project powering 4 MAX7219 chips driving 8x8 LED matrices. Powered from 9V, after a few minutes the regulator would shutdown, restart, shutdown, restart. Powered from 7.5V, the power was steady.  So I would offer that whether the shutdown works as intended seems to depend on how fast the regulator heats up. 12V into the barrel jack and high current is a no-go.

@CrossRoads I doubt that I've blown the pin as the setup above does work when I switch out the motor for an LED (as described in my question). I also tried using a separate power source for the motor (but connected the grounds together) but still no movement on the motor.


text:
Can you start/stop a code from the serial monitor?
pressing and number in the serial monitor to start code and stop code.

I'm glad that you got a satisfying answer, but note that questions like yours are often quickly closed and deleted as low quality. I hope you'll do a better job next time.

@DmitryGrigoryev o and a k

This can be done by using the Serial.read()command as referenced in the Arduino documentation here.
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
  }
}

does the code runs continuously after inputting the command or it only runs once?

It runs continuously.


text:
Unable to upload to Arduino Uno From Raspberry Pi
I am trying to upload code to my Arduino Uno from my Raspberry Pi 3B+ and have been following this guide.
After following the instructions and trying to upload, I received this error message.
pi@Positron-Pi:~/sketchbook $ make upload
-------------------------
Arduino.mk Configuration:
- [AUTODETECTED]       CURRENT_OS = LINUX
- [USER]               ARDUINO_DIR = /usr/share/arduino
- [COMPUTED]           ARDMK_DIR = /usr/share/arduino (relative to Common.mk)
- [AUTODETECTED]       ARDUINO_VERSION = 105
- [DEFAULT]            ARCHITECTURE =
- [DEFAULT]            ARDMK_VENDOR = arduino
- [DEFAULT]            ARDUINO_SKETCHBOOK = /home/pi/sketchbook
- [BUNDLED]            AVR_TOOLS_DIR = /usr/share/arduino/hardware/tools/avr (in Arduino distribution)
- [COMPUTED]           ARDUINO_LIB_PATH = /usr/share/arduino/libraries (from ARDUINO_DIR)
- [COMPUTED]           ARDUINO_VAR_PATH = /usr/share/arduino/hardware/arduino//variants (from ARDUINO_DIR)
- [COMPUTED]           BOARDS_TXT = /usr/share/arduino/hardware/arduino//boards.txt (from ARDUINO_DIR)
- [USER]               USER_LIB_PATH = /home/pi/sketchbook/libraries
- [DEFAULT]            PRE_BUILD_HOOK = pre-build-hook.sh
- [USER]               BOARD_TAG = uno
- [COMPUTED]           CORE = arduino (from build.core)
- [COMPUTED]           VARIANT = standard (from build.variant)
- [COMPUTED]           OBJDIR = build-uno (from BOARD_TAG)
- [COMPUTED]           ARDUINO_CORE_PATH = /usr/share/arduino/hardware/arduino//cores/arduino (from ARDUINO_DIR, BOARD_TAG and boards.txt)
- [DETECTED]           MONITOR_BAUDRATE = 9600  (in sketch)
- [DEFAULT]            OPTIMIZATION_LEVEL = s
- [DEFAULT]            MCU_FLAG_NAME = mmcu
- [DEFAULT]            CFLAGS_STD = -std=gnu11 -flto -fno-fat-lto-objects
- [DEFAULT]            CXXFLAGS_STD = -std=gnu++11 -fno-threadsafe-statics -flto
- [COMPUTED]           DEVICE_PATH = /dev/tty* (from MONITOR_PORT)
- [DEFAULT]            FORCE_MONITOR_PORT =
- [AUTODETECTED]       Size utility: AVR-aware for enhanced output
- [COMPUTED]           BOOTLOADER_PARENT = /usr/share/arduino/hardware/arduino//bootloaders (from ARDUINO_DIR)
- [COMPUTED]           ARDMK_VERSION = 1.5
- [COMPUTED]           CC_VERSION = 5.4.0 (avr-gcc)
-------------------------
mkdir -p build-uno
make reset
make[1]: Entering directory '/home/pi/sketchbook'
/usr/bin/ard-reset-arduino  /dev/tty36
Traceback (most recent call last):
  File "/usr/bin/ard-reset-arduino", line 45, in <module>
    ser = serial.Serial(args.port[0], 115200)
  File "/home/pi/.local/lib/python2.7/site-packages/serial/serialutil.py", line 240, in __init__
    self.open()
  File "/home/pi/.local/lib/python2.7/site-packages/serial/serialposix.py", line 268, in open
    raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 13] could not open port /dev/tty36: [Errno 13] Permission denied: '/dev/tty36'
/usr/share/arduino/Arduino.mk:1478: recipe for target 'reset' failed
make[1]: *** [reset] Error 1
make[1]: Leaving directory '/home/pi/sketchbook'
/usr/share/arduino/Arduino.mk:1454: recipe for target 'upload' failed
make: *** [upload] Error 2

After this I ran the command with root privileges and got this.
pi@Positron-Pi:~/sketchbook $ sudo make upload
-------------------------
Arduino.mk Configuration:
- [AUTODETECTED]       CURRENT_OS = LINUX
- [USER]               ARDUINO_DIR = /usr/share/arduino
- [COMPUTED]           ARDMK_DIR = /usr/share/arduino (relative to Common.mk)
- [AUTODETECTED]       ARDUINO_VERSION = 105
- [DEFAULT]            ARCHITECTURE =
- [DEFAULT]            ARDMK_VENDOR = arduino
- [DEFAULT]            ARDUINO_SKETCHBOOK =
- [BUNDLED]            AVR_TOOLS_DIR = /usr/share/arduino/hardware/tools/avr (in Arduino distribution)
- [COMPUTED]           ARDUINO_LIB_PATH = /usr/share/arduino/libraries (from ARDUINO_DIR)
- [COMPUTED]           ARDUINO_VAR_PATH = /usr/share/arduino/hardware/arduino//variants (from ARDUINO_DIR)
- [COMPUTED]           BOARDS_TXT = /usr/share/arduino/hardware/arduino//boards.txt (from ARDUINO_DIR)
- [USER]               USER_LIB_PATH = /home/pi/sketchbook/libraries
- [DEFAULT]            PRE_BUILD_HOOK = pre-build-hook.sh
- [USER]               BOARD_TAG = uno
- [COMPUTED]           CORE = arduino (from build.core)
- [COMPUTED]           VARIANT = standard (from build.variant)
- [COMPUTED]           OBJDIR = build-uno (from BOARD_TAG)
- [COMPUTED]           ARDUINO_CORE_PATH = /usr/share/arduino/hardware/arduino//cores/arduino (from ARDUINO_DIR, BOARD_TAG and boards.txt)
- [DETECTED]           MONITOR_BAUDRATE = 9600  (in sketch)
- [DEFAULT]            OPTIMIZATION_LEVEL = s
- [DEFAULT]            MCU_FLAG_NAME = mmcu
- [DEFAULT]            CFLAGS_STD = -std=gnu11 -flto -fno-fat-lto-objects
- [DEFAULT]            CXXFLAGS_STD = -std=gnu++11 -fno-threadsafe-statics -flto
- [COMPUTED]           DEVICE_PATH = /dev/tty* (from MONITOR_PORT)
- [DEFAULT]            FORCE_MONITOR_PORT =
- [AUTODETECTED]       Size utility: AVR-aware for enhanced output
- [COMPUTED]           BOOTLOADER_PARENT = /usr/share/arduino/hardware/arduino//bootloaders (from ARDUINO_DIR)
- [COMPUTED]           ARDMK_VERSION = 1.5
- [COMPUTED]           CC_VERSION = 5.4.0 (avr-gcc)
-------------------------
mkdir -p build-uno
make reset
make[1]: Entering directory '/home/pi/sketchbook'
/usr/bin/ard-reset-arduino  /dev/tty36
Traceback (most recent call last):
  File "/usr/bin/ard-reset-arduino", line 46, in <module>
    ser.setDTR(False)
  File "/usr/lib/python2.7/dist-packages/serial/serialutil.py", line 581, in setDTR
    self.dtr = value
  File "/usr/lib/python2.7/dist-packages/serial/serialutil.py", line 453, in dtr
    self._update_dtr_state()
  File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 614, in _update_dtr_state
    fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
IOError: [Errno 22] Invalid argument
/usr/share/arduino/Arduino.mk:1478: recipe for target 'reset' failed
make[1]: *** [reset] Error 1
make[1]: Leaving directory '/home/pi/sketchbook'
/usr/share/arduino/Arduino.mk:1454: recipe for target 'upload' failed
make: *** [upload] Error 2

Any help would be greatly appreciated.

Seems, that you use the wrong serial port. Is your Arduino really connected to /dev/tty36? If yes, then you don't have the correct permission to access it. Check, which group the device has and be sure, that your user is part of this group

How would I check which group I am in, as well as the permissions I possess?

The command id will show the groups of the current user. with ls -l /dev/tty36 you can check the permissions and the group of the device.

/dev/tty36 is a root directory and the current user is in the group "27(sudo)"


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

Looks similar to:
"8 Channel 5V/3.3V IIC UART SPI TTL Logic Level Converter"
https://www.aliexpress.com/item/32977711795.html

@FilipFranik Thanks that is the correct one

@FilipFranik you should post that as an answer so the OP can accept it.

Looks similar to:
"8 Channel 5V/3.3V IIC UART SPI TTL Logic Level Converter"

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


text:
How can I set the SIM900a to Europe?
I got a chinese SIM900a module but it can't connect to the network (I live in Europe). Is there a way to get it work on Europe mobile networks?

Find a provider that still supports GSM. I know that in the USA they are phasing out GSM. Could you tell us the provider you are currently trying to connect to, and in which country?

I am in Croatia...

The SIM900A seems to be carrier locked, and will only work in Asia. It appears you can update the firmware to make it work, as described here https://www.allaboutcircuits.com/projects/how-to-flash-the-sim900a-module/

Thanks. Will check it out? Add reputation?

Here is a manual in Dutch with all the necessary tools. https://drive.google.com/drive/folders/1glNtS7zUH_dMQdc8O_W3YZX4h6nKtPWF?usp=sharing


text:
Can I connect this LED Matrix to a ESP8266 Huzzah directly?
This tutorial 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  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.

The library does not support ESPs, but in general you should be able to drive it with ESP if you have enough free pins. You might need a level shifter

So I would not be able to use the library, and would have to figure out another way to output to the matrix? I don't know where to start with that...might just make the Uno a slave if I can figure out how to do that

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


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

Could you please revert the question to the original state, we don't use "[SOLVED]" on titles nor post solutions inside questions. The best would be for you to post a new answer and move your solution there. Thanks!

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

This worked.   I had to make make some changes to my Arduino IDE environment which I will add to my initial question.


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

Did you try connecting A4 to VCC or GND? Floating signal can give this behavior.

Thank you, it seems to work. Can I connect a pin directly to VCC or should I use resistor?

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.

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

Connect the pin to an internal, fixed size capacitor
Disconnect the pin
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.

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


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

No. It's not. It's too primitive.

tks.  chad solved it elegantly with a python script.  lightweight and easy to use.

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

the port is stumping me.  mind clarifying?  I keep on getting Please give serial port number

start the program like so   ./programName 1 or ./programName 0  the number dictates which of the ttyUSBx devices you are trying to watch(will match with what you see in the arduino IDE)

Spot on!  Perfect, elegant, simple.  UPVOTED, ACCEPTED & BOUNTIFIED.  :)

@tonygil, to copy port input to output, you don't need python. the python script could monitor more ports and print them with different color

that is also very useful, tks @Juraj!

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.

UPVOTED because it addresses the root problem of monitoring multiple boards.  NOT ACCEPTED becacuse the solution needed depended on one and only one instance of IDE.   tks!

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.

Tried your suggestion: 2 windows - 1 process.  Ubuntu creates a second process, unfortunately.

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

I use Sloeber. It is a very good integration of Arduino build tools and packages into Eclipse


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

is your goal just to have a backup of the hexcode, or actually de-compile it back into C/C++?

esptool is THE tool for esp8266

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

i was under the impression that the same tool that i use to flash (firmware) would be the one to get this job done.  tks 4 confirming and indicating which options to use and how to use them.  UPVOTED, ACCEPTED.    :)


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

cli() disables interrupts so that the ISR itself is not interrupted ... sei() enables the interrupts again

ok. Thanks for all answers. This problem can be closed.
I found the problem with the ISR routine and not knowing what the cli() was for just slowed me down a little.

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!

Thank you both for the clarification. It's interesting that the ISR that I was looking at uses the cli() at its start but forgot the esi() when closing. But it's got other problems also. Regarding the Arduino as a SPI slave, I know I have good data coming in at a very low clock rate by checking with a Logic Analyzer but the Arduino(UNO or Mega) shows garbage (all '?'). It never sees the '\n' and I can only stop it by counting characters to set the received_data flag before ending the ISR. Weird. Can't figure out why.

Post the sketch or the ISR in a new question if you are happy with the answer to your original question. We try to keep a clean question-answer session to allow others to find and follow. Extending with additional questions does not help reuse.


text:
Error when HX711_Arduino_Library installed
First I'm getting this error #include  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.

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!

I'm Not much familiar with Arduino software. can u plz help me with easy way..?? library with constructor not getting this??

Check the file HX711_Arduino_Library\src/HX711.h and the HX711 instance in your sketch. Use the constructor that matches the library. Change: sketch_jul18a:34:22: HX711 scale(DOUT, CLK);

I have Checked the file HX711_Arduino_Library\src/HX711.h but not getting this Change: sketch_jul18a:34:22: HX711 scale(DOUT, CLK); with what I have to replace this..????

Start with the example sketch: https://github.com/bogde/HX711/blob/master/examples/HX711_basic_example/HX711_basic_example.ino

yes sir,  github.com/bogde/HX711/blob/master/examples/HX711_basic_example/ this link code running properly. getting this message Done compiling without any error. But for my code still getting same error message: no matching function for call to 'HX711::HX711(int, int)'.. Guide me for next step to solve this issue.

Please post your sketch and we will help you fix it.

Not able to post my sketch its too long.. what can I do now?

Locate the line that starts with HX711 and remove the parameters to the constructor. Add a line to the setup() the calls HX711::begin() with the pin parameters. And now you should mark the question as answered :)


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

I think your problem is related to https://forum.arduino.cc/index.php?topic=165675.0, which is about two libraries using the same timer.

I'm looking through Tone.cpp and i think it's possible to force it to use another timer by defining USE_TIMER1 i will verify this asap.

@FilipFranik, thanks. Where do you find tone.cpp? I downloaded Arduino IDE from the Windows Store.

@MichelKeijzers The forum you linked doesn't seem to explain how to fix the issue I am facing although I do think it is the same problem.

https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/Tone.cpp

@rgiller I know, that's why I just post it as a comment instead of an answer.

@FilipFranik Do you mean I should change #define USE_TIMER2 to a different number which is different to the IR remote?

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.

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

I simply changed it to use #define IR_USE_TIMER1

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


text:
How to create parametric variable in class decleration
I hope the subject of this question if correct.
in timeOUT constructor, 3 more instances of other class are defined:
endTimeOUT_inFlash(key1),
inCodeTimeOUT_inFlash(key2),
updatedTimeOUT_inFlash(key3).
// ~~~~~~~~~~~ TimeOut Class ~~~~~~~~~~~~
timeOUT::timeOUT(char *sw_num, int def_val,char *key1, char *key2, char *key3)
        : endTimeOUT_inFlash (key1), inCodeTimeOUT_inFlash(key2), updatedTimeOUT_inFlash(key3)

I'm looking for a way that key1 to key3 will be predefined keys, and sw_num will serve as a prefix to those keys.
For example :
#define key1 "endTO"
#define key2 "inCodeTO"
#define key3 "updatedTO"

and using sw_num's value will be concatenate as: SW0_endTO( for key1 and so on . sw_num=SW0 ofcourse).
This way contructor will be :
// ~~~~~~~~~~~ TimeOut Class ~~~~~~~~~~~~
    timeOUT::timeOUT(char *sw_num, int def_val)
            : endTimeOUT_inFlash (key1), inCodeTimeOUT_inFlash(key2), updatedTimeOUT_inFlash(key3)

Why do you need this? Anyway you can use sw_num as String and make those concatenations like  sw_num + '_' + key1 ... (that's ugly solution). Or you can have two parameters in constructors and build the string inside of class. Or you can create child classes for each key...  But with knowing context, it might be something completely different

@KIIV as far as I understand ( tried ), nothing can come before constructor to do such "concatenate"

@Guy.D, read KIIV's comment again and slow

This smacks of an X-Y Problem. You should more clearly define what you want to achieve, and forget how you think you want to achieve it.


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

Check the command when compiling angle.c. Is that that right compiler? Try the extension .cpp instead.

the compiler is checked, i'll try the .cpp extension

you can't include Wire.h in .c . Wire.h defines a class

that is it you are right, no please post it as an answer, so that i can accept it

the solution is to change the extension into .cpp because Wire.h defines classes

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.


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

sleep is best for 30 minutes

the same question with more info https://forum.arduino.cc/index.php?topic=627149.0

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

esp8266 has built-in RTC with deep sleep wake-up option

for example blink a LED to show that it is alive

interrupts to keep the WiFi connected

@Juraj thanks for the extra comments .. offtopic:. btw congratulations with your 10K reputation. I removed my other answer so you don't need to downvote it anymore).


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

do you know that there is 5 V on USB pim if the laptop is on, and there is no 5 V if the laptop is 'off'?

@Juraj I haven't tested it thoroughly, but nothing I connect to the USB seems to have any power when the laptop is off, so I would think that the 5V is off?

By the way, consider my cheap solution. A sad part of these StackExchange forums is that people "downvote" when the don't like what you offered, Those downvotes often have  nothing to do with actual measurable data.

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:

simulate this circuit – Schematic created using CircuitLab
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.

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.

"double insulated" has nothing whatsoever to do with what is safe or not to do with ground. It is purely to do with the way the physical device is insulated. You are thinking of "galvanic isolation" which is a completely different thing.

Double insulation to UL1097 removes the requirement that the secondary circuit, considered accessible dead metal, be grounded - in fact it forbids it, and so ensures that the galvanic isolation afforded by the separation of the windings on the flyback inductor, and the creepage spacing of the board it is attached to is not compromised by it being connected to any point of the supply that would cause a ground loop to exist when connected to other equipment, grounded or not.

You're confusing ground "earth" with ground "0v reference point in a DC circuit".

No, I'm not. Whether it's safe to connect the GND of the laptop USB port to the GND of the Arduino's supply depends on there being no other connections to both of those that could hold them at different potentials, and the connection to the supply earth through both power supplies could do that. UL unfortunately uses the term "grounding" to mean earthing in a lot of places. https://en.wikipedia.org/wiki/Ground_loop_(electricity)

What about through the Y capacitor...? The leakage current ("touch current") could be fatal to one or other device...

Wouldn't be an issue if the Arduino were designed properly. However they decided (incorrectly) connect the USB shield direct to ground at the device. Fools! There should have been a 1M (ish) ground balancing resistor in there to gently equalise the ground potential differences while you plug the cable in. That's why some devices spark when you plug usb in.

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.

The only problems are that (a) the Laptop USB outputs 5V, and the arduino input should not exceed 3.3, and (b) when the Laptop is no longer powered, the 5V pin on its USB no longer has a defined state, and could theoretically spike.
Here's a simple and cheap way to do this with passives. The diode isolates the USB from any "back" voltage. The USB 5V is measured across the resistor, and I'd place a capacitor there to to absorb any voltage spikes from the laptop when it loses power. Finally, the second resistor also indirectly protects the digital input and acts like a voltage converter, between the 5V (4.5 after the diode) and the 3.3V the arduino wants to see. The over-voltage will simply be routed to ground via the chips internal protection diodes, and the current will be limited to about 120 microamps ( 4.5- 3.3 ) / 10K.
You could use an opto isolator, but this is a cheap solution that will work. You will have to share ground between the laptop's USB and your arduino (not shown in the diagram). That will not be an issue however. Especially considering all power adapters offer significant line-to-load isolation. By the way, the 1uF capacitor can be decreased to 100nF or less, depending on how quickly you want to respond to the power loss.

simulate this circuit – Schematic created using CircuitLab

What makes you think an Arduino has 3.3v logic?

Some are 5, some or 3.3. The OP didn't say.
https://www.arduino.cc/reference/en/language/variables/constants/constants/

99% are 5v. You chose the wrong default voltage.

Either way, the circuit show will work.


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

We can help you with the programming language and hardware side of things. We can't help you with obscure algorithms. Maybe the maths or physics SE sites would be better for that.

Well that's a bummer. I guess I will close the topic then. Thanks!

Once you have an idea of what you want to choose we can help you code it.

You could apply a simple version of Machine Learning; measure, filter, normalize and last match (as distance to collected statistics).

It depends.
First you need to break the problem in steps:

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

Thanks for the answer! As for the memory problems you pointed out, I think I may be able to get away with it because the spectrum I'm trying to analyse is completely below 1kHz, which means there is no need to have that high of a sampling frequency (I know harmonics can mess it up but I have some hardware filtering).

And I don't really need to do it realtime-ish.

still 1 KHz is 1024 bytes, the Arduino has 2048 free bytes, and you might need to store intermediate results.

Not realtime-ish makes it easier a lot.

I really only need 128 samples per cycle. The sampling frequency only affects the speed the arduino is running at.

Memory -> resolution.

In that case you might get good results. 128 samples is very good manageable. You might even be able to record new data while the previous data is being calculated (using two buffers, one for storing new data, one for processing).

If you think this answer is useful, upvote it please, and if the answer answers your question, accept it as answer.

Thanks for the help! I can't really accept it as an answer because I wanted to have some direction on what type of algarithms I can use

you're welcome (you can upvote by clicking the up arrow next to my answer), and below is a button to accept it. Good luck with your project.


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

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

Re “if the library is full of if statements to make a difference between models, that code is in”: Since version 1.6.10, the Arduino IDE enables link time optimization, and this is no longer always true. If the conditions in the ifs are compile-time constants, the optimizer notices that some parts of the code is unreachable, and discards them.

@EdgarBonet Thanks for that remark; I updated my question (credits for you). I didn't knew about this feature.

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.


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

Sometimes:

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.

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
Update: At Robert's suggestion, I modified the V-USB bootloader 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.

Did you apply a RESET pulse/code (DIN to GND)? Might need to be longer than 50us.

Leaving the DIN pin floating will give undetermined results. Try connecting the DIN pin to ground.

@Gerben Great thought, but DIN to GND still exhibits this behaviour. Also in my Adruino project the DIN pin is connected to the GPIO and not left floating. I’ve isolated the issue to the LED. Thx.

@MikaelPatel These LEDs are straight out of the manufacturer’s packaging and 90% of the time are blue when they are powered. I’ve removed all Ardruino circuity to demonstrate this issue.

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

Thanks, Robert. In lieu of anything else I can do, I modified the bootloader to send the control bits to turn off the APA106 LED. There is still an extremely brief blue pulse because the power is always faster than any CPU process. The random color still manifests, but it's brief. Thanks for the suggestion.


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

Post your circuit and the relevant code and what you see going wrong and what you expect.

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


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

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

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();

It worked! Thanks a lot. But I also had to remove the SoftAPConfig() command. Any idea why?

was it before or after internalServer = WiFiServer(WiFi.softAPIP(), 81);? SoftAPConfig should be before it, to have the right SoftAP IP

can you have a sever available on both interfaces at once?

@dandavis, at default it listens on all activated interfaces


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

board-specific flavors take some of the guesswork out of burning the first image and save clicks when switching

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.


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

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.

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:

simulate this circuit – Schematic created using CircuitLab
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.


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

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.

@Janik, you might want to check out any old phone (tablet etc) chargers that you have laying around.  The first two that I pulled out of my box delivered 2A@5V (Samsung) and 2.1A@5.1V (Apple) - and to all the "I don't like what you said - so I will down vote you people" on this site, this is the rating that is written on the charger.

Actually found a 3a@5v fast charger in my drawer, gonna use this, thanks

Cool. Just remember what chrisl said about not drawing the power through the arduino (last paragraph in the answer)


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

The struct itself does not use a lot of space, I see mainly the code itself with has 40 bytes. The message says, that your global variables take up 104% of the memory. There is the problem, but you didn't show us your global variables. Maybe you can reduce the number of global variables, when they don't really have to be declared the whole program runtime.

I did. When I comment out "pronto.setPronto("0000 0000");", I get allot more free space. But all the #define, #include and other global vars I commented out, nothing changed. I am going to add the url with pics on the post just to show you.

Ehm, how long is the proto code there? It is definitely way longer than the one in your question

It shouldnt matter, the Pronto code can be as long as it can be. You know what it is right? All I did was to store the Pronto code string to char* variable. I couldn't use string nor its library since the header won't let me. I ended up using char*.

You store the code in a global variable, so yes, it does matter, how big it is. You only have 2KB

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.

Thank you so much, now it is saving up more space.

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.


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

What protocol in what "example"?

The one I was referring was the SerialEvent example in the arduino IDE

Ah that. That's really not a protocol example. Only an example of how you can do things with SerialEvent.  SerialEvent is silly, anyway. Forget it.

Good to know, so do you have a recommendation to how I could get the two to talk properly and fast, as the sensors need to transmit data to the pi in real time?

Depends very much what the data is and what quantity there is.

The pi transmits command to control the motors. Wanting to expand I the future python sends the motor's name and a value. The Arduino ois responsable from interpreting that. On the other hand the Arduino sends data from 8 ultrasonic sensors as fast as possible (ideally every 50ms) as well as a light sensor which measures the rotation of the wheels (basically within a few dozen milliseconds).  My question wasn't really a how to do it. But rather has someone proposed a serial protocol to do such thing. I would be surprised otherwise

There are many many protocols around. I myself have one called ICSC, though whether that is suitable for you or not I can't say. There's as many ways of transferring the data as there are cats that want skinning. You could probably get away with a simple ASCII protocol (M1:213\n for example).

Why is the simple protocol from the examples too weak? Are you loosing data with it? Or what is the problem there?

indeed, I am missing data packets (e.g. the motor keep spinning even though I've sent the stop command) probably because the buffer is more than often full. and since I'm streaming data from the arduino i get to some points where everything freezes. Needless to say, that I'm not using it well, hence why i'm looking for examples of protocols such as the ICSC mentioned here or the arduino-robust-serial to see how people did it. I'm basically not very good at implementing the example shown in the aruidon IDE and am looking for what people have done so far

If your Arduino code cannot process the information fast enough, you have a general problem. At one point or another you will loose information with every communication protocol, if you cannot process the information as fast, as they are arriving. The buffers will also fill up with other interfaces. Or are your messages simply too long (more than 6 byte)? Then raise the buffer size

*more than 64 bytes - in case of Serial. Not 6 bytes, sorry, typo

Maybe if I reformulate my question: what frameworks exist for robotics applications that consider the coupling of an arduino with a raspberry pi (I'am looking into ROS.org, though it's not ideal for raspberry pi) are there modern alternatives?

why would the arduino need to transmit the signal from the wheel rotation sensor? ... that part of the system should stay in the arduino ... the arduino and the wheels should be more like a Logo turtle ... the RPi issues a command to move ahead 10cm and the arduino does it ... or move ahead 10cm, but stop when bumped, and report actual distance of travel

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 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 who helped me integrate the arduino Due to his pymata and pymataExpress 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 or gobot are better. But pymata worked for me hence my answer to my own question.

processing

https://github.com/firmata/processing
http://funnel.cc

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

perl

https://github.com/ntruchsess/perl-firmata
https://github.com/rcaputo/rx-firmata

ruby

https://github.com/hardbap/firmata
https://github.com/PlasticLizard/rufinol
http://funnel.cc

clojure

https://github.com/nakkaya/clodiuno
https://github.com/peterschwarz/clj-firmata

javascript

https://github.com/jgautier/firmata
http://breakoutjs.com
https://github.com/rwldrn/johnny-five

java

https://github.com/4ntoine/Firmata
https://github.com/kurbatov/firmata4j
https://github.com/reapzor/FiloFirmata

.NET

https://github.com/SolidSoils/Arduino
http://www.imagitronics.org/projects/firmatanet/
https://github.com/wbadry/FirmataCSharpClientClass

Flash/AS3

http://funnel.cc
http://code.google.com/p/as3glue/

PHP

https://bitbucket.org/ThomasWeinert/carica-firmata
https://github.com/oasynnoum/phpmake_firmata

Haskell

http://hackage.haskell.org/package/hArduino

iOS

https://github.com/jacobrosenthal/iosfirmata

Dart

https://github.com/nfrancois/firmata

Max/MSP

http://www.maxuino.org/

Elixir

https://github.com/kfatehi/firmata

Modelica

https://www.wolfram.com/system-modeler/libraries/model-plug/

golang

https://github.com/kraman/go-firmata

Qt/QML

https://github.com/callaa/qfirmata

Android/Kotlin

https://github.com/xujiaao/android-firmata

Smalltalk

https://github.com/pharo-iot/Firmata


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

This is really a basic C/C++ programming question, not an Arduino question. In any case, I'm glad you were able to figure it out.

@DuncanC There is indeed a sort of no-man's land there, since Arduino does restrict how you can use C++, especially vis-a-vis memory restrictions.  I am not sure that I would be so strict with Joshua, or anyone for the matter.

Tony, yes, there are some gray areas, but this is a programming 101 question for C/C++.

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

Wonderful answer. Way better than what I found. Thanks!

I just recently ran into this issue and this was the solution that i implemented.  keeps things cleaner, as well as making upgrading (adding or removing parameters) easier..  tks for accepting.

Exception 9 on Uno?

why the struct? it is useless and will be copied as function parameter. you can pass the array as parameter

you could do that, but a struct may have other data as well - such as multiple arrays for multiple dimensions of parameters.  such as other parameters.  a struct as a class is far from useless, especially if your development is method oriented.

i find your spamming rude and abusive in abstract and have flagged you for it, @Juraj.  I am not hard of reading, there is no point in sequentially writing the same rude comment.

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;
}


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

1273 = 8192 - 6919. There is no guessing whatsoever on the part of the IDE.

What I mean is, why it gives already a warning when I still have 1273 bytes left? It seems like a 'very safe' value.

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.


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

Thw calls to digitalWrite() are taking to long. It`s a rather big function. Use direct portmanipulation

you should delete the previous timer settings. Arduino core initializes the timers for PWM and you do |=

Why don't you do the toggling in the ISR? The time it takes the loop function to find the flag has changed won't be trivial.

@chrisl in the end I decided not to use the arduino core, things behave so weired... 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?

@NickGammon I started to reduce the code and it just remained there. How much cycles does such a boolean comparison actually take? Initially, I planned to read the frequency from a potentiometer after each interrupt, wouldn't this be easily possible in 8×83=664 cycles?

@Juraj right! I now decided not to use the arduino core...

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

I'm not that new to uC programming, I just tend to use programing registers directly rather than using the arduino environment. I thought this little program might be faster to implement  using the arduino core without having to look up things in the datasheet, but now I did so anyway. Concerning the adc: if it is in free-running mode, the hardware is doing the conversion in parallel. So if I only check the status bit for a completed conversion, this shouldn't be a problem and the actual time needed to handle the analog value would decrease a lot. Isn't that true?

I only need the analog value every 100ms and I'm not doing very much processing with it...

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

Thanks for your answer! Yes, I know the inverting mode, but I will soon have to be able to also change the frequency in a little range. I'm now doing direct port manipulation and it works fine so far. But a question: what is this _BV() you are using?

@SimSon: _BV(n) is a macro for (1<<(n)), from avr-libc. I guess it stands for “byte value”. I like to use it when writing AVR-idiomatic code.


text:
Why is the IDE not able to find the board despite it being clearly seen and selected?
i'm having an odd problem where despite having the correct port selected 3 times i'm still getting an error as shown below:  message:
Arduino: 1.8.9 (Windows 10), Board: "Adafruit Feather M0, Arduino, Off"

Sketch uses 20876 bytes (7%) of program storage space. Maximum is 262144 bytes.
Atmel SMART device 0x10010005 found
Device       : ATSAMD21G18A
Chip ID      : 10010005
Version      : v2.0 [Arduino:XYZ] Mar  5 2016 17:46:52
Address      : 8192
Pages        : 3968
Page Size    : 64 bytes
Total Size   : 248KB
Planes       : 1
Lock Regions : 16
Locked       : none
Security     : false
Boot Flash   : true
BOD          : true
BOR          : true
Arduino      : FAST_CHIP_ERASE
Arduino      : FAST_MULTI_PAGE_WRITE
Arduino      : CAN_CHECKSUM_MEMORY_BUFFER
Erase flash
done in 0.832 seconds

Write 21164 bytes to flash (331 pages)

[=====                         ] 19% (64/331 pages)
[===========                   ] 38% (128/331 pages)
[=================             ] 58% (192/331 pages)
[=======================       ] 77% (256/331 pages)
[============================= ] 96% (320/331 pages)
[==============================] 100% (331/331 pages)
done in 0.128 seconds

Verify 21164 bytes of flash with checksum.
Verify successful
done in 0.016 seconds
CPU reset.
Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.

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

the upload was successful, but after the reset the board changed port or the sketch hangs and doesn't handle USB. I guess you have Serial Monitor open and it can't connect back to selected port after Upload, and prints the message "Couldn't find a Board on the selected port."

The SAMD boards connect to computer over native USB support of the MCU. The handling of the USB is done by Arduino core functions linked at build to your sketch.
A consequence of using the native USB port is, if your sketch has a problem, it influences the USB communication. In this case you can activate the bootloader to handle the USB port and the upload. It is done by double clicking the reset button on board.

this reset will not always work: https://arduino.stackexchange.com/questions/85530/seeeduino-xiao-stopped-connecting-enter-bootloader-mode-is-not-working