text:
How can I switch a 1.5V buzzer with my Arduino?
I want to make my alarm clock “smart”. I'm very new to this stuff, that is, the hardware side. The programming shouldn't present too many problems.
I’m currently experimenting with a simulator (http://circuits.io) and want to start with controlling the alarm’s buzzer with my Arduino.
I did some reading on transistors and this is what I came up with:
I’ve turned pin D3 to high and hooked it up to the base of a NPN transistor. I’m trying to run 1.5V through the transistor, but nothing happens. Any thoughts?

To me it looks like you have your emitter and collector backwards? (but it's hard to tell from the picture, is it E B C? I think it should be C B E)

Could you add your ground connection(s) in, please?  as @redstarcoder says, it's hard to understand where you're going with it. Are you trying to put the buzzer on the collector or the emitter?

I just registered to the website to check, the first NPN transistor I saw was in fact C B E.

You need to connect the GND of the Arduino to the GND/- of the battery. In most application the transistor is placed after the load (buzzer). So + -- buzzer -- transistor -- -. But I don't think it matters in this case. But I have the feeling you can connect the buzzer directly to the Arduino by just adding a proper value resistor, to lower the voltage to around 1.5V. Where did you get the buzzer from?

@ redstarcoder The transistor in the picture is C B E, so the buzzer is connected to the emitter -- I expected it to be E B C. So the buzzer is on the collector, that's correct, right?
@ MarkSmith Grounding the Arduino surely helped a lot and indeed fixed my problem.
@ Gerben The buzzer is inside my alarm clock, I'll need to open it up to measure the exact voltage and current it requires -- I'll do that and report back.

You simply need to ground the circuit. In row E on your breadboard just under where you connect the - of the battery, connect that to the ground pin on the UNO. This causes the buzzer to start working.


text:
Convert LIRC config file to Arduino IR remote command
I have a LED 24 button remote with a few broken buttons and I want to simulate all the buttons with an esp8266 using an IR remote library.
I would like to know if someone can help me translate the LIRC config file with all the functional buttons to an ESP lib command.
I have 2 lircd.conf files of the same remote (everything worked on a raspberry) and I'm using the same circuit on an ESP8266 (wemos d1 mini pin D5 and D6).
lircd.conf 1
begin remote

  name  lumina
  bits           16
  flags SPACE_ENC|CONST_LENGTH
  eps            30
  aeps          100

  header       8860  4530
  one           508  1724
  zero          508   607
  ptrail        508
  repeat       8863  2301
  pre_data_bits   16
  pre_data       0xFF
  gap          107224
  toggle_bit_mask 0x0

      begin codes
          PWR_ON                   0xB04F
          PWR_OFF                  0xF807
          LI_LOW                   0xB847
          LI_HI                    0x906F
          R                        0x9867
          G                        0xD827
          B                        0x8877
          W                        0xA857
          R1                       0xE817
          R2                       0x02FD
          B4                       0xF00F
          G1                       0x48B7
          B1                       0x6897
          FLASH                    0xB24D
          STROBE                   0x00FF
          FADE                     0x58A7
          SMOOTH                   0x30CF
          G2                       0x32CD
          R3                       0x50AF
          R4                       0x38C7
          G3                       0x7887
          G4                       0x28D7
          B2                       0x20DF
          B3                       0x708F
      end codes

end remote

lircd.conf 2
begin remote

  name  lumina
  bits           16
  flags SPACE_ENC|CONST_LENGTH
  eps            30
  aeps          100

  header       8861  4525
  one           515  1718
  zero          515   600
  ptrail        516
  repeat       8865  2291
  pre_data_bits   16
  pre_data       0xFF
  gap          107235
  toggle_bit_mask 0x0

      begin codes
          B1                       0x6897
          PWR_ON                   0xB04F
          PWR_OFF                  0xF807
          LI_LOW                   0xB847
          LI_HI                    0x906F
          R                        0x9867
          G                        0xD827
          B                        0x8877
          W                        0xA857
          R1                       0x9867
      end codes

end remote

Output from a few buttons read from the esp using the IRremoteESP8266 library .
F0C41643
4039382595
Unknown encoding: F0C41643 (32 bits)
Raw (68): 8850 -4550 550 -650 550 -650 550 -650 500 -650 550 -600 550 -650 550 -650 550 -600 550 -1750 550 -1750 500 -1750 500 -1750 550 -1750 500 -1750 550 -1750 550 -1750 500 -1750 500 -650 500 -1750 550 -1750 550 -650 550 -650 500 -650 550 -650 550 -650 550 -1750 550 -650 500 -600 550 -1750 500 -1750 550 -1750 550 -1750 500
------------------

A3C8EDDB
2747854299
Unknown encoding: A3C8EDDB (32 bits)
Raw (68): 8900 -4550 550 -650 550 -600 550 -650 550 -650 550 -600 550 -650 550 -600 550 -600 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -650 550 -1750 550 -650 550 -1750 550 -650 550 -600 550 -600 550 -650 550 -1750 550 -650 550 -1750 550 -650 550 -1750 550 -1750 550 -1750 550
------------------

86B0E697
2259740311
Unknown encoding: 86B0E697 (32 bits)
Raw (68): 8900 -4550 550 -600 550 -650 550 -650 550 -600 550 -600 550 -650 550 -600 550 -600 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -600 550 -1750 550 -1750 550 -600 550 -600 550 -650 550 -650 550 -600 550 -1750 550 -600 550 -650 550 -1750 550 -1750 550 -1750 550
------------------

A3C8EDDB
2747854299
Unknown encoding: A3C8EDDB (32 bits)
Raw (68): 8900 -4550 550 -650 550 -600 550 -650 550 -600 550 -650 500 -650 550 -600 550 -650 550 -1750 550 -1750 500 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -650 550 -1750 550 -650 550 -1750 550 -650 550 -600 550 -650 500 -650 550 -1750 550 -650 500 -1750 550 -650 550 -1750 550 -1750 550 -1750 500

Looks like is just plain NEC IR protocol. So use something like irsend.sendNEC(0xB04F, 16) for POWER_ON.

did with a few of those values, tried 16 and 32 for the second value

source: Stack Exchange

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

sort: votes


text:
Powering SIM800L
With peak consumption at 2A, the SIM800L needs much more current than can be supplied by an Arduino or NodeMCU.
What is the best strategy to power this module, considering that you have access to a 100-240V outlet?

Use a suitable 2A power supply.

good answers until now, all UPVOTED.  Will place bounty tomorrow, whoever has the most votes takes it all.

I had to design a board for a customer with a built in LTE modem module (similar to a SIM800), and the power circuitry was something that required special consideration.
One requirement of the board was that the modem should be able to be powered on and off to save power, but that powering it on shouldn't ever cause the rest of the board to brownout.
To this end a separate 5V power circuit was built with a "soft start" facility built in.  This was always on, and fed into a number of capacitors to act as a reservoir. From them the power went via a large P-channel MOSFET to switch the power on to the LTE module when needed.  The capacitors provided the extra inrush current the LTE module demanded at powerup, and the soft start of the power supply limited the initial inrush current of charging the capacitors.
The power supply also had a "power good" output on it which was monitored to know when the output voltage had risen to an acceptable level (and hence the capacitors were charged) and the LTE module was able to be safely enabled.
The basic circuit was:

simulate this circuit – Schematic created using CircuitLab
That is a somewhat overkill probably for your situation though, but you should understand how it's done in the "real world" in a proper device.  However for experimental / prototyping with an Arduino where you aren't wanting to turn the modem on and off, and aren't too worried about the odd brownout, and bulkiness isn't of as much of a concern, then simply using two suitably sized external power supplies is adequate.  One small one to power the MCU (Arduino), and one larger one to power the modem.

simulate this circuit
Because the power supplies themselves should have plenty of capacitance, and they are separately powered from a low impedance source (the mains power) there should be no interference between the modem and the MCU.

The cleanest solution is to use separate power supplies for your MCU and your other high power devices. Get a 2.5A supply for the SIM800L, and a more modest supply for the Arduino/NodeMCU.
If you use the same power supply for both, you should use a bigger power supply than your max current needs to minimize "droop" as the load changes. You might also need to add filtering capacitors to the 5V rails of each device fed by the power supply.
EDIT
I've used this 2A power supply in my projects before: https://www.amazon.com/gp/product/B01G6ZJ6DY/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1
You could use one of those for your SIM800L, and a 0.5A supply for the Arduino (A USB power supply would be fine.) Just be sure to tie the ground lines of the separate power supplies together.

two power supplies for MCU and GSM module?

One for each, yes. A regulated power supply still "bobbles" some as its load changes. By using separate power supplies, you isolate the MCU from voltage variations caused the the changing load from the GSM module.

I am usually using 12V/1000 mA adapter source to power Arduino and adjustable step-down/buck converter which powers GPS and similar modules. Advantage of this is that these converters usually have big capacitors on input and output, so you do not have to use additional auxiliary capacitors.

Do you feed 12V into the Arduino's barrel connector? That's on the high side for it's voltage regulator, and will make it run pretty hot. (Or do you feed it regulated 5V from one of the buck converters?)

Yes, I am using barrel connector. It is true that the voltage drop is quite large, but in case you power only Arduino I never had a problem with high temperatures on linear regulator. For chinese clones I rather use 9V power source, though (absolute maximum voltage rating is different for original Arduinos and clones).

Addendum: Just a clarification – the buck converters are also powered from the 12V or 9V power source, not from Arduino VIN or 5V.

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


text:
Fritzing part repositry - GY-30
There is no GY-30 light sensor part design in the standard Fritzing repository.

Is there an official alternative part repository containing Fritzing fzpz file for this sensor?  Does it go by any other name or part code?

Design your own part. Or find some other I2C breakout in the fritzing library that has the same pinout. Or use a 5 pin header instead.

a bit time consuming, and i'm sure that there is something out there

This part also goes by the name BH1750.  And that is available in the Fritzing  parts library.

This is the correct one : http://goo.gl/JiTmQt  it is called BH1750FVI Breakout Board (GY-30). The bare BH1750 has a different pin order.

thanks for reviving this.  i've been using the GY-302.  I'll give this part a look, tks!!!!

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


text:
C++ trim char array
I have a char array of length 10.  It gets filled with an unpredictable number of chars, usually up to 6.
char charDummy[10] = "";

When i concatenate the char array with another, I get spaces, which are unwanted in later parsing.
char postStr[300] = "";
strcat(postStr, "&field1=");
strcat(postStr,dtostrf(rain05m,6,2,charDummy));

How do I trim a char array directly?
Workaround: loop thru the array and copy valid characters to a new char array with perfect number of rows.  Due to memory constraints, I need to be parcimonious with the amount of variables created.

Your problem is that dtostrf() right-aligns the value in the space allotted to it.  The simple answer is to tell it to left-align instead:

Conversion is done in the format "[-]d.ddd". The minimum field width of the output string (including the possible '.' and the possible sign for negative values) is given in width, and prec determines the number of digits after the decimal sign. width is signed value, negative for left adjustment.
AVR LIBC Manual

So, just make your width negative and it will left align.

@tony gil: The string terminator (ASCII 0) has nothing to do with NULL and is never referred to as NULL. NULL is a completely different, unrelated thing in C and C++.


text:
OTA push sketch to NodeMCU
Similar questions regarding Arduinos mention the existence of tools that would enable the pushing of sketch updates to NodeMCU via WiFi / OTA (Over The Air).
Does this proceed?  If so, please indicate the proper tools.

Arduino IDE supports upload to a network port. Network ports are detected with mDns and made available in Tools>Port menu.
The ArduinoOTA library bundled with the esp8266 Arduino boards package supports upload from IDE with 'network port' over WiFi. See the example of the ArduinoOTA library available in Examples menu in IDE.

Yes, there exist methods to update codes through OTA in Wifi-modules/NodeMCU. You will first need to allot an IP address to your device which will later be used as a port to carry out OTA transmission. Look out to this tutorial-https://circuitdigest.com/microcontroller-projects/esp8266-ota-update-programming-using-arduino-ide


text:
Is it any way to connect ESP8266 to wifi faster?
I'm uploading this sketch to try connecting ESP to internet. However, most of the times I've ran it it takes a very long time to connect, a lot of times I've had to break the process because it seems it goes to nowhere. Few times it has connected in less than a minute. Is it any alternative to boost the connection?
Also, when I reset the module, it writes to the terminal 3 strange characters, and freezes without even starting to execute its sketch. Do you mind me asking how to solve that?
Regards!
#include <ESP8266WiFi.h>

const char red[] = "CDT10";
const char pass[] = "G7ZSY74Cs";
unsigned long muestra = 0;

void setup() {
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(red,pass);
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(1000);
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: "); Serial.println(WiFi.localIP());
  Serial.print("Chip ID: "); Serial.println(ESP.getChipId());
}

void loop() {
  delay(5000);
  muestra = millis();
  Serial.println(muestra);
}

Which board are you using?

Right now, ESP-01.

is the bandwidth ok once it connects?

I have also experienced the inability to connect sometimes. I wait a certain amount of time for it to connect then do a ESP.reset() if it fails.
As for the boot problem it sounds like you are keeping GPIO0 low so it goes back into programming mode. Hold it high and it will run your program instead.

It worked! I forgot to hold high the GPIO0. Now it is running right. Thanks!

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


text:
NodeMCU what is my esp3286 core version
How do I find out what my esp3286 core version using Arduino IDE?

Tools Menu -> Board -> Boards Manager - scroll down to the core and see what version it is.


text:
Reset NodeMCU master from Arduino slave
I designed a PWS (personal weather station) which will be placed in a difficult to access location.  In case of the master crashing and not requesting from the slave for a certain amount of time (stay alive protocol), is it possible to reset the master from the slave by powering a digital pin?

Note, I improvised a pull down circuit so that the Arduino Nano's D7 (or any other digital pin) 5V output could be pulled down to 3.3V.

for me it didn't work for Wemos D1 mini. with level shifter it worked. I don't know why. but you should have a level shifter for esp8266 RX too

care to elaborate into an answer?  tks @Juraj

I plan esp-01S wiring experiments this weekend and the reset of the esp8266 from Arduino is one of the goals

The "RST" (reset pin) should work, try it w/o the other device, to see if it actually resets.

@Juraj da man!  tell me how that goes, please!  Do you want me to post this fritzing diagram as an fzz somewhere?

There is no need for a voltage divider or a level conversion on the reset pin of the esp8266. The esp8266 has internal pull-up on reset pin. To reset the esp8266 the reset pin must be connected to ground for a very short moment.
To pull the reset pin LOW with pin of the other MCU we do:
void resetEsp() {
  pinMode(ESP_RESET_PIN, OUTPUT);
  delay(1);
  pinMode(ESP_RESET_PIN, INPUT);
}

ESP_RESET_PIN is the pin wired to reset pin of the esp8266. It is not configured in setup() and it is never set HIGH (we don't want to send 5 V to esp8266). Setting the ESP_RESET_PIN to OUTPUT connects it to ground, setting it back to INPUT hands the control of the line back to esp8266 reset pin's internal pull-up.

not sure i understand the wiring.  Does that mean that my Arduino (MCU) digital out is connected directly to NodeMCU RST pin?  If not, do you  mind posting a Fritzing diagram?  UPVOTED pending clarification for eventual ACCEPT AS CORRECT ANSWER.

i am posting a Fritzing as an answer, please comment if correct or incorrect.  Vote (up or down) if you will.

yes direct connection, because there is never 5 V from Nano side. it only pulls the reset LOW

ACCEPTED, tks!!

As per verification from Juraj, this would be correct wiring for his answer:

the point of reset from other MCU is not in wiring, but in code.

so is my original diagram correct, with the voltage divider?

I removed my comments about level conversion on I2C following Majenko's explanation here: https://arduino.stackexchange.com/questions/67461/arduino-slave-with-2-masters-sharing-the-same-i2c-bus/67462?noredirect=1#comment145475_67462

as I write in the answer you don't need voltage divider on reset because it has nothing to divide. there is never 5 V

so, this wiring would work?

yes. of course there is a risk that some other unintentionally to Nano uploaded sketch sets the pin as output high.


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:
Arduino IDE display DEBUG PORT Serial1 output
How can I display / capture Arduino IDE's Serial1 output?
Can I display it using Arduino IDE or using a script in Python?
This python script (courtesy of Chad G) works for the Serial:
#!/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,9600,timeout=5)

while True:
    try:
    stringMe = str(ser.readline().strip())
    if len(stringMe)>3:
        print(stringMe)

    except:
    print(sys.exc_info())
    ser.close()
    exit()

called as (for USB0):
python3 Arduino/tools/multiMonitor/monitorUsb1.py 0

or, if I want to save to a log file:
python3 Arduino/tools/multiMonitor/monitorUsb1.py 0 >> Arduino/tools/multiMonitor/log/usb00.txt

Serial1 (on most Arduino boards that have Serial1) is connected to a pair of pins on the GPIO headers and nowhere else.
To get it to your computer you will have to feed those TX and RX pins through a USB to TTL UART (FT232, CP2102, etc) adaptor.
From there on in it's exactly the same as using Serial but of course with a different device name.


text:
Arduino - Print file name
I need my sketch to print the name of the original INO file at the beginning of execution (during setup).
Is it possible?  If so, what is the resource which should be used?

You can use the macro __FILE__ to get the filename that is being compiled.  That may not be your INO file, but may be some derivative of it.
Serial.println(__FILE__);

You also get some other handy macros:
__DATE__
The date the sketch was compiled

__TIME__
The time the sketch was compiled

__LINE__
The line number where __LINE__ is being used

The combination of __FILE__ and __LINE__ is commonly used for debugging:
Serial.prinln("Error 23 at line " __LINE__ " of " __FILE__);


text:
Arduino IDE - debugging Exception 29
I installed the ESP EXCEPTION DECODER along with my Arduino IDE.  When my sketch crashes with Exception 29, I take the stack trace and input it, but I can't understand its line references (they dont seem to point to my code).

Exception (29):
  epc1=0x4020ec84 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000
ctx: sys
  sp: 3ffffcd0 end: 3fffffb0 offset: 01a0
3ffffe70:  3fffb558 00000000 3fff197c fffffffb
  3ffffe80:  3fff0ea0 3fff0ea0 00000000 4020fb20
  3ffffe90:  00000000 00000000 0000001f fffffffb
  3ffffea0:  3fff0ea0 00000000 3fff0e9c 4020ed35
  3ffffeb0:  40000f68 3ffe93b4 3fff0e9c 402120ec
  3ffffec0:  00000000 00000007 3fff197c 402137fa
  3ffffed0:  3ffe93b4 3ffe93b4 3fff0e9c 4021211a
  3ffffee0:  ffffffff 3fff0e9c 3fff197c 4021463c
  3ffffef0:  0100a8c0 3fffdcb0 3ffee960 00000030
  3fffff00:  00000000 3fff0e9c 3fff197c 4021468f
  3fffff10:  4020ffa8 3fff0afc 3fff0fc4 40100690
  3fffff20:  40229e46 00000000 00000012 3fff0af8
  3fffff30:  4020ffa8 3fff0afc 3ffe9348 4020ffb6
  3fffff40:  40104d7e 948e6801 00000018 40210074
  3fffff50:  3ffe9348 3ffed9fc 948e6801 00000000
  3fffff60:  4022e654 3ffee928 3ffee950 60000600
  3fffff70:  0fc612e0 3ffee950 3ffee928 4022e661
  3fffff80:  4022e6a6 3fffdab0 00000000 3fffdcb0
  3fffff90:  3ffee968 40000f65 3fffdab0 00000000
  3fffffa0:  40000f49 3ffe96e8 3fffdab0 40000f49
  <<

  0x4020fb20: tcp_abort at core/tcp.c line 544
0x4020ed35: netif_sta_status_callback at glue-lwip/lwip-git.c line 303
0x402120ec: netif_set_ipaddr at core/netif.c line 545
0x402137fa: dhcp_create_msg at core/ipv4/dhcp.c line 1825
0x4021211a: netif_set_addr_LWIP2 at core/netif.c line 584
0x4021463c: dhcp_release_LWIP2 at core/ipv4/dhcp.c line 1314
0x4021468f: dhcp_coarse_tmr at core/ipv4/dhcp.c line 423
0x4020ffa8: cyclic_timer at core/timeouts.c line 165
0x40100690: free at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.1/cores/esp8266/umm_malloc/umm_malloc.c line 1739
0x4020ffa8: cyclic_timer at core/timeouts.c line 165
0x4020ffb6: cyclic_timer at core/timeouts.c line 171
0x40210074: sys_check_timeouts at core/timeouts.c line 351

How can I find ou what happens at address 0x4020ec84 and what line it points to?

use the latest esp8266 arduino core 2.5.2.

done.  went in BOARDS MANAGER and upgraded core from 2.4.1 to 2.5.2 -  what next?

upgraded, must wait for problem to occur (historically it has taken 16+ hours to manifest itself - memory might be an issue)

do you use String class to build strings and convert numbers?

yes i do.  could that be the culprit?

https://majenko.co.uk/blog/evils-arduino-strings

@Juraj, apparently, your comment re Strings has pointed me in a valid direction, though it is not quite the answer to the question.  IMportantly, it solves my underlying issue.  I therefore awarded you the 50 bonus points in the other question.  well done, m8 !  ;)


text:
ARDUINO IDE debug level for stack trace only (nodeMCU 1.0)
What is the minimum debug level (TOOLS tab) which will display the stack trace on crash?
I would like to reduce information clutter in the serial monitor.
I understand that debug port must point to my serial monitor.
In case it makes a difference, it is a NodeMCU, running C++, in Arduino IDE on a Ubuntu 16.04 machine.

The crash report is printed to 'standard output' by __wrap_system_restart_local in core_esp8266_postmortem.c in esp8266 Arduino core.
The standard output is considered as debug output in esp8266 Arduino core. Debug output to hardware Serial can be enabled in runtime by Serial.setDebugOutput(true);.
At compile time the initial debug output is controled by -DDEBUG_ESP_PORT=, for example -DDEBUG_ESP_PORT=Serial1. The Tools menu "Debug port" sets the DEBUG_ESP_PORT define. The crash report is not controlled by "Debug level" setting.

Tks.  Compiles.  Testing.  Is it your evaluation that a question regarding the purposes and effects of Debug Level would be appropriate?

take a look into the boards.txt file in the esp8266 boards package installation folder


text:
SD Card store struct: force big-endian / little-endian?
Following MAJENKO's tutorial on sd card file optimization and data integrity, can I force the SDCard to read and write in either big-endian or little-endian?
I need this in order to maintain backup data integrity across a wide array of IoThings, using various boards (Arduino UNO, MEGA, Nano, NodeMCU, etc) for future parsing.

Many full C libraries have an sys/endian.h header file. This defines a number of macros so you can find out what the endianness of your device is.  It also usually defines a number of handy macros that can convert the endianness for you.
htobe16(x)
htobe32(x)
betoh16(x)
betoh32(x)

These convert Host to Big Endian values and back again.
htole16(x)
htole32(x)
letoh16(x)
letoh32(x)

And these convert Host to Little Endian values and back again.
Not many embedded C libraries provide it, though, and not all that do provide the handy macros.
It's not too hard to implement yourself, but it does mean you deciding what to do depending on the target architecture. Which kind of negates the handiness of the endian.h file.
So really you want to re-implement the functionality in a form you can include in all your sketches.
Fortunately the compiler provides a set of macros defining the endianness that you can use though:
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __ORDER_PDP_ENDIAN__ 3412
#define __ORDER_BIG_ENDIAN__ 4321
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__

So you can examine the __BYTE_ORDER__ macro to see what byte order it equates to and use that to select whether htobe32(x) has to do anything to the byte order or not.
In the PIC32 compiler it's done as a set of macros that either call swap32 / swap16, or pass the value unchanged:
#if __BYTE_ORDER__ == __LITTLE_ENDIAN__

#define htobe16 swap16
#define htobe32 swap32
#define betoh16 swap16
#define betoh32 swap32

#define htole16(x) (x)
#define htole32(x) (x)
#define letoh16(x) (x)
#define letoh32(x) (x)

#endif /* __BYTE_ORDER__ */

#if __BYTE_ORDER__ == __BIG_ENDIAN__

#define htole16 swap16
#define htole32 swap32
#define letoh16 swap16
#define letoh32 swap32

#define htobe16(x) (x)
#define htobe32(x) (x)
#define betoh16(x) (x)
#define betoh32(x) (x)

#endif /* __BYTE_ORDER__ */

So now depending on the byte order it will either swap the bytes around, or leave them unchanged.  It's now just a matter of implementing swap16 and swap32 - which I'll leave to you (hint: it just returns the value with the bytes in the reverse order - bit shifting and masking is good for that).
Then you need to decide on an endianness for your file.  Maybe choose little-endian since that is probably the most common.  So whenever you place a value into a struct for writing you pass it through either htole32(...) or htole16(...) depending on the data type.  Then whenever you read from a struct that has been read you pass the value through either letoh32(...) or letoh16(...) to get it in the host's endianness.


text:
Do comments occupy space in compiled C++ sketch? Arduino / NodeMCU
I tend to leave old code around as comments until I am sure that my current version is stable.  Just the way I like working.  I am concerned that I may be unnecessarily bloating up my sketches.
Do comments occupy space in an Arduino IDE compiled C++ sketch for Arduino (Nano, Uno)?  Is it correct to suppose that the behavior would be the same for NodeMCU?

you can determine that by compiling two identical sketches, one of which has a huge amount of comments

Not related to your question but... you should learn to use version control, and use comments for... commenting the code!

Unrelated, unhelpful, unasked for and... mistaken.  One is often wrong when guessing with little or no information to base one's assumptions upon.  I am talking about in between versions, as is clearly stated in the question.

What's unhelpful, unasked for and mistaken? Edgar's comment about source control is a very good suggestion. (Keeping your old code in the file as comments is superfluous if you use version control.)

The C/C++ processor (which processes only the #define & #include statements) is the first stage of the compilation process. It runs before the compiler does and strips out everything that isn't code. The compiler will never see your comments.

No.  Comments don’t take up any space.


text:
Bot not activating after button press
This bot is supposed to begin moving forward when the button is pressed, and stop after counting 3 lines of tape on the ground. Currently it is set up to scan the color of the floor at the beginning and count any major differences as a line of tape. Unfortunately I can't test its tape-sensing capabilities due to not being able to get it to actually start. It will only move if I hold the button down continuously, and stops as soon as I release it. Here is the code and images (It uses the Arduino Pro Mini 3.3v):
#include <SFE_ISL29125.h>
SFE_ISL29125 RGB;
unsigned int master2;
unsigned int detect2;
boolean isOn = false;
unsigned int accumulator = 0;

void setup() {
  RGB.init();
  pinMode(7, INPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  master2 = RGB.readGreen();
}

void loop() {
  if(isOn) {
    if(accumulator < 3) {
      detect2 = RGB.readGreen();
      digitalWrite(8, HIGH);
      digitalWrite(9, LOW);
      if(detect2 <= (master2 - 10) || detect2 >= (master2 + 10)) {
        accumulator++;
      }
    } else {
      accumulator = 0;
      isOn = false;
      digitalWrite(8, LOW);
      digitalWrite(9, LOW);
    }
  } else if(digitalRead(7) == HIGH) {
    isOn = true;
  } else {
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
  }
}

Could you replace the various hard-coded GPIO numbers with constants (e.g. #defines) please? It's hard(er than I can be bothered with) to guess what the various pins do.

Pin 7 is the button, pins 8 and 9 are the motor. I really can't be bothered with using constants since I'm rushing to get this done.

Possibly it accumulates so fast that it will immediately stop when you release the button?

Could I solve it by increasing the color tolerance? Or switching to one of Parallax's Line Follower Kit sensors that I have lying around?

Rip out the detector code and test it. I strongly suspect your readings are causing problems, and the code to count the three lines is broken anyway.

I already tested the components individually. What do you mean by the count code is broken?

Do it step by step. For starter, make it move after button is pressed without using sensor. I agree with @MarkSmith , its highly possible that your sensor reading algorithm is the problem

I strongly suspect the main problems with your code are in these lines:
  if(detect2 <= (master2 - 10) || detect2 >= (master2 + 10)) {
    accumulator++;
  }

If I understand correctly, with this code you are attempting to tell whether you have been over a line of tape, which will be indicated by a change in reading from RGB.readGreen(); - say high, low, high.  If so, accumulator++.  (I have no opinion on whether this is a valid way of sensing it, or how well your sensor will work.)
This is definitely broken in one way, and probably broken in another.
First the definitely-broken way:
You want to sense down-up-down-up-down-up (or up-down-up-down-up-down).  Your code senses simply three higher or lower readings.  Your loop() takes no time at all, so when your buggy moves onto the tape, it will immediately read (say) high, then loop round, read high again, loop round and read high again, and again. accumulator is now 3 and we stop the motor.
Second, the maybe-broken way:
What value does master2 have?  Consider that it is an unsigned integer.  You are subtracting 10 from it.  What do you get if its value is 5?  It can'be be -5 because it is unsigned.  How you solve this depends on the possible range of values from RGB.readGreen();.  The implementation looks like it could give a value anywhere in the range, so we have to be careful.
Here's my reworking of your code.  It assumes the concept of checking for values which vary by 10 from the original value is sensible - I've no idea if it is.  (I don't understand what this "middle" values means, but you say you've "already tested the components individually" which I don't believe because your code could never have worked but, assuming you saw something similar working...)  It also makes a very big assumption that the value will change cleanly - from higher to lower exactly once per edge of strip, with no wobbling.  Log out some values to find whether it really does.
#include <SFE_ISL29125.h>
SFE_ISL29125 RGB;
int master2;
boolean isOn = false;
int changes = 0;

#define BUTTON 7
#define MOTOR_A 8
#define MOTOR_B 9

#define LOWER 0
#define HIGHER 1
int last_state = 0;

void setup() {
  RGB.init();
  pinMode(BUTTON, INPUT);
  pinMode(MOTOR_A, OUTPUT);
  pinMode(MOTOR_B, OUTPUT);
  master2 = (int)(RGB.readGreen()/2);
}

void loop() {
  if(isOn) {
    // Wait for 6 changes: up-down or down-up, three times.
    if(changes < 6) {
      int detect2 = (int)(RGB.readGreen()/2);
      digitalWrite(MOTOR_A, HIGH);
      digitalWrite(MOTOR_B, LOW);
      // Count _changes_ in state only
      if(last_state == HIGHER && detect2 <= (master2 - 5) {
        last_state = LOWER;
        changes++;
      } else if (last_state == LOWER && detect2 >= (master2 + 5)) {
        last_state = HIGHER;
        changes++;
      }
    } else {
      accumulator = 0;
      isOn = false;
      digitalWrite(MOTOR_A, LOW);
      digitalWrite(MOTOR_B, LOW);
    }
  } else if(digitalRead(7) == HIGH) {
    isOn = true;
  } else {
    digitalWrite(MOTOR_A, LOW);
    digitalWrite(MOTOR_B, LOW);
  }
}


text:
What is the difference between a 3 pin and 4 pin ultrasonic range sensor?
I am following a tutorial that uses an arduino and ultrasonic range sensor, it calls for a 3 pin module (Paralax 28015-ND) and I have a 4 pin module (http://www.electroschematics.com/wp-content/uploads/2013/07/HCSR04-datasheet-version-1.pdf).  The 3 pin seems to have one signal pin (both input and output) and the 4 pin has two separate signal pins (a trigger and echo).  How would I need to change the code and wiring if I am using the 4 pin?  Here is the code from the tutorial:
     /* Ping))) Sensor

   This sketch reads a PING))) ultrasonic rangefinder and returns the
   distance to the closest object in range. To do this, it sends a pulse
   to the sensor to initiate a reading, then listens for a pulse
   to return.  The length of the returning pulse is proportional to
   the distance of the object from the sensor.

   The circuit:
    * +V connection of the PING))) attached to +5V
    * GND connection of the PING))) attached to ground
    * SIG connection of the PING))) attached to digital pin 7

   http://www.arduino.cc/en/Tutorial/Ping

   created 3 Nov 2008
   by David A. Mellis
   modified 30 Aug 2011
   by Tom Igoe
   modified again 02 Apr 2016
   by Randy Sarafan

   This example code is in the public domain.

 */

// this constant won't change.  It's the pin number
// of the sensor's output:
const int pingPin = 4;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

There are already libraries that do that for HC-SR04, the code is quite simple, just take a look at it and you'll see how you can modify your program.

It's simple enough... instead of:
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);

You would have
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);

(of course you have to define echoPin to be whatever pin you choose to connect ECHO to).
And to save processing time you can have all your pinMode() calls in setup since there is no need to change mode on the fly any more.


text:
Run different code on different type of reset in arduino nano
I would like to program the arduino such that if I reset it by disconnecting and then reconnecting the usb.. A particular led glows BUT If I press the manual reset button on my nano... I want a different led to glow. How can I achieve this.
I have 2 leds and my nano... Along with the laptop and any other necessary components.

The MCUSR register (page 79 of the datasheet) tells you what kind of reset happened most recently. As long as the USB interface chip on your nano isn't controlling the RESET pin without the port being opened (i.e., toggling it at power up regardless of the USB state) then you could query that register to see how it reset:
if (MCUSR & (1 << 0)) { // POR
    digitalWrite(4, HIGH);
} else if (MCUSR & (1 << 1)) { // External Reset
    digitalWrite(5, HIGH);
}

However, if the USB chip does toggle the RESET pin then there is no way you can distinguish between the two resets since they are bot the same "external" reset using the RESET pin.

Note that the information in MCUSR is lost on boards running optiboot, such as Uno. Luckily the standard bootloader on the Nano doesn't do this so it likely won't be an issue in this case but it's worth mentioning because it's common for people to burn the optiboot bootloader to Nanos as it's otherwise far superior to the stock one.

If the usb-to-serial is actually resetting the MCU right after power-up, you could try using the PORF bit in the MCUSR. When first power-on, this bit is set. If you clear this bit, and then press the reset button, this bit will still be 0 when the sketch start again.


text:
Making HTTPS requests using ESP8266 AT commands
I am trying to make HTTPS GET/POST requests to the following server using AT commands.
AT+CIPSTART="TCP","54.166.71.140 ",443

I get errors when i use port 443 but on port 80 the requests are successful.
How can i get around this issue ? what could be potential solutions ?

read the reference, please

are you referring to this docuement ?  https://docs.espressif.com/projects/esp-at/en/latest/AT_Command_Set/TCP-IP_AT_Commands.html

it depends. that is for AT 2.1. for AT 1.7 this https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf

HTTPS requires that you make an SSL connection not a TCP connection.  To do that you need to use
AT+CIPSTART="SSL","54.166.71.140 ",443

You also need to configure SSL itself.
However the SSL support is not great and struggles with some sites (no SNI support by all accounts).
So you're better off programming the ESP8266 directly with your own sketch to make any HTTPS requests and process the data for you.

How do i configure the SSL, is there any reference ?

From the examples I've seen it looks like it's just setting the SSL buffer size. There's configuration commands but I haven't seen them being used.

That solved it :) the buffer size was 2048 by default


text:
GET/POST request via AT Commands
I am trying to send a simple GET/POST request to a dummy end point on https://requestbin.com/. I am using an ESP8266 module. I am using the arduino serial monitor to send these AT commands. I connect to wifi and then use the following AT commands
AT+CIPSTART="TCP","54.166.71.140 ",443  (the IP address from requestbin)

I then do
AT+CIPSEND=80

followed by
GET / HTTP/1.0\r\nHost: fc35001f8ec49962d182320446070d.m.pipedream.net\r\n\r\n

I get the output as follows
Recv 80 bytes

SEND OK

+IPD,272:HTTP/1.1 400 Bad Request
Server: awselb/2.0
Date: Mon, 07 Dec 2020 13:28:01 GMT
Content-Type: text/html
Content-Length: 122
Connection: close

<title>400 Bad Request</title>

400 Bad Request

CLOSED

Is there problem with the length of CIPSEND or the format of the request itself.

the \r\n are send as \r\n, not as new line characters

how should the At command look like in that case ?

send first GET / HTTP/1.0, then Host: fc35001f8ec49962d182320446070d.m.pipedream.net and then an empty line. do it fast before the connection times out

what would be the value for CIPSEND in this case ?

the count should include the new line charcaters. \r as 1 and \n as 1 character

Is there an easier way to calculate how long the AT+CIPSEND value should be ? i still get bad request.

bad request is a response from the server, so it can connect and receive the response. that is a good test. now write the code

Let us continue this discussion in chat.


text:
What is best way to get data from sensors if arduino is slave?
Im working on a project where i have motor controller(arduino nano) being i2c slave. Its job is to get RF24 data and control motor and at same time send data to master about motor... Currently i have 2 ultrasonic sensors for distance sensing and if they are too close it will stop motor. I want to add 2-4 more but it adds a lot of delay because of
pulseIn();

command. I want to use attiny as sensor reader and just dump current data when requested.
Is it possible for arduino nano to be i2c slave (hardware i2c) and at same time i2c master (software i2c/please library without using timers... im short on them) or there is way to dump data in less than 2ms via serial or some other protocol? SPI is already used for RF24 and i need RF24 to be up all the time.

What is the length of the data to be transmitted? In any case using a UART you can send, at 115200, around 230 bits (23 bytes) in 2 milliseconds (count 8 bits/byte + start and stop bits). At 9600 you can send sligthly less than 2 bytes. Is this enough? Since the attiny just has to check it asynchronously an asynchronous transmission (UART) is better if it has enough bandwidth)

I would need around 6 bytes, struct of 6 bytes (6 ultrasonic sensor readings), is there Serial_Anything like I2C_anything?

What do you mean? Serial.write(buf, len) and, well, the reading has to done byte by byte using the Serial.read() function

Oh thanks, i didnt know that i could use (buf, len).

On simultaneous master/slave: Yes and no. You can initiate the Wire library as slave and despite of than using Wire.beginTransmission() and it's siblings to send as a master. The library will configure the hardware as master only for the time it needs to send. But there are 2 problems:

When you have multiple masters on the same bus, they have to continuously watch the bus, so that they are only starting a transmission, when the bus is free. The Wire library doesn't seem to do that.
If two masters start their transmission at the same time, the data will be good, as long all transmitted bits are equal. For other cases the I2C protocol has a rule: When 2 masters start a transmission at the same time, the first one to write a 1 to the bus (HIGH value) has to immediately back of to slave mode. (This is because to write a 1 to the data line the pullup resistors are used. When another master tries to write 0 to the bus (LOW value on SDA) he wins against the pullups, effectively writing 0 to the port, and not 1)

As mentioned on this Github issue there are some workaround, though I haven't tested them myself until now. All in all I2C multi-master may be to complex at this point.
As another option, you can use an extra line, connecting master and slaves (use the internal pullup on the masters side). Any slave can at any time write a LOW to this line, triggering the master to request data from all slaves (maybe via external interrupt or pin change interrupt).
Note: I don't know, for what purposes you used all your timers, but maybe there is a way to share one of them with other hardware, so that you don't have to use the blocking pulseIn() function. Or maybe you can tweak the timeout value of the function to a fitting value.

One timer is used for servo, other is used for millis and delay and pwm for controlling motors, third one is used by a some library i think.... Anyways in loop i have to read 5 ultrasonic sensors and it has to finish whole loop in less than 10ms, im scared that if i add too many ultrasonic sensors(max 6) that it will lag(be delayed because of 6x pulsein, i have timeout set to 60cm).


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

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

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

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

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

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

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

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

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


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

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

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

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

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


text:
24LC1025 Arduino - Data Writing Problem
I have a very big problem by writing a list of strings to an eeprom (24LC1025) Your help with my problem highly appericiated.
I have a data matrix, PageData[111][96] and I want to write all them at once, line by line to the eeprom. I am using arduino for coding.
the code is :
{

#include <Wire.h>

#define EEPROM_ADDR 0xA0;

void setup()
{

  Wire.begin();

  Serial.begin(9600);
int PageData[111][96]={ my data is here ... }

 for (t=0; t<111; t++){
  for (unsigned long i=0; i<96; i++){
    m=i*2;
    value[m] = highByte(PageData[t][i]);
    value[m+1] = lowByte(PageData[t][i]);   }

  at=((t*192));

 for (unsigned long i=0; i< 192; i++) {
    i2c_eeprom_write_byte(EEPROM_ADDR,(at+i),value[i]);
    delay(5);                             }
      }

void i2c_eeprom_write_byte( int deviceaddress, unsigned long eeaddress, byte data )
{
if( eeaddress > 65535 )
    deviceaddress = deviceaddress | B00001000;

    deviceaddress = deviceaddress >> 1;

  byte rdata = data;
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));    // Address High Byte
  Wire.write((int)(eeaddress & 0xFF));  // Address Low Byte
  Wire.write(rdata);
  Wire.endTransmission();
}

My problem in this code: when I want to read the eeprom for the checking the strings, I realize, it does not write the eeprom the whole 111 line. It just writes randomly sometimes half of this sometimes less than this amount.
I tried several ways to solve the problem. but now I am desperate , please check this and tell me where i miss a point. Please let me know, if any information you need for the answer.

111 x 96 x 2 Byte = 21312 Byte. How is this supposed to fit into your maybe 4096 Bytes SRAM? You're probably getting a stack overflow and undefined behavior.

@brhans: I am not talking about the Flash, I am refering to the SRAM of the Arduino controller. "Stack overflow" has nothing to do with external storage.

@Rev1.0 - doh - I should read more carefully - didn't even consider that the OP might be messing up the basics ...

arduino due has 96kbyte SRAM not 4096 bytes.
https://www.arduino.cc/en/Main/arduinoBoardDue

@AhmedTarhan: Granted, but you left us guessing what kind of Arduino you have. And since most have 8-bit controllers with very little ram, limited SRAM was a potential issue.

Writing a single byte is really bad. You are causing a page write with each bye, and each page has a limited lifetime (100,000 - 1,000,000 cycles) so use block instead.

When writing any amount of data, including a single byte using this
  function,   the EEPROM will refresh the entire page (128 bytes) of
  data.   EEPROMs have a limited write endurance (often 1 million cycles
  per page).   Therefore, if you write one byte at a time, instead of
  writing a full block   at once, you are wasting the chip's lifetime
  (doing so is also MUCH slower).   ONLY use this if you really only
  need to write ONE byte, and avoid it   when you can.   Using a block
  write (below), you can write 128 bytes and only use a single   page
  write (or at most two, if the write is not aligned to a page
  boundary).

This library should do the trick for you:
https://github.com/exscape/electronics/tree/master/Arduino/Libraries/EEPROM/EEPROM_24XX1025

Im sorry buddy, I don't get what you mean? Expand my answer of not writing one byte at a time? I referenced a well written out description on why, and a library that will take care of writing with pages. If you need more information, you can click on the link and read about which modules are supported. Do you need help for a specific module, or a specific scenario? The original post is about a 24LC1025 module, which is supported for the first block (64KB) by the referenced library.

authors: Виктор Аверков


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

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

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

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

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

simulate this circuit – Schematic created using CircuitLab

but I think the example in the book is ugly.

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

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

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

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

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

Looks better. :)

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

Through what resistor?

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

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

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

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

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

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

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


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

which line is it having problems with?

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

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

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


text:
Arduino reading value from external devices on
For this device it says:
The PC Interface Option has all the features of the standard DC1100, but also has a COM Port interface that allows you to capture the air quality data to a PC for graphing and analysis. A 9pin serial cable or USB-to-COM Port Adapter (not included) links the DC1100 to your PC or laptop which then captures the data as it samples.
Is it possible to connect such a device directly to an Arduino so that measured data are sent through the Serial Interface and Arduino is able to read them and manipulate them?

Yes, with a small converter board it can be connected to an Arduino. The "9 pin serial cable" is very likely an RS-232 interface.

RS-232 is like UART with a few extra connections. Here is what the cable looks like:

Basically UART with flow control and other modem lines. Most likely it hasn't any of them conencted but that standard RXD, TXD and GND. These are all the connections needed for the microcontroller.
The voltage level of RS232 is however specified in a wide range (plus/minus 3V to 25V), so you need a converter chip (e.g. this one with a MAX3232, search for "RS232 to TTL Converter Board"). You need to measure the voltage levels with a multimeter to see what converter for what voltage rage you need.

Then conencting it to an Arduino is as simple as just connecting these 3 wires to the Arduino, either to the Hardware Serial port (D0, D1, GND) or via a software serial port.
Reference project:

http://www.picprojects.net/rs232_communication/

However, receiving the communication data is only half the battle. You still have to figure out what the sent data represents and what commands you can send the device. Without datasheets from the vendor, you are left alone. This is where reverse-engineering starts.
As a starting point, you can "eaves-drop" on the communucation that PC software does with the device by just connecting a USB-RS232 converter to your computer and connecting the RX line line to either the TX or RX line of the the target device's COM port. This allows you to see the entire communication exchange. From this you might be able to see what commands you're supposed to send. But as I said, from there it's unchartered territory.


text:
How to create a device with buttons that records when they are pressed
I want to build a very simple device, which has a bunch of buttons for switching "settings" and LED lights to show which "setting" it is on.  I also want it to record the times of the transitions between settings so that I can later connect it to a computer through USB and retrieve the timestamps of the setting changes, i.e. when the buttons were pressed.
What is the best way to do this?  Is it with Arduino or some other way?  If it is with Arduino, what would I need to buy, and what would I need to read?

What research have you done? Code?

All is reasonably easy.

Buttons: use separate buttons, or think about a small 4x4 matrix keypad.
LED: WS8212 etc or use your own separate LEDs (very cheap)
Record times: store them on a SD card
USB: It is possible to send texts via USART which can connect via USB; also you can consider putting the SD card directly in your computer.

Arduino is ideal for it. Buy Arduino or Genuino UNO with Starter Kit. Starter kits contain buttons, LEDs, resistors, breadboard and example projects brochure.
link: Getting Started with Arduino


text:
my arduino uno board is not working
at once, when i connect arduino uno to my computer, my computer shuts down, after that i cannot upload programs to my computer,the board is not working but the led is ON. Before this, i upload programs 4 to 5 times continuously. i upload program with no physical connections in arduino except motor shield which is also not connected to anything.
i used three boards, all of them got damaged.
my computer's USB port and USB cable is in good codition.
i already updated my drivers.
computer spec: dell inspiron 15 3567
               windows10 x64 bit

Real Arduinos, or cheap chinese knockoffs?

Did you try without the shield connected? I think upload doesn't work when something is connected to D0, no idea if this applies to ohter pins too. When you try to upload, what error do you get? Enable verbose output during upload in the preferences.

Computer shutting down is often an indication that excess power is being drawn.
If you measure  between +5 and Gnd on the unpowered board with a meter set for resistance, do you get a reading in the 5Kohm range? Or something much lower? Much lower would be bad.


text:
ZS-040 (HC-05) blueetooth module Arduino Mega
I followed this tutorial http://www.martyncurrey.com/using-an-arduino-mega-with-a-hc-05-zs-040-at-mode/ and it seems that the AT mode is on. (the LED is blinking like it's supposed)
I connected my pins like this:

BT VCC to Arduino 5V out. Disconnect before running the sketch
BT GND to Arduino GND
BT RX (through a voltage divider) to Arduino TX1 (pin 18)
BT TX  to Arduino RX1 (no need voltage divider)   (pin 19)

This is the code I run: (from the tutorial)
// Basic Bluetooth test sketch 5a for the Arduino Mega.
// AT mode using button switch
// HC-05 with EN pin and button switch
//
// Uses serial with the host computer and serial1 for communication with the Bluetooth module
//
//  Pins
//  BT VCC to Arduino 5V out. Disconnect before running the sketch
//  BT GND to Arduino GND
//  BT RX (through a voltage divider) to Arduino TX1 (pin 18)
//  BT TX  to Arduino RX1 (no need voltage divider)   (pin 19)
//
// When a command is entered in to the serial monitor on the computer
// the Arduino will relay it to the Bluetooth module and display the result.
//

char serialByte = '0';
const byte  LEDPIN = 13;

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

    // communication with the host computer
    Serial.begin(9600);

    Serial.println("Do not power the BT module");
    Serial.println(" ");
    Serial.println("On the BT module, press the button switch (keep pressed, and at the same time power the BT module");
    Serial.println("The LED on the BT module should now flash on/off every 2 seconds");
    Serial.println("Can now release the button switch on the BT module");
    Serial.println(" ");
    Serial.println("After entering AT mode, type 1 and hit send");
    Serial.println(" ");

    // wait for the user to type "1" in the serial monitor
    while (serialByte !='1')
    {
        if ( Serial1.available() )   {  serialByte = Serial1.read();  }
    }

    // communication with the BT module on serial1
    Serial1.begin(38400);

    // LED to show we have started the serial channels
    digitalWrite(LEDPIN, HIGH);

    Serial.println(" ");
    Serial.println("AT mode.");
    Serial.println("Remember to to set Both NL & CR in the serial monitor.");
    Serial.println("The HC-05 accepts commands in both upper case and lower case");
    Serial.println(" ");
}

void loop()
{
    // listen for communication from the BT module and then write it to the serial monitor
    if ( Serial1.available() )   {  Serial.write( Serial1.read() );  }

    // listen for user input and send it to the HC-05
   if ( Serial.available() )   {  Serial1.write( Serial.read() );  }
}

I want to mention that the baud rate is set to 9600 and Both NL & CR is also set.
The problem is when I insert 1 in the Serial Monitor and nothing happens. How can I solve this problem?

Solution
Connection:

Bluetooth RXD to Arduino Mega pin 11
Bluetooth TXD to Arduino Mega pin 10
Bluetooth VCC to Arduino Mega 5V
Bluetooth GND to Arduino Mega GND

I used this code:
#include <SoftwareSerial.h>

#define RxD 10
#define TxD 11

SoftwareSerial BTSerial(RxD, TxD);

void setup(){
  // replace BAUDRATE as suggested
  BTSerial.begin(BAUDRATE);
  Serial.begin(9600);
  BTSerial.print("AT\r\n");
}

void loop(){

  if (BTSerial.available())
    Serial.write(BTSerial.read());

  if (Serial.available())
    BTSerial.write(Serial.read());

}

after setting AT mode as described in the tutorial above.
I tried running the code with BAUDRATE starting from 9600 to 460800:


text:
Can you use a RF remote with nRF24L01 and Arduino?
I recently bought a 10 pack of RF transceivers (nRF24L01). I wanted to know if its possible to pair one with an RC drone controller. I can't seem to find any ways to do this through google.
If this helps:
My drone and its controller is called "Sky Viper v2400" and a link to where you buy it is: https://www.amazon.com/Sky-Viper-01601-Streaming-Video/dp/B01D1HRXSK.
Thanks

Probably not. You'd have do dismantle the drone and find out what chip it uses. If it's the nRF24L01 or one of the Nordic SoCs with a built in nRF24L01, then it could be possible. Otherwise, no.

Even if you figure out that your drone uses the same proprietary protocol (/chip) you have to somehow determine the channel, pipes and every other piece of the radio's configuration for any (proper) communication to work.

The nRF24 operates in the 2.4GHz frequency and implements a proprietary protocol so, even if I don't have much information on your particular drone/controller, I strongly doubt there's a chance you can use the nRF24 module to talk to your drone.


text:
Using Due (SAM3X8E) native USB port for programming?
I would like to make my own version of the Arduino Due.
What I can't find the answer to is;
Can I program a blank SAM3X8E using the native USB port from within the Arduino IDE, or do I first need to program some bootloader or similar?
My board will not have the Mega16U2 which is normally used for programming.

Regardless of the answer to that question, it would be extremely unwise to design an ARM Cortex-M series board which did not make the SWD pins available at least on tiny test pads; they are just too useful during early development, and key to hardware-assisted breakpoint debugging (especially if your board ever gets used for non-Arduino purposes).  About 4 via-sized through holes will let you pick them up with wire wrap wire or similar.

I have decided to go down the SAMD21 path and have put a SWD header on my board. I use my Segger to put the Arduino boot loader into the chip and I am good to go.

The SAM3X8E comes with a bootloader in ROM.

Memories

256 to 512 Kbytes embedded Flash, 128-bit wide access, memory accelerator, dual bank
32 to 100 Kbytes embedded SRAM with dual banks
16 Kbytes ROM with embedded bootloader routines (UART, USB) and IAP routines
Static Memory Controller (SMC): SRAM, NOR, NAND support. NFC with 4 Kbyte RAM buffer and ECC

Since this bootloader does all that the Arduino IDE asks of it, and has a freely available cross-platform command-line upload tool (bossac) the IDE just uses that. No need to invent the wheel when the wheel does everything you need and even comes with a tin of axel grease.
While technically it is possible to use your own bootloader in conjunction with the existing one (use the existing one to install yours, and then use yours to upload sketches) it requires in-depth knowledge of both the chip and GCC linker ("ld") scripts to set aside a block of memory for your bootloader to reside in and relocate the compiled code around it properly. Too much work when the bootloader that already exists does what you want.
However other chips either don't have a bootloader (like the M0 in the Feather) or don't have one that works as desired (like the DFU bootloader in the ATMega32U4) so a custom bootloader is used on those.
The IDE itself is pretty dumb. It just has a configuration file that says "Execute this command with these parameters to upload the HEX file". It neither knows, nor cares, what the bootloader at the other end of the connection is, nor how it works. As long as there is a command-line executable to do the work it just hands over to it.

Hi @Majenko, I am not sure if that fully answers the question. Is that boot loader compatible with Arduino IDE?

@gjt211 That is the "bossac" bootloader that the Due uses. The question "is it compatible with the IDE" makes no sense. The IDE has no concept of bootloaders, only configuration files that specify executables to run to install the compiled file into the target. If there is a binary you can execute to interface with a bootloader you can make the IDE run that executable. Regardless: it's what the Due uses, so "yes".

Maybe it makes no sense to you, but for the thousands (millions) of Arduino users that have very little experience, the question makes a lot of sense. To those users (me included) who have no idea what bossac is, or config files that specify executables, let alone where they are or how to obtain them, where to put it if we worked all that out. All we know, select the serial port, then click upload.

@gjt211 It's expected that if you are technically adept enough to consider building your own SAMD based board that at least you understand the basics of the datasheet. Without that basic level of knowledge what are you doing even considering building something as non-trivial as a DUE-based system? ARM is considerably more complex than little AVR chips. You can't just slap one in a breadboard and expect it to work.

I appreciate your comments, but I am a full time professional hardware design engineer with over 25 years of multilayer, high speed, and RF design experience. Building something with a SAMD processor would be one of the simplest designs I have ever done. The design is for a customer, he is an Arduino guy. He wants to know if the board I designed for him will work the same as an original Arduino DUE with respect to the Arduino IDE.

Ok, so it's lack of Arduino knowledge not lack of electronic design knowledge then. Ok. The Arduino IDE is dumb (in more ways than one). It just runs executables to do jobs, including upload via a bootloader. The SAMD chips come with a bootloader in ROM, and a freely available cross-platform command line tool bossac to upload to it. So the IDE just uses that. Why re-invent the wheel when the wheel does what you want?  Other ARM based chips (like the M0 one used in the Feather) don't have a bootloader and need one installing.

I have fleshed out my answer with how the IDE interacts with the bootloader.

Most users that come here have a certain amount of Arduino knowledge but almost zero electronics knowledge. You're kind of the opposite end of the scale, so please forgive the confusion.

Microchips needs some kind of bootloader to be able programmed over USB. Arduino boards cames with default bootloader loaded (from Arduino company at least, net necesarry from Chine, probably without, if you byu just the chip from manufacturer), so on official boards it is all done for you to have aesy life.
Being able to properly communicate over USB is not exactly easy task and there are many different protocols for sending program to bootloader, which is then resposible to put the program at flash memory at proper place and give it controll later.
Also keep in mind, that there are other ways, how to put program in memory and that not all devices using some microcontroler are even meant to be programable by user over it. (For example they may idetyfy themself as keybords, mouses, joysticks and such to computer and be closed to reprogramming by manufactor of such device. Arduino community is only small part of industry, which uses the same chips for totally different tasks).


text:
Why do I get “ stray '#' in program ” error?
I am making an Arduino program with SIM800L module and would like to check credit status of the SIM card.
When I manually enter the command: AT+CUSD=1,"*123#" into Serial Monitor, it works fine.
But in the Arduino (1.8.7) I am receiving an error
      stray  "#" in program
when compiling this line of sketch:
      SIM800.print("AT+CUSD=1,"*123#"\r");
I am not experienced enough to fix this problem.
Could somebody help me, please?
Thank you.
Marko

I think something else is stray. Why are there three double quotes in "*123#"\r". A backslash is a normal part of a string, why did you put it outside the string?

There are four quotes in the command ("AT+CUSD=1,"*123#"\r"). When I manually enter this command into Serial Monitor, I type  AT+CUSD=1,"*123#" .

Sorry, there are four indeed. A double quote " in a string closes the string. You need the escape backslash and use " in the same way as the escape is used for \r. https://en.cppreference.com/w/cpp/language/escape

I understand that  *123#  is a string for provider to perform this function (return a info of my SIM credit). When I make a phone call from my mobitel, I just enter *123# and receive an answer with this info.

It is interesting that a similar command:    SIM800.print("ATD*123#\r");   works fine ( return OK) and without any compiler comment.

Use the escape backslash to get a double quote in a text. See: https://en.cppreference.com/w/cpp/language/escape
Is the *123$ between double quotes?
Serial.println("Hello");
Serial.println("I said: Hello to you");
Serial.println("I said: \"Hello\" to you");
Serial.println("AT+CUSD=1,\"*123#\"\r");
Serial.println("AT+CUSD=1,\"*123#\"");

I think the carriage return \r at the end is not needed when the println is used. The println adds a linefeed \n by the way.

The last suggested command   SIM800.println("AT+CUSD=1,"*123#"");  is accepted by compiler but returns only "OK" - the same answer as basic command  SIM800.println("AT+CUSD=1"); . It looks like as the parameter "*123#\  is not forwarded to SIM800?

.....or the provider does not recognise this parameter "*123#\  ?

You could try to send the ASCII code of these characters with Serial.write(). In that way you don't have to bother about escaping and the compiler doesn't see the # anymore.

The command "*123#" is translated by the compiler into "*123#" including the two double quotes. I don't know if that is recognized, I see examples that have a comma and a number after it.

Thank you all for the good will and your efforts to help me. Jot, can you please clarify what is meant by "... have a comma and a number after it."

For example AT+CUSD=1,"*123#",15 You should use the sim800 commands. On Github are arduino libraries for the sim800 that you can use (or use as an example).


text:
Using timer classes within classes
I am trying to develop a class for a pump that works on a stepper motor, it should be simple but its not working the way I thought it would. Once I move the timer object into the class the code wont compile I have tried a lot of things but nothing seems to work correctly. The goal of this whole thing is getting the stepper motor to step on its own based off of the calls from the timer object.
pump.h
#include "TimerObject.h"`
#ifndef Pump_h
#define Pump_h

class Pump
{
  public:
     Pump(char pin_, char dir_);
    void pumpstep(void);
  private:
    char pin;
    char dir;
    TimerObject *pumptimer;
};

#endif

pump.cpp
Pump::Pump(char pin_, char dir_)
{
    pin = pin_;
    dir = dir_;
    pumptimer = new TimerObject(100, &this->pumpStep); //PROBLEM IS HERE

  pinMode(pin, OUTPUT);
  pinMode(dir, OUTPUT);
}

void Pump::pumpstep(void) {
     Serial.println("Stepping");
}

my .ino simply creates the class passing in the needed parameters but everything binds up when I try to compile because of the callback in the constructor for the timer, for some reason It wont let me use the address of a non-static method here but I cant make the method static each pumpstep() method must be separate depending on which pump is running.
I have tried using &Pump::pumpstep, &(Pump::pumpstep) and many more pointers but cant seem to get the one I need.
outside this class the timer was working great I used this line below:
pumptimer = new TimerObject(100, &pumpStep);

The library for the timer can be found here:
https://playground.arduino.cc/Code/ArduinoTimerObject
Any help would be greatly appreciated.

You cannot. A member function has a different prototype to a global function. There are ways around it, but you really dont need that library to make something happen periodically. Only a couple of lines of code and one unsigned long variable.

The function prototype of a member function is completely different to that of a global function. The two are not interchangeable.
There are ways of working around it, such as "bouncing" your callback through a global function, but they're messy.
However, in this situation you are better off just ditching TimerObjects.h and doing it manually - it's not exactly difficult:
#ifndef Pump_h
#define Pump_h

class Pump
{
  public:
     Pump(char pin_, char dir_);
     void pumpstep(void);
     uint32_t ts;
     void run()
  private:
    char pin;
    char dir;
};

#endif

Pump::Pump(char pin_, char dir_)
{
    pin = pin_;
    dir = dir_;
    ts = 0;
    pinMode(pin, OUTPUT);
    pinMode(dir, OUTPUT);
}

void Pump::pumpstep(void) {
     Serial.println("Stepping");
}

void Pump::run() {
    if (millis() - ts >= 100) {
        ts += 100;
        pumpStep();
    }
}

Then in loop call:
myPump.run();

You can, of course, just combine run() and pumpstep() into one single function.


text:
Upcoming Project
Hey guys I have a project that will require 20 I/O pins with serial communication from a computer to control each of the pins. I would like something as small as possible would a arduino micro or uno work for this project or will i need to go bigger like a mega. I have looked at all the pinouts but am confused to know of which pins I can use as digital I/O or not.
Thanks

rarely do you need 20 IO pins if you play your cards right; i have an LCD, INA219 module, a button and an LED on one ESP-01. Take advantage of i2c, ws2812, charleyplexing, etc, then use expanders or pro-minis if needed.

i would also consider an ESP32. you can disable wifi, and it's still a beast of an arduino; it can do your 20GPIOs, and even a devkit is much smaller than a mega, for about the same price or less. The raw power makes coding easier since higher level instructions run plenty fast enough (String class, double, serialized objects in SPIFFS vs EEPROM structs, etc). And who can complain about hundreds of KB of RAM?

@Cameroony Please see the link above for answers to a pretty similar question. Hopefully you get some answers there. If this is not a duplicate, please edit your question and let us know how your question is different.

There are a couple of options

Easiest = Use an Arduino with a greater number of pins (e.g. MEGA2560)
Easy = Use an add-on board (e.g. Teensy)
Harder = Use shift registers (see Is there a way to have more than 14 Output pins on arduino?)

Further discussion on these options here.

If you require 20 I/O pins then use Arduino Mega. If it’s too big then use Nano, Micro or Pro Mini (you need a serial thingy to program the Mini) with I/O expanders like PCF8574P with I2C communication or MCP23S17 with SPI communication.


text:
Why NRF24L01+ pipe has 5 byte address
I am studying NRF24L01+ module. I see, that only 6 receivers can be connected with the transmitter, via their unique pipes. What I can’t get is why the pipe id (address) has 5 long bytes.
As to me,1 byte would be much more than enough.
What is the purpose in 5-byte address in 5 bidirectional communications?

I see, that only 6 receivers can be connected with the transmitter source link?

@MaximilianGerhardt, In every worthy tutorial I found. In docs also: http://tmrh20.github.io/RF24/classRF24.html#a9edc910ccc1ffcff56814b08faca5535

what would you do if you had a 100 clusters of 6 receivers each near each other?

The datasheet (https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss_Preliminary_Product_Specification_v1_0.pdf) page 54 shows 6 pipes, and each pipe holds a 5 byte (max) address; (actually, RX addresses 2-6 only modify the last 8 bit of the pipe1)). So you can have 6 communication partners and each one is identified by a 40-bit address, so 2^40 possibilities. It comes down to address space (for addresses) and hardware limitations (number of pipes). If the address space was too small, you would have address collisions (two or more modules have the same address), which is bad.

@jsotola that question disturbs me too. how should I generate these pipe ids.

use your birthday

5 bytes = more than 1 million million unique addresses, although not all addresses (as the nRF24L01 datasheet points out) are advised, for instance because they mimic the nRF's preamble packet.
So what is the purpose of addresses?
The purpose is to ensure that radio transmissions are received at the intended radio module.  Consider a radio network where you have 1 transmitter (TX) and 3 receivers (RXs) within range of one another, all using the same radio frequency (channel).  Now all receivers will detect a message sent by the transmitter, but only act upon it, such as raising an interrupt flag, it if the TX and RX addresses match.  To avoid chaotic communication, failed packets or on-air collisions you need each receiver to have a unique address.  Consider these like a postal address.  You should have an intuition of what would happen to your mail if both you and your neighbor had the exact same address.  Since the 2.4 GHz band can be extremely busy in public places with WiFi and Bluetooth traffic (which as an aside, Bluetooth is based on the nRF protocol), having 40 address bits seems quite sensible, as the probability of matching addresses by chance is almost zero.
So what are pipes?
If you read the nRF datasheet, you will see that in TX mode the radio can only send on using one address.  In RX mode, the radio will listen for messages on up to 6 different addresses.  Why 6?  This is likely arbitrary - a balance between register memory allocation, most probable number of nRF modules being used simultaneously and the likelihood of more efficient network topologies (such as star/tree networks) that do not require huge numbers of pipes.  A pipe represents one of these 6 addresses that a radio can receive the message and send and an ACK packet if requested.  That's all.
I hope this answer clears any confusion you had between nRF addresses and pipes.

I see, that only 6 receivers can be connected with the transmitter,

That depends on how you define "connected".  It is only possible for one transmitter to, at any one time, send data to up to 6 other devices (one per pipe). However, that is something that is very rarely done.
In practice no more than 2 pipes are needed for you to communicate with thousands of devices.
In general:

Pipe 0 is the pipe you send data on
Pipe 1 is the pipe you listen for incoming data on

You should always send on pipe 0 because that is the pipe that any ACK messages will be received on (set pipe 0's address to the address you are sending to).
With pipe 1 set to the receive address you are always ready to receive data from elsewhere.
The transmitter doesn't need to know about every other device - only the one device it is sending data to at any one moment in time.
You can set up multiple addresses on other pipes if you want to receive data that is being sent to different addresses, though there's not many circumstances where you'd want to do that (such as if you want to communicate with different pipe widths to different groups of nodes, effectively bridging between two separate networks).
In summary:

Pipe 0's address changes all the time depending on who you are sending to (assuming you are using Auto ACK)
Pipe 1's address is static and is your address that you will receive on.

To illustrate it more:

Node A has address "NODEA".
Node B has address "NODEB".
Node C has address "NODEC".

Node A has pipe 1 address set to "NODEA".
Node B has pipe 1 address set to "NODEB".
Node C has pipe 1 address set to "NODEC".

Node A sets pipe 0 address to "NODEC"
Node A sends a packet through pipe 0
Node C receives the packet on pipe 1 since it's addressed to "NODEC"
Node C responds with an ACK to its own address ("NODEC")
Node A receives the ACK on pipe 0 since it's address is "NODEC".

Node A sets pipe 0 address to "NODEB"
Node A sends a packet through pipe 0
Node B receives the packet on pipe 1 since it's addressed to "NODEB"
Node B responds with an ACK to its own address ("NODEB")
Node A receives the ACK on pipe 0 since it's address is "NODEB".

what is the difference between pipes and addresses then?

A pipe is what you communicate through. An address is where you communicate from or to.


text:
Multiple serial monitors with the same arduino mega
I’ve got mega 2560.
In my project serial port is used for communicating with PC.
However, I’d like to see debug info in serial monitor. Mega has a few hardware Serial ports. How to use one of them got extra serial monitor?

Use an USB to TTL Serial adapter. Wire it to one of the RX/TX pin pairs and in code use the corresponding Serial object Serial1, Serial2 or Serial3. Don't forget to wire Ground.
You can use some terminal program or Serial Monitor in Arduino IDE to communicate over the adapter. You can open a second instance of the Arduino IDE by starting it with the Desktop or menu shortcut. In this instance you can select a different port then the sketch upload port.

https://arduino.stackexchange.com/questions/57653/can-i-have-two-separated-serial-monitor-for-the-same-arduino-board-connected-to/57669

You need to connect one (or more) to your PC. To do that you would use a USB to TTL UART adaptor, like an FT232 board.
That will give you a new COM port that you can open with your terminal program of choice, though opening the Arduino "serial monitor" multiple times might be somewhat difficult.


text:
What killed my Arduino nano?
Yesterday evening everything worked well. Today morning I am trying to upload sketch to the Arduino (nano china, CH340) and get the following:
Writing |

avrdude: stk500_paged_write(): (a) protocol error, expect=0x14, resp=0x00

############avrdude: stk500_cmd(): programmer is out of sync

avrdude: stk500_recv(): programmer is not responding

Check wiring, settings, cable, another PC. The same result.
Took another Arduino from the same supply. Works.
What could damage my Arduino nano? Static voltage? This is the first time in 3 years of insensitive playing with Arduino. I was told that Arduino nano is quite tolerant to static voltage.
What can I do with this damaged Arduino? Is it possible to restore it?
The boards is still recognizable by PC and blinks with leds when it is connected.

why are you so certain that it is damaged?

Since the Arduino is still recognized, try to open a serial monitor and send some data to the Arduino. The RX LED should light up shortly. That would show, that the serial data is still transmitted. Then you can try to burn the bootloader again via an another Arduino

Could be that the flash in the main chip is dead and the data isn't being written correctly. That's what you get when you buy boards made with chips taken from the factory reject bin.

i saw that message a few years ago. iirc, rebooting my pc fixed it.


text:
make servo stay at the current position when attach() is called
I use a small SG90 servo with arduino.
When I call attach() servo moves to its default position or whatever I set with write() before it.
I’d like to make servo stay at the current position when I call attach() in setup().
How can I achieve it?
I believe I can simply store last position in EEPROM. It’ll help a little. However, I’m afraid that EEPROM won’t last long.

Why would you call attach() time and again?

You can't read the servo's position, so your sketch has no chance to know the real current position.
And you found that you have to set up the initial value of the servo "driver" to the one your sketch thinks is the last known position of the servo.
So your problem boils down to these questions: "How do I store a value during power-down times?" This leads to the common solution of storing the value in the EEPROM. This is a well-known and widely accepted solution, but you already found a problem: "How could a value be stored in the EEPROM without over-stressing it?"
You need to look up the guaranteed number of write cycles for a EEPROM cell. Then you need to think about the rate you would like to save the value. Divide the values and you know how long this will work. However, in reality the EEPROM will have much better endurance.
Some ideas how to "get better":

Reduce the rate of saving. I see at least two factors: The refresh rate of the servo controlling pulse is just 50 Hz. And a servo will move between (extreme) positions only a few times per second. There might be no need to save more than once per second, or even slower, depending on your application.
Don't save if the value has not changed. Well, this should be done already at the driver level of the EEPROM. It won't hurt to read its documentation and/or its source code.
Use an as large as possible array to store the value. You will store a marker for "invalid" in all but one cell, and only this cell holds the real value. This will put the "load" of two writes per save on the EEPROM, but distribution over more than two cells will lower the average load. If you select an all-1s value as "invalid", it is actually just the same value as the erased value of the EEPROM, which is necessary the next time anyway.
Add a circuit that detects the power loss before the CPU stops. This is the most chosen solution, but only usable when the hardware can do it. You need just a few milliseconds to save the value, look up the documentation. If you implement an ISR that catches the coming power loss, save the value and await the end.


text:
What fuses should I set without a boot loader with arduino nano 328pb?
What fuses should I set in order to use all the 32768 byte of Flash memory correctly?

What do you mean with "correctly"? You don't need to set fuses to use the 328 without a bootloader.

For instance, I have to disable BOOTRST to use memory of boot loader. You won’t see any problem in most cases, until firmware size is comparatively small.
My Arduino Nano won’t start with firmware of size more than 30720 bytes until I disable BOOTRST.
Playing with BOOTSZ1 and BOOTSZ0 also spares some more bytes.
However, I can’t find ultimate manual how to be able to use all the 32768 bytes.

Using the "minicore" Arduino core is the recommended way of using an Atmega328PB chip (or indeed an Atmega328p chip) with Arduino environment if you do not require a bootloader. It will set the fuses correctly for no bootloader operation.
https://github.com/MCUdude/MiniCore

You disable BOOTRST. That's it. The "ultimate manual" you refer to is the datasheet which is currently at https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf.
If that link doesn't work, try Googling "atmega328 datasheet".


text:
How to obtain the type of DHT sensor
I made a simple temperature controller on DHT11.
I want it to work with DHT22 as well having the same code.
However, I can’t find a way how to get known what type of sensor is installed.
Is there a way?

internet search reveals that DHT11  needs 1 second between readings ... DHT22 needs 2 seconds between readings  .... run tests .... see what happens if you try to read each of the sensors at 1.2 second intervals

You can use another library for DHT: https://github.com/markruys/arduino-DHT
Although, the library is quite old, it works fine and has auto-detection feature.

Wow, I'll try this library. Thanks!

I don't think that is possible.
What you should do is pass the type (DHT11 or DHT12) to the code, store it and change calculations (or functions) accordingly.
If you use a class, you can pass it as argument of the constructor, so the user of the library only need to set it up once (in the constructor where it belongs). Make it an enumeration, copy it into a class variable and all methods inside your class can use the type.
Something like (not checked):
MyDht.hpp:
class MyDht
{
public:
    enum EType { DHT11, DHT12 };

    public MyDht(EType type);

private:
    EType _type;
}

Dht.cpp:
MyDht::MyDht(EType type)
{
    _type = type;
}

And you create the class by:
MyDht sensor1(MyDht::DHT11);
MyDht sensor2(Mydht::DHT12);

Actually it is possible. If DHT type is wrong, I get empty results. Then I try another type and the results are correct.

Ok, than use your method in case you don't know, and use mine if you want to do it programmatically... Actually, you could combine both solutions by creating (dynamically) the correct type after your 'one time check', Create a pointer to MyDht, and create either a DHT11 or DHT12 instance.


text:
Program size optimization
I am trying to spare a few bytes of program size.
I faced a problem which I cannot understand and I hope somebody will help.
Look at this empty sketch, pleas. It takes just 444 bytes:
void setup()
{
}

void loop()
{
}

However, this one – 1332 bytes already!
void f() {
    Serial.println(1);
}

void setup()
{
}

void loop()
{
}

Why?
It is supposed that function f() will be cut-off during the linkage stage. But it is not.
And what can I do to cut such things off, since they are not used in the code?

The problem is not f(), it's the fact you're now using the Serial object, which is massive.

@Majenko Is it possible to optimize it some-how?

Don't put code in that you don't need? If you want optional code use #ifdef etc to include/exclude it so the compiler never sees it.

@Majenko,
As I know, unused code must be optimized during the linkage or so.

You may find that making f() static, as in static void f() { will give the compiler enough information to recognize early on that f is unused and prevent it from building dependencies for println that it later has to work to figure out whether or not it can eliminate; this is not particularly Arduino related.

If you don't like the big Serialimplementation, you may want to implement some bare-metal UART driver, like in https://exploreembedded.com/wiki/Serial_UART_Interface_with_AVR.

Using the Serial object pulls HardwareSerial0.o into your program
linkage. This file defines, among other things, the ISRs (interrupt
service routines) associated with the serial port. ISRs are defined
using the ISR() macro from the acr-libc. This macro creates a
function prototype and assigns some attributes to the function,
including the used attribute which tells the linker that it
should consider the function to be used, even if it cannot spot a single
call to it within the compiled program. The ISR cannot then be removed,
and it in turn keeps lots of code from the Serial implementation.
Edit: As pointed out by the busybee in a comment, although f()
cannot be removed at link time, it can be removed at compile time if you
give it the static qualifier. This has the added benefit of triggering
a compiler warning:

warning: 'void f()' defined but not used [-Wunused-function]

You might like to add that the missing static forces the compiler to include f() in the first place. All other stuff is then pulled in by this.

@thebusybee: Right, I edited my answer.