text:
Can batteries be damaged?
I have some questions when it comes to draining batteries with low power projects.
I have been making a few low power projects with Arduino Pro Minis running on batteries. Some run on single non-recharchable CR123As while others run on two or three recharchable AAAs. I have removed the regulator and the power led on the Pro Minis, and I have changed the fuses making them run as low as 1.8v (or according to my measurements 1.7v). This way they consume a few µA and should be able to run for years on those batteries.
Now, what started to concern me is that this setup will be able to run the batteries very low. According to the voltage curve of a CR123A, it will be practically drained when reaching 1.7v. The same goes for two or three recharchable NiMH AAAs, that will have an individual voltage of 0.85v or 0.55v. Unless the batteries themselves have a discharge protection built in. In that case there might be no problem at all; I just don't know if batteries such as Eneloops have that.
So my questions are:
1) Do batteries such as CR123As and Eneloops have built in discharge protection so that they stop supplying power when the voltage is too low?
2) If no, will draining a non-rechargable CR123A be dangerous or problematic in any way? And will draining MiMHs down to 0.85v/0.55v hurt the batteries?
3) And, a question that I suppose applies to any battery powered Arduino project: When the supplied voltage drops below the Pro Minis BOD limit, will the Arduino stop using any power, or will it continue draining the batteries until they are completely empty? (In the first case I guess I could stick with the factory set BOD at 2.7v to protect the batteries.)
4) Finally, relating to the first question: Should I try to construct some kind of battery protection in the circuit, or is unnecessary when using CR123A and NiMH batteries?

Consider posting this on Electrical Engineering SE rather than Arduino SE.

1) Do batteries such as CR123As and Eneloops have built in discharge protection so that they stop supplying power when the voltage is too low?

No, they don't.  They just run till there is nothing left.

2) If no, will draining a non-rechargable CR123A be dangerous or problematic in any way? And will draining MiMHs down to 0.85v/0.55v hurt the batteries?

A single cell can be run completely flat without problems. NiMH may need some "recovery" to wake them back up again, but shouldn't suffer serious problems (and no safety issues).  However, batteries are a different matter: see below.

3) And, a question that I suppose applies to any battery powered Arduino project: When the supplied voltage drops below the Pro Minis BOD limit, will the Arduino stop using any power, or will it continue draining the batteries until they are completely empty? (In the first case I guess I could stick with the factory set BOD at 2.7v to protect the batteries.)

It will continue draining power. The BOD is a reset circuit - designed to recover the system into a known good state after a dip in the power. A permanent decrease in the input power is beyond the scope of the BOD system.  It will just get stuck in a BOD reset loop and consume all your remaining power.

4) Finally, relating to the first question: Should I try to construct some kind of battery protection in the circuit, or is unnecessary when using CR123A and NiMH batteries?

For a single non-rechargeable cell you can just let it run flat. For NiMH you need to protect them.  Here's why (and what I was alluding to above):

When you have two or more cells in series (a battery) the current flows through all the cells of the battery equally. That is all fine when the cells are all fully charged - however no two cells are precisely the same.
As the battery runs down each cell will approach "empty" at a different time. With a single cell that's not really a problem, since it will just stop providing enough current to run.  However, with multiple cells one cell will run flat before the others. At that point the current provided by the other cells which still have some charge in them will be pushed through the flat cell backwards.  It is at that point that the flat cell becomes irrevocably damaged.  Current flowing backwards through the cell will try to reverse charge the battery and mess up the internal chemistry beyond recovery.
In the best case scenario, your battery will now have a much lower capacity and need recharging far more often. Worst case scenario: that damaged cell overheats and explodes.
The most prevalent problem that is caused by reverse charging is the depositing of metal crystals on the dielectric (the separator between the two electrodes) in the cell which grow and pierce the dielectric causing short circuits within the cell. There is no way back from that happening.
So you should protect your NiMH batteries from over-discharge by cutting the power to your circuit when the voltage drops below a specific threshold.  You should also recharge all the cells individually, not together in series, or they will end up unbalanced and the same problems of over-discharge can occur.

As a side note: I use the terms "cell" and "battery" with their "proper" usage: A cell is a single power-producing unit, such as an AA "battery".  A battery is a collection of cells.  This is the proper usage of the words, not the common usage where battery can also be taken to mean cell.  I use these terms specifically to differentiate between a single unit and a collection of units because of the major differences in how you need to handle them. It helps prevent confusion if you know that I am talking about just one AA (a cell) or a collection of three AA in series (a battery), for example.

Wow, thanks, Majenko, that was a quick and brilliantly explained answer.
The conclusion then would be that I can stop worrying about my project running CR123A cells (thanks for clarifying those terms!) while I need to make protective circuits for my projects with NiMH batteries.
I must admit that I am relatively new to electronics, so please excuse yet another question: What would be a simple way to introduce discharge protection to a low power project? Is it possible without drawing much current? My projects consume 5-30 µa in sleep mode, and I would love to keep them in that range.

You can measure the power supply voltage directly with the Arduino (see here), and implement a simple "soft power" switch using a P-channel MOSFET (wired so it's normally off, and the Arduino turns it on with a GPIO - use a button to bypass it to turn the system on).  Draws next to nothing, governed by the values of pullup resistors alone.


text:
What is a cheap way to measure co2 or o2 level in air?
I am making an air purifier which also increases o2 level as a school project but facing some difficulties. I plan to run the purifier whenever the co2 level is higher than usual or o2 level is lesser than usual but the sensor available in the market are quite expensive. So is there any cheaper alternative or any other method to detect a change in concentration?

why are you asking that question on an Arduino website? .... it has nothing to do with Arduinos ...... you may have better luck at a chemistry site

source: Stack Exchange

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

sort: votes


text:
The servo sweep library code - "delay" versus "in steps of"
This is a pretty basic question - essentially I want to know the difference between adjusting the basic sweep code (from the library) in terms of the "delay" instruction and the "pos += 1" (in steps of 1 degree) instruction.
For my project I want my servo to move 60 degrees at the same frequency as a heart beating relatively fast (lets say two beats a second). I.e., the servo moves from zero to 60 degrees twice in one second. Should I adjust the 'delay' or the 'position' instruction from the library? What's the difference? Does it matter which one I adjust as long as it does what I need it to?
Thanks for your time!

when it comes to programming microcontrollers, the microcontroller does exactly what you tell it to do, no more, no less .... regarding servo moves from zero to 60 degrees twice in one second, you can only move zero to 60 once ..... you have to return to zero before the action can be repeated .... the microcontroller  will not return the servo to zero without a specific instruction to do so

as long as it does what I need it to .... you have not clearly defined how the servo should move, so the question is not answerable

Changing the delay and leaving the increment to one generally gives a "smoother" movement. In fact, if you want for instance to move (roughly) five times faster than the example you can either move the delay to 3ms or increment the position by 5. This is what happens at the position request:
Time   0  3  6  9 12 15 18 21 24 27 30 33 ...
Delay  0  1  2  3  4  5  6  7  8  9 10 11 ...
Incr.  0  0  0  0  0  5  5  5  5  5 10 10 ...

Now, usually I try to use the delay approach as much as I can; the limitations on that approach are that it becomes more CPU consuming if you should also perform other actions between two movements (which is not your case, since you are using delays).
In order to perform four 60° movements in one second you should wait roughly 4ms between calls.
In any case, even if the single increment is the best solution, as long as you perform one movement every 10-20ms you won't be able to see any differences, so even increasing the position by 3 every 12ms or by 5 every 20ms is fine. If you start hearing a "pulsed" noise or see the motor going "jerkily" reduce the increments and the delay.
Note: You can also use multiple increments in order to have "fractional" delays. For instance, if you want to have one increment every 3.5ms, instead of using delayMicroseconds you can perform two increments every 7ms.

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


text:
Connecting a servo motor to an Arduino
I currently have a push solenoid connected to my standard Arduino board. The Arduino is powered via its USB cable, while the solenoid is powered using a 12V Huawei adapter (in conjunction with a MOSFET driver module).
How can I switch out the push solenoid for a servo motor? The operational voltage of the servo is 4.8 to 7.2V (with a stall torque of 13 kg-cm) to give you an idea of its size. I have been told to buy a DC-DC step-down module (to adjust the Huawei supply from 12V down to 5V) but I think it could be easier to power the servo using some sort of USB?
Or other suggestions are welcome. I want the easiest solution (since I am NOT tech savvy) and I can't buy parts until I am for certain the solution will work (that's research for you). Thanks!

You will have to check in the servos datasheet for the maximal current, that it draws (motors draw more current, when inhibited by mechanical force, so be sure to get the maximal current from the datasheet). From the data, that you gave us, I think it will draw rather much current. So you should not power it over the USB port of your PC (which gives 500mA at maximum). Also you should not use the 5V pin of your Arduino, or you may fry components like the diode, that lies in the current path from USB to 5V pin.
For your step down module, you will also have to check, if it can provide the current, that the servo needs, or you may kill it. If you want to use USB, you can use a standard USB charger or powerbank. Often these can provide more than 1A (depending on the actual product). Most USB wallwart chargers have a current specification on them. But (as said earlier) don't provide the power through the Arduino. Provide it directly from the source, so that the possibly high current for the servo does not have to pass trough the Arduino. You can also power the Arduino with the same source in parallel to the servo, so that you don't need two sources or a converter.
For more info, you will have to provide more information about the servo

Hey thanks so much for your reply :). I am going to be using the TowerPro MG995 servo. According to their website:
Current draw at idle 10MA
No load operating current draw 170MA
Stall current draw 1200MA
So I could buy a standard usb charger plugpack to power the servo (eg. 5V, 2A)? Then my next issue would be cutting and soldering these parts together I assume...

Yes, that should be sufficient. You can either cut the USB cable (charge-only cables only contain 2 wires), or you can solder your own wires directly to an USB plug. The outer contacts are connected to power. Be sure to use the correction polarisation, so that the charger is not connected the other way round.

I don't know if i understand your question properly, but if you want to connect the servo to the Arduino try connecting it to the 5v Output of your board.

Getting a DC-DC step down converter would definitely work and would be a good way to do it. However,realistically you will be fine if you connect the servo to +5V from USB, since you said it only draws absolute max of 1.2A. Almost all USB ports can handle that.


text:
Serial loopback not working with jumper wires connected
I'm a beginner to Arduino programming. Before attempting anything more complex I'm trying to get some very basic functionality first, so using some of the sketchbook examples I'm trying to get the most basic serial loopback working. I used the SerialEvent sketch as a reference point to come up with this:
String inputString = "";
bool stringComplete = false;
int inByte = 0;

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // wait for serial port to connect. Needed for native USB port only
  while (!Serial) {
    ;
  }
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
  Serial.println("Hello world\n");
}

void loop() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
  if (stringComplete) {
    Serial.println(inputString);
    inputString = "";
    stringComplete = false;
  }
}

When I flash that image to the Arduino and then open the Serial monitor, everything appears to work fine. As pictured below, whatever I type gets echoed back to me after pressing Enter:

However, it's a different story when I connect the TX and RX pins on the board, as pictured here:

As soon as I do that, the serial communication becomes totally non-responsive. It still prints out "Hello world" at the beginning, but it no longer echoes back the messages that get sent in, as you can see here:

I should say that even when it is no longer echoing messages back, the yellow "RX" light on the board does still briefly light up when I press Enter. But the "TX" light doesn't. Note that both lights light up if I unplug the jumper wire.
It seems to me that what I'm trying to do here is a very simple thing, that really shouldn't be this hard. Is there something obvious I'm missing? Any advice?

put the ATmega328p in reset for loopback test or at least upload a sketch without Serial.begin. RX/TX of the 328p is attached to RX/TX of the USB chip and to the RX, TX pins on header. wiring the pins on header together disturbs the communication between the 328p and the USB chip

You are trying to use the serial port connected to two devices at a
time:

to the on-board serial/USB bridge that allows communication with your
computer
some unspecified external serial device.

Connecting your TX (transmit pin) to two receivers is fine: whatever you
write will be received by both.
Connecting your RX to two transmitters doesn't work, you can at most
read the data sent by one transmitter.
On the Uno board, there are resistors along the serial connection
between the main MCU and the serial/USB bridge. Thanks to the resistor
on the RX line, you can connect an external device to the MCU's serial
port: The device's TX will override the USB bridge. This means the main
MCU can no longer receive what you send it from the serial monitor.

I can not comment, it turns out that this example that you are working is not very suitable, since the RX and TX are directly connected to the USB connection (for Arduino UNO), that is, you can only use these pins as long as it is loaded from Sketch uses An external power supply to connect the Arduino, my recommendation is to work if you have a sensor to verify the transmission of data by serial port. Greetings


text:
Arduino not writing full NMEA sentence to SD-card file
I'm currently building a small GPS-box that's supposed to track my location and write the full NMEA sentence to an sd card.
(I want to pars it afterwards at my pc)
I'm using the Arduino Nano and the NEO-6M GPS Module to get the data.
What works: getting the NMEA data from the module, writing to the SD-card.
Outputting the data to the serial output over Serial.write works fine.
Now I have the problem that it looks like the Arduino can't write the data fast enough to the SD-card and desyncs with the GPS module. This occasionally produces things like this: $G3,3,09,32,20,248,*4D
I have some ideas on how to fix this:
1. write the data faster
2. always wait till the data is fully written before acquiring the next fix
3. only write every second GPS fix
I tried to implement these but failed every time (sorry I'm new to this).
Here is my current code:
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

SoftwareSerial GPS_Serial(4, 3); // GPS Module’s TX to D4 & RX to D3
File GPS_File;
int NBR = 1;  //file number

void setup() {
  Serial.begin(9600);
  GPS_Serial.begin(9600);
  SD.begin(5);                  //SD Pin

  //write data to a new file
  bool rn = false;
  while (rn == false) {
    if (SD.exists(String(NBR) + ".txt")) {
      NBR = NBR + 1;
    }
    else {
      GPS_File = SD.open(String(NBR) + ".txt", FILE_WRITE);
      GPS_File.write("START\n");
      GPS_File.close();
      rn = true;
    }
  }
}

int x = 0;
int temp = 0;
char gpsData;
char buff[300];

void loop() {

  //collect data and write to buffer
  while (GPS_Serial.available() > 0) {
    gpsData = GPS_Serial.read();
    x++;
    buff[x] = gpsData;
  }

  temp = x;
  x = 1;

  GPS_File = SD.open(String(NBR) + ".txt", FILE_WRITE);

  //copy from buffer to sd
  while (x <= temp) {
    GPS_File.print(buff[x]);
    x++;
  }

  GPS_File.close();

  x = 0;
  temp = 0;
}

You need to overhaul your serial reading. And don't keep closing and opening the file (use GPS_File.flush() instead).  https://majenko.co.uk/blog/reading-serial-arduino

while (GPS_Serial.available() > 0) might break in the middle because the loop is faster than the speed of (byte) transmission. You might like to wait for the end-of-line character.

@Majenko implementing the File.flush() improved it a bit and made it possible to get full sets while the GPS has no signal. Sadly, when the GPS acquires a signal the data amount goes up by a lot and it can't keep up anymore leading to desyncs

@Majenko implementing the readline from your link sadly didn't improve it and led to more desyncs.

After trying different approaches I decided to dumb it down to its most basic level.
Without any fancy coding or buffers, I'm now just writing the data directly to the SD-card and flushing every 15 seconds which has the risk to loose up to 15 seconds of data i.e. 15 GPS-fixes (1 per second) when cutting off power.
The only other time where a potential data loss can happen is observed when the program flushes the accumulated data to the SD. This doesn't happen every time though.
To pars the NMEA-sentences into usable data I use GPSBabel. It automatically ignores the broken lines. After converting to .gpx I view it with Google Earth.
This is the "finished" code:
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

SoftwareSerial GPS_Serial(4, 3);  // GPS Module’s TX to D4 & RX to D3
File GPS_File;
int NBR = 1;                      //file number

unsigned long TimerA;             //save timer
bool sw = false;                  //save timer switch

void setup() {
  Serial.begin(9600);
  GPS_Serial.begin(9600);
  SD.begin(5);                    //SD Pin

  //write data to a new file
  bool rn = false;
  while (rn == false) {
    if (SD.exists(String(NBR) + ".txt")) {
      NBR = NBR + 1;
    }
    else {
      GPS_File = SD.open(String(NBR) + ".txt", FILE_WRITE);
      GPS_File.write("START\n");
      rn = true;
    }
  }
}

void loop() {
  while (GPS_Serial.available() > 0) {
    GPS_File.write(GPS_Serial.read());
  }

  //set up timer
  if ( sw == false) {
    TimerA = millis();
    sw = true;
  }

  //save every 15 seconds
  if (millis() - TimerA >= 15000UL) {
    GPS_File.flush();
    sw = false;
  }
}


text:
How to get Transmission package Timestamp from ESP8266
I am trying to make an Indoor positioning system using ESP8266 as a beacon, how do I get the transmission package timestamp from router to ESP8266 and vice-versa?
Thank you in advance for any advice

what is a transmission package timestamp?

it's the timestamp that's attached to a package every time it is sent from the receiver to the router or vice-versa

What do you hope to use the timestamp for?

I'm going to compare the received package timestamp from ap to dongle and vice versa to get the distance between the ap and dongle

You can use timestamp from NTP client and attach it
Install NTPclient library from Arduino library manager
This library uses WiFiUdp library to connect to the NTP server, so download that too
Then you can just update the time every time your sending/receiving something and log it as and how you see fit!

this answer is so wrong. it doesn't answer the question and it doesn't answer right the question I assume it answers

How do I access it though?

@Juraj oh I see! maybe I misunderstood the question, I definitely didn't know what Indoor positioning system using ESP8266 as a beacon was! I was working on sending sensor data to database and added this NTP client to get time every time i sent data to database, so i thought the requirement was the same and hence suggested it! would love to hear your thoughts!


text:
Can the function be written without ";" in the end?
I have seen the following code on the Internet:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9);
void setup()
{
  mySerial.begin(9600);
  Serial.begin(9600);
  delay(100);
}
void loop()
{
  if (Serial.available()>0)
  mySerial.write(Serial.read());
  if (mySerial.available()>0)
  Serial.write(mySerial.read());
}

The command works perfectly fine. How was it possible in the code to write the command without ";" at the end of the line?
The link to the code is: enter link description here

take a coding course or read a book about C or C++

Do you refer to this block?
if (Serial.available()>0)   <- here
mySerial.write(Serial.read());
if (mySerial.available()>0) <- here
Serial.write(mySerial.read());

If so, there is a ; at the end of each command. The commands are just split onto two lines each.  It could be written like this:
if (Serial.available()>0) mySerial.write(Serial.read());
if (mySerial.available()>0) Serial.write(mySerial.read());

The second and fourth lines are the body of the if.  Better indenting with the original arrangement would be:
if (Serial.available()>0)
    mySerial.write(Serial.read());
if (mySerial.available()>0)
    Serial.write(mySerial.read());

Or even better, include the brackets around the body:
if (Serial.available()>0) {
    mySerial.write(Serial.read());
}
if (mySerial.available()>0) {
    Serial.write(mySerial.read());
}

So this means, we are allowed to neglect the {} and () for conditions, right? But why do sometimes errors occur if I do not write this symbols?

You can omit the brackets if there is only one statement in the body of the if.

A conditional or loop expression, such as 'if' or 'while', controls the next statement or block. It does not need its own semicolon because it is not a complete complete statement. A block is one or more statements surrounded by '{' and '}' and is treated like a statement. So the following simple statement ended with ';' or block surronded by '{', '}' is a necessary part of the 'if' or 'while'.

authors: Асмир Абдимажитов


text:
unable to program esp32cam via cloned esp32-cam-mb
I bought a couple of ESP32CAMs from aliexpress... althought the listing shows them with two buttons, I got the ESP32-CAM-MB boards with just the reset button...
I have my computer set up to dual boot Windows and Linux so when I got an error in windows, I rebooted and installed the ESP32 boards for Arduino 2.1 and went ahead. I had to also install esptool and pyserial for it to work, but it ended up recognizing the port and every time I try to program it the flash flashes, but the programmer responds with

A fatal error occurred: Failed to connect to ESP32: Wrong boot mode detected (0xb)! The chip needs to be in download mode.

When I enable the serial console and press the reset button I get the following:
ets Jul 29 2019 12:21:46

rst:0x1 (POWERON_RESET),boot:0x1b (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0030,len:4
load:0x3fff0034,len:6968
load:0x40078000,len:13072
ho 0 tail 12 room 4
load:0x40080400,len:3896
entry 0x40080688
[0;32mI (31) boot: ESP-IDF v4.1-dirty 2nd stage bootloader[0m
[0;32mI (31) boot: compile time 16:15:01[0m
[0;32mI (31) boot: chip revision: 3[0m
[0;32mI (34) boot_comm: chip revision: 3, min. bootloader chip revision: 0[0m
[0;32mI (41) boot.esp32: SPI Speed      : 40MHz[0m
[0;32mI (46) boot.esp32: SPI Mode       : DIO[0m
[0;32mI (51) boot.esp32: SPI Flash Size : 4MB[0m
[0;32mI (55) boot: Enabling RNG early entropy source...[0m
[0;32mI (60) boot: Partition Table:[0m
[0;32mI (64) boot: ## Label            Usage          Type ST Offset   Length[0m
[0;32mI (71) boot:  0 nvs              WiFi data        01 02 00009000 00005000[0m
[0;32mI (79) boot:  1 otadata          OTA data         01 00 0000e000 00002000[0m
[0;32mI (86) boot:  2 app0             OTA app          00 10 00010000 00300000[0m
[0;32mI (94) boot:  3 spiffs           Unknown data     01 82 00310000 000f0000[0m
[0;32mI (101) boot: End of partition table[0m
[0;32mI (106) boot_comm: chip revision: 3, min. application chip revision: 0[0m
[0;32mI (113) esp_image: segment 0: paddr=0x00010020 vaddr=0x3f400020 size=0x1d2048 (1908808) map[0m
[0;32mI (849) esp_image: segment 1: paddr=0x001e2070 vaddr=0x3ffbdb60 size=0x04d3c ( 19772) load[0m
[0;32mI (857) esp_image: segment 2: paddr=0x001e6db4 vaddr=0x40080000 size=0x00400 (  1024) load[0m
[0;32mI (858) esp_image: segment 3: paddr=0x001e71bc vaddr=0x40080400 size=0x08e54 ( 36436) load[0m
[0;32mI (880) esp_image: segment 4: paddr=0x001f0018 vaddr=0x400d0018 size=0x9df74 (647028) map[0m
[0;32mI (1127) esp_image: segment 5: paddr=0x0028df94 vaddr=0x40089254 size=0x0b6a0 ( 46752) load[0m
[0;32mI (1159) boot: Loaded app from partition at offset 0x10000[0m
[0;32mI (1159) boot: Disabling RNG early entropy source...[0m
�
SD Size: 29557MB  OK

I can see that the board is in SPI_FAST_FLASH_BOOT mode which according to the linked documentation is wrong... but how to I get it to reboot in the correct mode?
Others have had similar issues, but they use another tool stack, so I am not sure what their solution would translate to in the Arduino 2.1 IDE...

While making sure I included all the correct links and pictures in the question, I found the answer - if an SD card is inserted, the flashing cannot be performed.
Removing the SD card and resetting the ESP32 works. I now have a very bright flashing LED


text:
Maximum signal frequency obtained at the gpios of arduino mega 2560
Is it possible to obtain the rectangular pulse signals of freuency 10 MHz simultaneously at the GPIOs of arduino mega 2560?

If you ran it at 20 MHz clock speed, maybe. But it's quite a stretch.

But in that case I am not getting perfect rectangular shape pulses. Please help me to solve the problem. Thanks in advance.

Short of replacing the on-board resonator, the maximum you can get is 8 MHz. You can get that on any of the pins identified as “PWM” (i.e. pins 2 – 13).

You should learn something about "impulse response". There is nothing like perfect. You can get closer to it by reducing parasitic capacitances/inductances and by using stronger line driver.

16 MHz is also possible if one of the fuses is changed to output the system clock.  '2560 is only rated to 16 MHz as well, at 20 MHz you'd be overclocking it:   ATmega2560/ATmega2561: • 0 - 16MHz @ 4.5V - 5.5V

The maximum fundamental frequency you can generate is fcpu/2 - or 8MHz with the default 16MHz resonator / crystal.
What shape the actual signal is, though, is very much dependant on the load on the IO pin. The IO pin has a specific drive strength which will provide limited current into a load. Any capacitance or inductance within that load causes a change in the slew rate (also known as the rise time or fall time) of the IO pin, which affects the shape of the signal by limiting the highest harmonic frequencies you observe.  At the worst case scenario, you get an almost sine wave (only the fundamental frequency gets through). In general though you get more of a rounded-off square wave:

You can improve that slew rate by adding a buffer with a higher drive strength to the output (assuming your buffer has a high enough bandwidth).  However, the IO pin itself will always have a certain amount of curvature to the signal due to its own internal capacitances.
For generating higher frequencies you are better off using a chip that is designed to operate at higher frequencies.


text:
LED brightness and Arduino ports
Hi I am learning Arduino. Pin 13 lights the LED's very brightly. With subsequent LED's on other ports the LED's are much less bright than the one on 13.
Anyone know what is going on?
regards

Wiring? Code? We're not psychic, you know...

my guess is the you are using two different kinds of LEDs ..... no other guesses are possible because you provided zero information

I used the example program in Uno called Blink.

You probably have cheap crappy inefficient leds on the other pins. Or you have the wrong value resistor in series with them. If they are not from the same batch, with the same resistor, you can't really complain. Maybe they are for a higher voltage. (because of the resistor value)
Are you sure you set the port pins for output?
pinMode(Output_PIN, OUTPUT);

I used this basic code then cut and pasted it and added two more pins 12 and 11. The LED's all came in a starter kit so I assume they are the same.
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);

The leds in the starter kit are probably a different size compared to the led on the board. Probably through hole parts, so they are not the same as what was used on the board.  Can you provide a link to the kit you bought?

Haven't got supplier details for my kit. Can you recommend a good starter kit and supplier details.


text:
How to build a wireless pump controller using arduino and esps?
I want to have automatic control for my pump, wirelessly.
A transmitter unit fitted in the water tank would sense the water level and transmit the data to a receiver unit attached to the pump starter to turn it off/on.
Also an override unit would allow me to turn the pump on/off according to my will and will also display the water level.
How do I write the code for the wireless transmission part ?

this question has been asked almost exactly same way before .... is this a school assignment?

which of the transmitters are you asking about?

Since it was closed I decided to post a new one with more specific on point questions as directed.

I want to know about how to code the wireless transmission-receiving part of the system.
For the sensor an ultrasonic sensor can be used to output the water levels.
so, the code goes like this :
if(waterlevel <= minimum )
turn pump on;
if(waterlevel = maximum)
turn pump off;
I now want to know how to send the instruction from the transmitter module (that will be attached with the tank) to the receiver module (that will be attached to the pump switch) wirelessly over my home network.

First of all I would recommend to play around with Web Server example to understand how the server hosting works. Also, the ip adders is assigned randomly to the ESP so you definitely need to write a rule in your WiFi router in order to assign a static ip to the ESP. But you can try to use mDNS to assign a name to your esp. For example http://pump.local/path. You can find some instructions here. If you are looking for simplicity you can use Blynk. It is a fully automated and free service that allows you to control you ESP from anywhere where there is a internet connection. And it also can display different variables such as the water level in your case.


text:
Look for Master and Slave code with error for a Arduino Mege
I am building a a-10c Sim. So I need lots of input and outputs. Each Arduino has 54 digital i/o and 16 analog inputs in each. As I need more I just add another arduino mega 2560.
I want to thank in advance Im am very new at his, and would welcome any help.
Regards,
Gary
Im am a dyslexic so pls excuse the spelling or bed sentences

I am not sure that I understand what you are planning to build. From the Internet I see that a "10c Sim" is a flight simulation program. Therefore I assume you plan to build some hardware, like flight stick and throttle, to provide the necessary input to the PC on which this sim program runs.
The number of digital i/o and analog inputs you mention is not true for "each Arduino" but only for an Arduino Mega.
To expand the number of i/o pins you could add another Arduino, but this makes the programming (much) more complicated. You could set them up as master and slave, where the master tells the slave which output to perform and the slave tells the master which input came in. Or you can split-up the total system into two subsystems where each Arduino has his own responsibilities to handle it's part of the system. In order not to lose many i/o pins to the connection between both Arduino's, the connection between the two Arduino's has to be serial.
But there are better possibilities to extend the number of i/o-pins. IC's (chips) exist wit a serial input and a number of (parallel) i/o pins. A special case of this are the IC's working with I2C as the serial connection. Look at Google for "i2c port expander".

The same can be said for ADC chips too if you want to expand the analog inputs.


text:
Get value from protected member of class
i'm really new to Arduino.
I have Arduino Mega, a USB host shield and a barcode scanner. I'm using this library >> link and modified it example so barcode scanner worked (Got it from here) to read what barcode scanner scanned and it worked just fine.
#include <usbhid.h>
#include <usbhub.h>
#include <hiduniversal.h>
#include <hidboot.h>
#include <SPI.h>

class MyParser : public HIDReportParser {
  public:
    MyParser();
    void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
    uint8_t getValue();
  protected:
    uint8_t KeyToAscii(bool upper, uint8_t mod, uint8_t key);
    virtual void OnKeyScanned(bool upper, uint8_t mod, uint8_t key);
    virtual void OnScanFinished();
};

MyParser::MyParser() {}

void MyParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
  // If error or empty, return
  if (buf[2] == 1 || buf[2] == 0) return;

  for (uint8_t i = 7; i >= 2; i--) {
    // If empty, skip
    if (buf[i] == 0) continue;

    // If enter signal emitted, scan finished
    if (buf[i] == UHS_HID_BOOT_KEY_ENTER) {
      OnScanFinished();
    }

    // If not, continue normally
    else {
      // If bit position not in 2, it's uppercase words
      OnKeyScanned(i > 2, buf, buf[i]);
    }

    return;
  }
}

uint8_t MyParser::getValue() {
  uint8_t getAscii;
  bool upper; uint8_t mod; uint8_t key;
  getAscii = KeyToAscii(upper, mod, key);
  return getAscii;
}

uint8_t MyParser::KeyToAscii(bool upper, uint8_t mod, uint8_t key) {
  // Letters
  if (VALUE_WITHIN(key, 0x04, 0x1d)) {
    if (upper) return (key - 4 + 'A');
    else return (key - 4 + 'a');
  }

  // Numbers
  else if (VALUE_WITHIN(key, 0x1e, 0x27)) {
    return ((key == UHS_HID_BOOT_KEY_ZERO) ? '0' : key - 0x1e + '1');
  }

  return 0;
}

void MyParser::OnKeyScanned(bool upper, uint8_t mod, uint8_t key) {
  uint8_t ascii = KeyToAscii(upper, mod, key);
  Serial.print((char)ascii);
}

void MyParser::OnScanFinished() {
  Serial.println(" - Finished");
}

USB          Usb;
USBHub       Hub(&Usb);
HIDUniversal Hid(&Usb);
MyParser     Parser;

void setup() {
  Serial.begin( 115200 );
  Serial.println("Start");

  if (Usb.Init() == -1) {
    Serial.println("OSC did not start.");
  }

  delay( 200 );

  Hid.SetReportParser(0, &Parser);
}

void loop() {
  Usb.Task();
}

So, I want to get the value from (char)ascii, store to char on loop and run it.
void MyParser::OnKeyScanned(bool upper, uint8_t mod, uint8_t key) {
  uint8_t ascii = KeyToAscii(upper, mod, key);
  Serial.print((char)ascii);
}

I tried created function that return the value but still no luck.
uint8_t MyParser::getValue() {
  uint8_t getAscii;
  bool upper; uint8_t mod; uint8_t key;
  getAscii = KeyToAscii(upper, mod, key);
  return getAscii;
}

Called it on loop:
void loop() {
  Usb.Task();
  uint8_t abcd = Parser.getValue();
  char c = (char)abcd;
  Serial.print(c);
}

What am I missing? Thank you.

Upper mod and key have no defined value in getValue.

I don't understamd, what the problem is or what you are trying to achieve. Is your KeyToAscii function not working properly? If so, how is it not working?


text:
String to Dynamic Byte array
I'm new in Arduino stuck in String to a dynamic byte array.
My String:
String Finalval="6D616320747820636E662031352033300D0A";

Dynamic Byte array:
byte ft[]={0x6D,0x61,0x63,0x20,0x74,0x78,0x20,0x63,0x6E,0x66,0x20,0x31,0x35,0x20,0x33,0x30,0x0D,0x0A};

Common C-string to byte array functions as shown in https://stackoverflow.com/questions/3408706/hexadecimal-string-to-byte-array-in-c work perfectly fine.
Source hex string: 6D616320747820636E662031352033300D0A
Conversion OK buff 0x289 len 18
output byte array:
  00 6d 61 63 20 74 78 20 63 6e 66 20 31 35 20 33 30  mac tx cnf 15 30
  10 0d 0a                                            ..

#include <Arduino.h>

void hexDump (const char *desc, const void *addr, const int len);

bool convert_hexstr_to_bytearray(const char* source, uint8_t* &output,
        size_t& output_len) {
    size_t len = strlen(source);
    //cannot convert non-even string length
    if ((len % 2) != 0) {
        return false;
    }
    //dynamically allocate output buffer
    output_len = len / 2;
    output = (uint8_t*) malloc(output_len);
    const char* curPos = source;
    for (size_t count = 0; count < len; count++) {
        sscanf(curPos, "%2hhx", output + count);
        curPos += 2;
    }
    return true;
}

String Finalval="6D616320747820636E662031352033300D0A";

void setup() {
    Serial.begin(115200);
    Serial.print("Source hex string: ");
    Serial.println(Finalval);
    Serial.flush();

    uint8_t* buffer = nullptr;
    size_t buffer_len = 0;
    if(convert_hexstr_to_bytearray(Finalval.c_str(), buffer, buffer_len)) {
        Serial.println("Conversion OK buff 0x" + String((long)buffer,HEX) + " len " + String(buffer_len));
        hexDump("output byte array", buffer, buffer_len);
    } else {
        Serial.println("Conversion failed\n");
    }

    //free memory
    if(buffer)
        free(buffer);
}

void loop() {
}

void PrintHex8(const uint8_t *data, uint8_t length) // prints 8-bit data in hex
{
     char tmp[length*2+1];
     byte first;
     byte second;
     for (int i=0; i<length; i++) {
           first = (data[i] >> 4) & 0x0f;
           second = data[i] & 0x0f;
           // base for converting single digit numbers to ASCII is 48
           // base for 10-16 to become lower-case characters a-f is 87
           // note: difference is 39
           tmp[i*2] = first+48;
           tmp[i*2+1] = second+48;
           if (first > 9) tmp[i*2] += 39;
           if (second > 9) tmp[i*2+1] += 39;
     }
     tmp[length*2] = 0;
     Serial.print(tmp);
}

void hexDump (const char *desc, const void *addr, const int len) {
    int i;
    unsigned char buff[17];
    const unsigned char *pc = (const unsigned char*)addr;

    // Output description if given.
    if (desc != NULL) {
        Serial.print (desc);
        Serial.println(":");
    }

    if (len == 0) {
        Serial.print("  ZERO LENGTH\n");
        return;
    }
    if (len < 0) {
        Serial.println("  NEGATIVE LENGTH: " + String(len));
        return;
    }

    // Process every byte in the data.
    for (i = 0; i < len; i++) {
        // Multiple of 16 means new line (with line offset).

        if ((i % 16) == 0) {
            // Just don't print ASCII for the zeroth line.
            if (i != 0) {
                Serial.print ("  ");
                Serial.println((char*)buff);
            }

            // Output the offset.
            Serial.print ("  ");
            PrintHex8((uint8_t*)&i, 1);
        }

        // Now the hex code for the specific character.
        Serial.print(" ");
        PrintHex8(pc + i,1);

        // And store a printable ASCII character for later.
        if ((pc[i] < 0x20) || (pc[i] > 0x7e))
            buff[i % 16] = '.';
        else
            buff[i % 16] = pc[i];
        buff[(i % 16) + 1] = '\0';
    }

    // Pad out last line if not exactly 16 characters.
    while ((i % 16) != 0) {
        Serial.print ("   ");
        i++;
    }

    // And print the final ASCII bit.
    Serial.print ("  ");
    Serial.println((char*)buff);
}

I'm trying this but not working         Serial.write(buffer,sizeof(buffer))

@VikashSingh, there is no statement: Serial.write(buffer,sizeof(buffer))  anywhere in the posted code.

@VikashSingh sounds like you're having an advanced problem when handling the decoded buffer. What is the exact code?

@MaximilianGerhardt thanks for help my problem solved


text:
How do I write my code to reverse the motors in the opposite direction so the RSLK can move backwards?
I've assembled the TI RSLK Robot Maze Edition for a final project for my embedded systems class. Instead of using the MSP432P401R LaunchPad that came with the kit to control the power board, I've used an Arduino MEGA 2560 instead. I'm also using a KY-023 Analog Joystick to control the two dc motors.
int xPin = A0; // analog input for x-axis joystick
int yPin = A1; // analog input for y-axis joystick

int yPosition = 0;
int xPosition = 0;

//Right motor pins
#define MRSpeed 11
#define MRDir 10
#define MRSleep 9

//Left motor pins
#define MLSpeed 8
#define MLDir 7
#define MLSleep 6

void setup() {
 Serial.begin(9600);
 pinMode(xPin, INPUT); // setup x input
 pinMode(yPin, INPUT); // setup y input

 pinMode(MRSpeed, OUTPUT);
 pinMode(MRDir, OUTPUT);
 pinMode(MRSleep, OUTPUT);
 digitalWrite(MRSleep, 1);

 pinMode(MLSpeed, OUTPUT);
 pinMode(MLDir, OUTPUT);
 pinMode(MLSleep, OUTPUT);
 digitalWrite(MLSleep, 1);

 }

 void loop() {

  yPosition = analogRead(yPin);
  xPosition = analogRead(xPin);

  //Steer Forward
  if (yPosition > 1020)
  {
    analogWrite(MRSpeed, 255); //To move right wheel forward
    analogWrite(MLSpeed, 255); //To move left wheel forward
  }

   //To stop both wheels
    else if (yPosition = 506 || 505)
    {
      analogWrite(MRSpeed, 0);
      analogWrite(MLSpeed,0);
    }

     //Turn Right
      if(xPosition < 512)
      {
       analogWrite(MRSpeed, 0);
       analogWrite(MLSpeed, 255);
      }

     //Turn Left
       if(xPosition > 1020)
       {
         analogWrite(MRSpeed, 255);
         analogWrite(MLSpeed, 0);
       }

       }

Have you tried to use those MRDir/MLDir outputs?

And also: (yPosition = 506 || 505) won't work as you hope it'll

@KIIV I've added
else if (yPosition < 505)
{
digitalWrite(MRDir, HIGH);
analogWrite(MRSpeed,255);
} But I get no movement

@Angel Please update the code in your question, if you change something, so that we can exactly see, what you changed.


text:
Controlling Multiple Brushless Motors with Arduino
I'm working on making an FPV racing drone as an introductory project to using Arduino. I need to be able to control four brushless motors using an Arduino Uno.
First of all, does anyone have any recommendations for motor type and ESC type? But my real question is: how can I power all four motors using one battery? What components do I need to buy? I've tried searching the internet for the answer but I can't find my specific use case, although it doesn't seem like it's uncommon at all.

The uncommon thing in this use case is the Arduino. These days nearly noone uses an Arduino for building a drone. Taking all the sensory input, doing the fusion of the sensor data and controlling the drone accordingly is not a trivial task. A dedicated flight controller is better fit for this task and these days not that expensive. I'm sure, that there are plenty of drone building tutorials on the web, that does not involve Arduino.

Arduino really isn't the best processor for a drone. It can certainly be done however. You can buy a MultiWii flight controller which is based around an Arduino Mega and functions as a drone flight controller.
You can't just ask which motors and ESCs to use. How heavy is your drone? How fast does it need to fly? Is there a payload? To figure out which motors to use, go watch some videos by FliteTest or a multitude of other videos online suggesting how to build a drone. You can certainly power everything off one battery. Again, watch some videos on how multirotor drones are made.
Takeway: An Arduino is a very poor choice for making a flight controller, and there quite a few components needed to build a drone, so watch some videos and learn how!


text:
i am having Strange issues when trying to read form gps serial connection
I have an Adafruit Ultimate GPS connected to a MEGA2560. I am trying to get the data from the buffer and do other data processing at the same time, however. when i allow other processing to be done the output becomes garbled such as below. the first out is correct and then becomes garbled and outputs now useful data.
16:34:54.466 -> $GPGGA,163453.155,,,,,0,00,,,M,,M,,*7F
16:34:57.111 -> $GPRMC,163453.155,V,,,,$GP$GPGGA,1$GPGGA,$GPGGA

    void loop()
    {

    GetTotalPressure();
      char c = GPS.read();
      Serial.print(c);
       if (GPS.newNMEAreceived()) {

        if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
          return;  // we can fail to parse a sentence in which case we should just wait for another
      }
      if (timer2 > millis())  timer2 = millis();

      if (millis() - timer2 > 1000) {
        timer2 = millis(); // reset the timer
    GPSScreenUpdate();
      SDcardSave();

      }

When GetTotalPressue is commented out The GPS serial output is correct when it is no the error above happens.
GetTotalPressure is below the sensor is connected to a I2C bus
void GetTotalPressure() {
  Totalpressure = ms5611.readPressure();

Many Thanks

Please, link to the GPS library you are using.

https://github.com/adafruit/Adafruit_GPS

You are not reading the GPS often enough. The method
Adafruit_GPS::read() is documented in the comments embedded in the
source code:

Read one character from the GPS device.
Call very frequently and multiple times per opportunity or the buffer
  may overflow if there are frequent NMEA sentences. An 82 character
  NMEA sentence 10 times per second will require 820 calls per second,
  and once a loop() may not be enough. Check for newNMEAreceived() after
  at least every 10 calls, or you may miss some short sentences.
returns: The character that we received, or 0 if nothing was available

Accessing the I2C bus makes loop() slower, slow enough that you get a
buffer overflow, as explained above. I suggest that, instead of reading
a single character per loop iteration, you read as many as are present
in the buffer:
void loop()
{
    GetTotalPressure();

    // Empty the GPS port receive buffer.
    while (GPS.available()) {
        char c = GPS.read();
        Serial.print(c);
    }

    // Parse any newly received NMEA sentence.
    if (GPS.newNMEAreceived()) {  // clears the newNMEAreceived flag
        if (!GPS.parse(GPS.lastNMEA()))
            return;
    }

    // Display and log location every second.
    if (millis() - timer2 > 1000) {
        timer2 = millis(); // reset the timer
        GPSScreenUpdate();
        SDcardSave();
    }
}

As an aside, I removed the line
if (timer2 > millis()) timer2 = millis();

which serves no useful purpose. If you are trying to detect millis()
overflows, you are almost certainly doing something wrong.


text:
How to run my servo until an input is recieved?
I am VERY new to this so please excuse any silly questions.
I am trying to run an FS90 micro servo in a sweeping motion until I receive a certain value from my Adafruit TCS34725 colour sensor. I currently have my loop set that it checks the colour sensor red value using an if statement and then performs a single sweep and then checks again. Rinse Repeat. Is there a way I can get it to check the sensor and stop mid sweep if there is a red colour change?

I guess, that you use delay() in your for loop. Instead of the blocking delay() call use a non-blocking coding style like in the BlinkWithoutDelay example, that comes with the Arduino IDE. It uses millis() as clock and checks, wether a specific time period has passed. If yes, it does what it needs to do, if not, it will exit fast to execute different code, until it is time to do something.

Please show us the sketch you're using.


text:
How can I set a timer?
I would like to set a stopwatch timer that will determine how long an input is in a certain state before changing. I want to set it so that, depending on the output my code executes one of 2 switch cases. But my trouble comes in on setting a timer. Is there a function I could use? Or a method that somebody knows? The time that the input will be for each case is not fixed so I cannot use a delay.

As I suggested in the comments to your other question, you can also use millis() here to measure time differences (use micros() if the time to measure is smaller than a few milliseconds).

Use micros() (reference page) to obtain a microsecond timestamp, and millis() (reference page) to obtain a millisecond timestamp.
Full Disclosure: I link to a library I maintain in my answer below, and I mention a few products (no links) I created with various techniques presented here in order to act as representative examples of when one approach might be preferred over another.
Example 1: simple linear (synchronous) software timing measurement, including low-resolution (micros()) and high-resolution (timer2.get_count())
In the simplest sense, let's measure how long it takes to set an output pin HIGH and then LOW again:
void setup()
{
    Serial.begin(115200);
    // I'll just leave pin 9 as an input; but uncomment the line below to make it an output
    // pinMode(9, OUTPUT);
}

void loop()
{
    // Measure and print how many microseconds it takes just to set an output pin HIGH and then
    // LOW again.
    uint32_t time_start_us = micros();    // <=== START TIMESTAMP
    digitalWrite(9, HIGH);
    digitalWrite(9, LOW);
    uint32_t time_end_us = micros();      // <=== END TIMESTAMP
    uint32_t time_elapsed_us = time_end_us - time_start_us;
    Serial.print("time_elapsed_us = ");
    Serial.println(time_elapsed_us);
    delay(100);
}

The really cool ShowInfo Arduino speed profiling sketch shows that Arduino's digitalWrite() function takes about 5us each, so expect the code above to print ~10us. Let's see if that's correct. I ran this on an Arduino Nano and got this output:
time_elapsed_us = 8
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 8
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 8
time_elapsed_us = 12
time_elapsed_us = 8
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 8

That's weird. Why only 8 or 12 us? Why not 10? Or 9? Or something else? Well, it turns out the Arduino micros() function only has a resolution of 4us, so it will actually print out either 8 or 12 us since those are multiples of 4 us. To get better resolution you'd have to modify the hardware timer registers, as I've done in my eRCaGuy_Timer2_Counter library, which has 0.5us-resolution. Full Disclosure: I wrote and maintain this library. It is free and open source, but I have it on my personal website, which has ads, and I solicit donations for downloads. A fully-functional snippet is also available in code at the bottom of that web-page without downloading anything.
Here is how to do the above code with my library:
#include <eRCaGuy_Timer2_Counter.h>

// Convert timer2 clock counts, which are 0.5us each, to us.
float counts_to_us(uint32_t time_counts)
{
    float time_us = (float)time_counts/2.0;
    return time_us;
}

void setup()
{
    Serial.begin(115200);
    // I'll just leave pin 9 as an input; but uncomment the line below to make it an output
    // pinMode(9, OUTPUT);

    // Configure Timer2. This MUST be done before the other Timer2_Counter functions work.
    // Note: since this messes up PWM outputs on pins 3 & 11, as well as interferes with the tone()
    // library (http: arduino.cc/en/reference/tone), you can always revert Timer2 back to normal by
    // calling `timer2.unsetup()`
    timer2.setup();
}

void loop()
{
    // Measure and print how many microseconds it takes just to set an output pin HIGH and then
    // LOW again.
    uint32_t time_start_counts = timer2.get_count();    // <=== START TIMESTAMP
    digitalWrite(9, HIGH);
    digitalWrite(9, LOW);
    uint32_t time_end_counts = timer2.get_count();      // <=== END TIMESTAMP
    uint32_t time_elapsed_counts = time_end_counts - time_start_counts;
    float time_elapsed_us = counts_to_us(time_elapsed_counts);
    Serial.print("time_elapsed_us = ");
    Serial.println(time_elapsed_us);
    delay(100);
}

Now look at the output. Here's the more accurate and precise results with my eRCaGuy_Timer2_Counter library. Much better! But why those spurious 14.50us values I have marked with <===? Why are they off by 4us? I will explain below.
time_elapsed_us = 10.00
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 14.50  <===
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 14.50  <===
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.00

The tradeoff of doing what Im doing is that you will get a 4us jitter introduced more often. Every time the 8-bit timer2 counter overflows, an ISR (Interrupt Service Routine) is called. This counts overflows to keep track of the 32-bit software timer from an 8-bit hardware counter. Entering this ISR takes about 4us, which means that if you try to grab a timestamp but then the ISR is called, you have to wait 4+us to get that timestamp, so it is off by that much. One of the several Arduino experts I really look up to, Nick Gammon, mentions this here in his Interrupts article where he says, "There is a tweaking figure of 4 µS...". So, this 8-bit counter counts at 1 tick per 0.5us, which means it rolls over every 256 ticks * 0.5us/tick = 128us. So, every 128us you will have at least a 4us delay error introduced if you try to call the timer2.get_count() exactly when the ISR is called. If you get really unlucky you may even get this effect twice and be off by as much as 8us. When using the standard micros() function, since it rolls over only every 256 ticks * 4us/tick = 1024us, you get this 4us error effect 8x less frequently. That's the tradeoff of getting better resolution: you also get more-frequent 4+us jitter.
And just for kicks, here's a really bad one. Notice the 20.50us value--off by 10.50us!
time_elapsed_us = 15.00 <===
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 15.00 <===
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 20.50 <======
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.00

Using mode filters, median filters, or other filters, these spurious results can be removed, at, of course, the cost of reduced frequency response to the thing being measured (all this means really is it takes multiple measurements to know the true value, just as we need to see with our eyes multiple measurements above to deduce 10.0us seems to be the right answer).
Example 2: non-blocking (asynchronous) timing measurement of external event
More-complicated Example: measure how long INPUT pin 9 is HIGH, and print out the HIGH time out each time it goes LOW again.
In general, use this approach for any and all input events you need to measure at the 100us to ~200us resolution or larger level. You can use this on every single pin at once and get good results with resolutions around that level, depending really just on how long your main loop takes to run each iteration.
constexpr uint8_t PIN = 9;

void setup()
{
    Serial.begin(115200);
    pinMode(PIN, INPUT);
}

void loop()
{
    // This will measure how long `SOME_PIN` is HIGH, in microseconds.

    static uint32_t time_start_us = micros();
    bool time_just_acquired = false; // true if a new time value was just measured
    uint32_t time_elapsed_us = 0;

    bool pin_state = digitalRead(PIN);
    static bool pin_state_old = LOW;

    if (pin_state == HIGH && pin_state_old == LOW)
    {
        // The pin just barely went HIGH, so "start the timer" by obtaining a timestamp of the
        // start time
        time_start_us = micros();
        pin_state_old = pin_state; // update
    }
    else if (pin_state == LOW && pin_state_old == HIGH)
    {
        // The pin just barely went LOW, so "stop the timer" by obtaining a timestamp of the
        // end time
        uint32_t time_end_us = micros();
        pin_state_old = pin_state; // update
        time_elapsed_us = time_end_us - time_start_us;
        time_just_acquired = true;
    }

    // In some other place later down the code where you need this value,
    // you can use it like this. Here I just print the value.
    if (time_just_acquired)
    {
        time_just_acquired = false; // reset
        Serial.print("time_elapsed_us = ");
        Serial.println(time_elapsed_us);
    }
}

IMPORTANT: notice in all my examples above I use ONLY UNSIGNED INTEGER variables for timestamps. This is ESSENTIAL. Using signed integers for timestamps in the same way I've written them here would be a violation of the C standard because it will produce undefined behavior when you do subtraction which results in underflow, or when the integer has overflow. Using unsigned integers, however, is perfectly valid. Ex: (uint8_t)0 - (uint8_t)1 = 255, because it is an unsigned 8-bit integer which safely underflows from its lowest value back around to its highest value. Similarly, (uint8_t)255 + (uint8_t)1 = 0 because it is an unsigned 8-bit integer which safely overflows from its highest value back around to its lowest value. This is how time_elapsed_us = time_end_us - time_start_us works in both of my examples as well. As the 32-bit microsecond counter overflows, which it will every 70 minutes or so, it wraps around back to 0. This means that sometimes time_end_us will be SMALLER than time_start_us, and you could end up with a measurement like this: time_elapsed_us = 124 - 4294967295, which equals 125.
Example 3: use external interrupts to detect changes on pins to measure external events
Use this approach when you need to measure external events at the 4~10us or larger resolution level on 2 pins maximum at a time.
This is a really good approach for measuring external events, but you get only 2 pins per Arduino Uno or Nano or similar that can do it. They are pins 2 or 3. See the table here: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/.
For a demo, see Edgar Bonet's answer here.
Example 4: use pin change interrupts to measure external events
Use this approach when you need to measure external events at the 4~10us or larger resolution level on > 2 pins maximum at a time.
These are like external interrupts except you have to manage up to 8 pins in a single interrupt service routine (ISR), instead of only 1 pin per ISR, so they aren't quite as good as "external interrupts". Every single digital-capable pin on an Arduino Uno or Nano can do this. I use this approach when reading many PWM signals from a radio control receiver, for instance, but it requires some sophistication and a ring buffer to do it right, as the time in the ISR must be minimized or else you get tons of jitter all over the place! That means you just grab the timestamp in the ISR, store it in a ring buffer, and exit. You do NOTHING ELSE! No subtraction, no math, no determining which pin fired, nothing! You then process the ring buffer of timestamps and pin states in your main loop to determine which pin changed and do the math to obtain a new time reading on that pin. I used this for passing signals through a fire-shooting battlebots hexacopter that flew on ABC TV. It worked well. It made me happy to see the ISR do its job.
Example 5: use input capture (on pin 8 only) to measure an external event
This is the "golden", or "best" approach. But, you get 1 pin per Arduino Uno or Nano that can do it. Use this approach when you need to measure external events at the 62.5 nanosecond or larger resolution level jitter-free. There will be NO ISR TIMESTAMP DELAY WHATSOEVER with this approach, which is really cool.
Input Capture is only available on 16-bit timers on the 8-bit AVR microcontrollers such as the ATmega328. Since an Uno or Nano only has 1 16-bit timer, this means they get 1 single input capture pin. It is pin 8. Don't waste this pin for anything else if you need perfect time measurements of external events using input capture. Input capture is the "perfect" way to measure external events since it stores the time count in a hardware register at the moment the event happens, without CPU interaction through an ISR, which, as we know, would cause a delay and 4+us jitter.
I first did this on a commercial product I made which needed to read a single Radio Control receiver PWM pin. It made me happy to see it work right, as it has zero jitter. I'll come back and add a demo (code only, no more mention of the product) if I get a chance. This technique is also perfect for reading PPM (Pulse Position Modulation) signals, which are just a bunch of multiplexed Radio Control PWM signals.

Your last link points the user to a website that is full of advertisements and solicits either a monetary donation or your email address to continue. This question has been locked.

That isn't supposed to happen. Can you screenshot it? I updated my ads recently to Google auto-ads. I need to adjust it and reduce them. I'll take care of it as soon as I can, but I don't know what email address or donation would possibly be requested to continue.

Also, I've never heard of locking an entire question over one link. That seems really weird.

I'm voting to close this answer because the last link points the user to a website that is full of advertisements and solicits either a monetary donation or your email address to continue.

Even though you are not running an actual (complex) Operating System, you should adhere to common practices.  For an Arduino, you should, in many cases, avoid directly controlling the hardware so as to be compatible with as many existing libraries for your particular Arduino platform as possible.
Setting the timer directly (if you are using an official Arduino Uno which contains an Atmel328P processor the processor's timers are covered in section 14 of the Atmel328P Specifications) may cause unexpected results should you use a library which expects the timer to run without being altered.
Instead, consider using the millis() function built into the Arduino IDE.  The function returns the current number of milliseconds since the Arduino was powered up.  Record this value in your code.  Then, if you want to know if One Second has elapsed, get the new value of millis and subtract this saved value from it and see if it is greater than 1000.  When that is true, One Second has elapsed.

Re “consider added the code to detect this roll over”: better to just write rollover-safe code, like if (millis() - start_time >= duration). “check to see if millis() returns a number which exceeds this value” is not rollover-safe.

True Edgar.  @Damon Swart is brand new to the site and I like trying, testing & vetting 1 idea at a time (using millis()) - then, after the 1st idea is working, adding to it (roll-over).  Also, I rather not include code.  It takes longer to post answers w/code and the code may not be correct or complete.  Besides, describing the solution makes the Original Poster think through the problem.

@Damon Swart, if you try the answer and it works for you, accept the answer as correct so that others can also find and use the answer.  If it doesn't work for you, post a comment here and we can try to change the answer so that it does work for you.

This answer should be edited to do things the safe way.  There’s no reason anyone should have to check for rollover if you write code correctly.  Always see how long it has been.  Never try to predict a future time.

Please see my proposed edit.

Your title is about “setting a timer”, but your actual question is about
measuring the length of a pulse. There are two functions provided by the
Arduino IDE for this purpose, pulseIn() and pulseInLong():

pulseIn() is based on a carefully timed delay loop. It
has a resolution of the order of one microsecond, but will not count
the time spent servicing interrupt requests. It works best for very
short pulses timed with interrupts turned off.
pulseInLong() is based on micros(). It has a
resolution of 4 µs and will not work properly if interrupts are
turned off. It works best for longer pulses where its limited
resolution and interrupt latency are tolerable.

Both of these are blocking functions: they completely block your
sketch while they perform the measurement. If you don't want your sketch
to be unresponsive during this time, you can write a non-blocking
version of pulseInLong() using a finite-state machine like
this:
// Measure the length of a pulse in a non-blocking manner.
// Returns 0 if no measurement is available at the time of the call.
void get_pulse_length() {
    static enum {
        INITIAL_WAIT,    // wait for the first (partial) pulse to end
        BETWEEN_PULSES,  // wait for the pulse to start
        WITHIN_PULSE     // wait for the pulse to end
    } pulse_state = INITIAL_WAIT;
    static uint32_t pulse_start;  // when the current pulse started

    uint8_t pin_state = digitalRead(pulse_pin);
    uint32_t now = micros();
    switch (pulse_state) {
        case INITIAL_WAIT:
            if (pin_state == LOW)
                pulse_state = BETWEEN_PULSES;
            break;
        case BETWEEN_PULSES:
            if (pin_state == HIGH) {
                pulse_start = now;
                pulse_state = WITHIN_PULSE;
            }
            break;
        case WITHIN_PULSE:
            if (pin_state == LOW) {
                pulse_state = BETWEEN_PULSES;
                return now - pulse_start;
            }
            break;
    }
    return 0;
}

Note that this measures high pulses. You will have to swap HIGH and
LOW if you want to measure low pulses. You would use it like this:
void loop() {
    uint32_t pulse_length = get_pulse_length();
    if (pulse_length) {
        // handle the pulse
    }
}

The resolution of the measurement is the execution time of loop(), so
you have to make sure there is nothing blocking there, and specially no
calls to delay(). If you need a better resolution from a non-blocking
method, you can use interrupts to trigger the measuring process:
volatile uint32_t pulse_start, pulse_length;
volatile bool pulse_valid;

void on_rise() {
    pulse_start = micros();
    attachInterrupt(digitalPinToInterrupt(pin), on_fall, FALLING);
}

void on_fall() {
    pulse_length = micros() - pulse_start;
    pulse_valid = true;
    attachInterrupt(digitalPinToInterrupt(pin), on_rise, RISING);
}

uint32_t get_pulse_length()
{
    if (!pulse_valid) return 0;
    noInterrupts();
    uint32_t pulse_length_copy = pulse_length;
    pulse_valid = false;
    interrupts();
    return pulse_length_copy;
}

void setup() {
    attachInterrupt(digitalPinToInterrupt(pin), on_rise, RISING);
}

This should give you the resolution of micros(), i.e. 4 µs, but
occasionally you may get results that are slightly off if interrupts
happen to be disabled when the input transitions. If this is
unacceptable, the only other options I see is to use a hardware timer
with input capture capability. You will have to look at the datasheet
of your microcontroller to see how it works, and maybe do a Web search
for “Arduino input capture”.


text:
Distance Measurement - between 6 points, individually moving in (almost) any direction within 1m
I'm trying to find a solution for a given task in a problem I want to solve.
Assume I have 6 individual Points in a 3D environment of about 1m³. Each point will be able to change position (almost) freely.
Is there a way I can get the information of which distance each point is to any of the remaining 5 points?
Background Idea for understanding: Say its 2 wooden triangles (one of those points on each angle) and I need to calculate how far and in which direction one is moving from or towards the other.
By comparing all those distances, direction and step-width may be easily calculated.
Are there like "coded" distance-sensors so they don't mix their signals?
Any thoughts highly appreciated.

Not a very easy task. A distance sensor always points in 1 direction, so you would need to target each individual other point with one distance sensor, while it is moving. I would think, at this point it is easier to use 2 cameras (pointed from different angles to the space) and computer vision to calculate their positions and thus get their distances.

thanks chris,
i was afraid to hear that ;)

Camera would have to be mounted on one of the triangles since they may be positioned anywhere with no outer bounds.  Only limit is that they always stay together within a given maximum distance from each other.

You may try to implement some kind of ultrasonic transponders. The
emitter sends a code addressing a specific receiver. Upon recognizing
its address, the receiver replies after a short, fixed delay. The
emitter measures the time it took the response to reach it, and from
there computes the distance.
You may need some kind of omnidirectional transducers (e.g. this
models) if you want the measurement to work in any
direction. And also a protocol to avoid several emitters talking at the
same time.
This seems to me like a very complex project though.

addressing the receiver is going into the direction I was looking for. I only knew of those sending like a small angled beam and waiting for its reflection. I didn't know of a possibility to address a specific receiver or better to have a receiver only answer to a specific emitter instead of whatever is calling.
As soon as I can locally separate emitter and receiver and have the receiver only respond to that one specific request, I'm fine to go on from here. Thank you.

The vertices of two (wooden) triangles already constrains the problem - in a positive way - since the inter-point distances of each triangle's vertices is constant. If they were 6 individual, free-floating points, the job would be that much more complex -- 30 unknown distances (each point to each other point), instead of only 18 (each vertex to each of 3 vertices on the other triangle). That's the math part.
The technology part - what kind of sensors - will need more specifics to answer. For instance, ultrasonic sensors may have an interference problem with wooden triangles drifting about. Light and radar may have visibility issues - i.e., can't see certain of the points, depending on the physical shape and implementation of the drifting objects.

okay, lets change triangles to shoes on feet. Lets say I want to keep track of tip to tip, heel to heel, shaft to shaft distances. Does that make it easier to find the right sensors? Sensors will most likely stay within visibility to each other as being mounted on the inner side and turns usually wont exceed 70-80° angles.

You counted each unknown twice: the distance from A to B is the same as the distance from B to A. Six free points is 15 distances, two triangles is 9 distances.

@EdgarBonet: Right you are - missed that.


text:
esp8266 cant make more than one request at time
i am trying to make a get request, read that request and make another request with that read value. i havent shown it in this code but i want to make a request inside in a request. is it possible to make a request without ending one, if its, how do i do that?
here is the code :
#include <ESP8266WiFi.h>

#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>

#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "pw"

void conn();
void getreq();
void anothergetreq();

void setup() {
  conn();
  getreq();
}

void loop() {
}

void getreq() {
  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/users/1");

  int httpCode = http.GET();
  String payaload = http.getString();
  Serial.print("HTTP CODE: "); Serial.println(httpCode);
  Serial.print("PAYLOAD: "); Serial.println(payaload);
  //here i presume got the value from payload, and making another request with it
  anothergetreq("posts/1");
  http.end();

}
void anothergetreq(String p) {

  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/"+p);

  int httpCode = http.GET();
  String payaload = http.getString();

  Serial.print("HTTP CODE: "); Serial.println(httpCode);
  Serial.print("PAYLOAD: "); Serial.println(payaload);
  http.end();
}

void conn() {
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
}

here is the output:
Connected with IP: 192.168.1.100

HTTP CODE: 200
PAYLOAD: {
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}
HTTP CODE: -1
PAYLOAD:

https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html#bearssl-client-secure-and-server-secure

Secure clients and servers require siginificant amounts of additional
  memory and processing to enable their cryptographic algorithms. In
  general, only a single secure client or server connection at a time
  can be processed given the little RAM present on the ESP8266

you have two BearSSL::WiFiClientSecure instances at time. it is simple to change your code to first free the first SSL client object.

i got the compile error "'client' was not declared in this scope" if i only use one ssl client object.

you can use two. only delete the first (from runtime memory, not from code) before using the second. it is possible that calling http.end() before making the second request will be enough

i dont know how to free that allocated memory, could you please show me. i managed to fully run and get the response by stopping client using  client->stop();. thank you.


text:
Using SDA and SCL with analog inputs at the same time
I'm trying to build a robot arm based on Arduino UNO and PCA9685 controlled by few potentiometers. The easiest way that I figure out and find on internet is using two Arduino's, one as master and second as slave.
This is where my question comes from, there is a way to use single Arduino UNO instead of two by using at the same time SDA and SCL with analog inputs? Maybe there is another way to do that?
That's my actual code:
#include <Arduino.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwmDriver = Adafruit_PWMServoDriver(0x40);

void setup()
{
  pwmDriver.begin();
  pwmDriver.setPWMFreq(51);
}

int tempPotVal = 0;
int adcPin[4] = {A0, A1, A2, A3};
int pwmRisingTime = 0;
int pwmFallingTime = 0;

void loop()
{
  for (int id = 0; id < 4; id++)
  {
    tempPotVal = analogRead(adcPin[id]);
    pwmFallingTime = map(tempPotVal, 113, 842, 102, 512);
    pwmDriver.setPWM(id, pwmRisingTime, pwmFallingTime);
  }
}

I2C on Uno/Nano/Mini uses only pins labeled A4 and A5. you can still use 4 ADC pins A0 to A3 on Uno.

Yes, you are right! I have absolutely no idea why it didn't work for me before and why I found so many sources on the internet saying that using these two things at the same time is impossible.

No. You can't. Not unless you could come up with some way of disconnecting one set of devices and connecting the other.
Instead you could add an I2C ADC chip to the existing SCL/SDA bus to expand the number of ADC channels you have available. Or use an analog MUX chip on one of the other ADC pins to expand the number of devices you could connect to it. Or you could add an SPI ADC chip to pins 10-13 (SPI bus) to give you more analog inputs.


text:
Arduino Uno does not detect the GPS module
I am trying to start the GLONASS NEO-7M-C module using TinyGPS++ liblary, but in the serial monitor I receive a message all the time that the module is not detected.
My connection:

PPS - None
RX - 4
TX - 3
GND - GND
VCC - 5V

is RX wired to TX?

What exactly do you mean? I connected the RX to pin 4 and TX to pin 3

Don't post screen shots of your code, post it within your question.

but 4 is RX of SoftwareSerial in your code or not? so receive to receive, transmit to transmit?

Yes you are right. Everything works well already. Thank you for your help!


text:
ATMEGA 328P Standalone on 3.3v controlling a servo
I'd like to use an ATMEGA 328P on standalone mode powered by a 3.3V supply source to control a servo (which is powered by 4 AA batteries, resulting in 6V). My question is: do I have to convert the PWM signal's peak amplitude to 5V for it to work? Or will the servo work just fine with a 3.3V amplitude signal? My servo's datasheet says its operation voltage ranges from 4.8V to 6V, but I'm not sure if that applies only to its power source or if it has implications on the control signal as well.
Servo's datasheet:
https://www.donkeyhoute.com/UploadFiles/2014916134245511.pdf
Also, since I will be using an 8 MHz external clock, do I have to change anything in my Arduino sketch regarding the PWM signal frequency, or do I just set the board to the 'Lilypad' option when burning the bootloader and keep the sketch the way it is now?

It's impossible to tell. There's no real data in that datasheet. You'll have to try it and see.

do I have to convert the PWM signal's peak amplitude to 5V for it to work?

There is insufficient information to determine that.  It may, or it may not. You'll have to try it and see.

since I will be using an 8 MHz external clock, do I have to change anything in my Arduino sketch regarding the PWM signal frequency

If the board you select is 8MHz then no, you don't need to change anything. The fact you have selected the right frequency for the board means that all the timing calculations the Arduino API does will be correct.


text:
Is there a relationship between RSSI and Power? If so, how are they connected and does it have a formula to extract one from the other?
I have searched on Google but to no avail. Perhaps you guys can help.
-Aj

Is there a relationship between RSSI and Power?

Yes

If so, how are they connected and does it have a formula to extract one from the other?

RSSI is in relation to the square-root of the power. See below references for the actual formula.
Holiday extra: RSSI for an RF433 module can be estimated by the time from end of transmission and noise. This is the time for the AGC circuit to increase gain from the received signal to the noise level. Please see Cosa RF433 library for an example.
References:

https://en.wikipedia.org/wiki/Received_signal_strength_indication
https://en.wikipedia.org/wiki/Signal_strength_in_telecommunications


text:
What is the easiest way to count how many global variables are in your sketch code?
I have a fairly complicated sketch with about 1k lines of code. I should also say that I'm not a programmer by trade...
As I go over my code and try to make it more efficient, it'd be good to know how many global variables are in my code and whether/if all of them are necessary as global. So:
1 - Is there an easy way to count how many global variables you've used (again, imagine complex code by a non-coder), and
2 - Is there an easy way in the Arduino IDE to jump to it?

You can show us the code and we tell you how to make it more efficient.

@Jot - a thousand lines?

@JaromandaX, sure, a normal sketch for a arduino Uno can be 3000 lines, 1000 lines is not a large sketch.

If you compile your code ("verify"-button) you can see the size of the program, and the amount of memory used for global variable, at the bottom of the screen.

globals aren't as evil on MCUs as they are on PCs; used right, they can save precious RAM.

all fair comments - but none answer my question: does the IDE (or any other tool) have a feature that highlights/counts your globals?

frednikgohar, you have to meet us halfway. Tell us what the compiler says about memory when you verify the sketch. It show the amount of bytes that the sketch uses (bytes and percentage) and the amount of bytes used by global variables (bytes and percentage). Show us your sketch. I don't understand what you want. If you have declared the global variables above the setup function, then that is where they are. What exactly do you want to count? variables or bytes? The compiler shows the amount of bytes when you verify the sketch.

1 - The number of variables is not important, but the number of used memory (in bytes) is important. That is shown at the bottom of the Arduino IDE by the compiler when verifying or uploading a sketch.
2 - It is not possible to go to, for example, the largest global variable. You can use the search function to search for something.
For a small microcontroller, for example a Attiny or Atmega8, every byte that uses memory can be important.
For a Arduino Uno and larger, the optimization is done more globally.
To optimize for ram, look for the hungriest memory eaters:

For the Arduino Uno and other avr microcontrollers, the text with
Serial.println can be put in PROGMEM with the F() macro.
Many String
objects might need a lot of heap memory.
Arrays can get large
quickly.
Arrays of large elements (float, struct) can get large even
more quickly.
The SD library uses a lot of ram memory. There is a small version
of the SD library.
Some graphical libraries for displays use a lot of memory.

Try to avoid to save a single byte, unless you check the resulting memory usage. The compiler can optimize code in a way that conflicts with someone trying to save a byte.

When an integer is changed into a byte,
perhaps all the calculations are still done with integers and the
compiler needs more memory to convert from byte to integer and back.
Perhaps that integer was only used in registers and
did not use a memory location.
A 'const' integer uses probably no ram memory at all.

Final tip: Don't be afraid to upgrade to an other Arduino board with more memory. If you project uses almost all the memory, then it is not possible to add something to your project. When the project runs for a while, you might want to add an extra sensor or extra functionality.


text:
Combining code for multiple sensors in a single program
I need to operate 3 different sensors (taken 6 sensors of each type) by Arduino Mega2560 :-

DHT11 (temperature-Humidity sensor)
MQ5 (gas sensor) and
Soil Moisture sensor
{taken 6 of each type (total=18).}

I have managed to run each one of them separately and I don't know how to manipulate the code so they could work all together. My background in coding is basic, so it would be great help if someone can help me for combining these codes.
Here are the sketches:
MQ5 Code:
int sensor=7;
int gas_value;
void setup()
{

pinMode(sensor,INPUT);
Serial.begin(9600);

}

void loop()
{

gas_value=digitalRead(sensor);
Serial.println(gas_value);
}

{other digital pins to be used: D6,D5,D4,D3,D2}
DHT11 Code:
#include <dht.h>
#include <dht.h>
#include "dht.h"
#define dht_apin A0 // Analog Pin sensor is connected to
dht DHT;

void setup(){

  Serial.begin(9600);
  delay(500);//Delay to let system boot
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");
  delay(1000);//Wait before accessing Sensor

}//end "setup()"

void loop(){
  //Start of Program

    DHT.read11(dht_apin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");

    delay(5000);//Wait 5 seconds before accessing sensor again.

  //Fastest should be once every two seconds.

}// end loop()

{analog pins for other sensors: A1,A2,A3,A4,A5}
Soil_Moisture Sensor Code:
int sensor_pin = A6;
int output_value ;

void setup() {

   Serial.begin(9600);
   Serial.println("Reading From the Sensor ...");
   delay(2000);

   }

void loop() {

   output_value= analogRead(sensor_pin);
   output_value = map(output_value,550,0,0,100);
   Serial.print("Mositure : ");
   Serial.print(output_value);
   Serial.println("%");
   delay(1000);
   }

{Analog pins for other sensors to be used: A6,A7,A8,A9,A10}

your finished program has to have setup() and loop() blocks ..... what do you feel that should happen with the codes in the three setup() blocks?  ..... what do you think that should happen with the code in the three loop() blocks?

All things before void setup() put before one setup() function. All things in void setup() put to the one void setup() - do not duplicate things like #include or Serial.begin(). And things from loop() function put to the loop() function.
It's a good practice to don't use delay() in  loop() when you are processing more things than one. Instead of delay() use millis() to get current uptime and after that compare this uptime to last uptime of check.
I modified your code, so read it and try it.
#include <dht.h>

#define dht_apin A0 // Analog Pin sensor is connected to
dht DHT;

int sensor=7;
int gas_value;

int sensor_pin = A6;
int output_value ;

unsigned long gas_last_time = 0;
unsigned long dht11_last_time = 0;
unsigned long analog_last_time = 0;

void setup(){
  Serial.begin(9600);
  pinMode(sensor,INPUT);
}

void loop(){
  if(millis() - gas_last_time >= 10){
    gas_last_time = millis();

    gas_value=digitalRead(sensor);
    Serial.println(gas_value);
  }

  if(millis() - dht11_last_time >= 5000){
    dht11_last_time = millis();

    DHT.read11(dht_apin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");
  }

  if(millis() - analog_last_time >= 1000){
    analog_last_time = millis();

    output_value= analogRead(sensor_pin);
    output_value = map(output_value,550,0,0,100);
    Serial.print("Mositure : ");
    Serial.print(output_value);
    Serial.println("%");
  }
}

Thank you so much for your precious help, specially in letting me know the basic things you told me via your code. A lot of thanks to you, because of all help by all you guys, I completed my code.(i'm sorry for replying too late from the day of completion of code)

@Deepanshu No problem. :)

In general:
All #defines and #includes get put from all separate sketches, at the top.
Globals and function definitions (except for setup() and loop()) get mixed together below the #defines and #includes.
All code in the separate setup()s get put in the combined setup().
All code in the separate loop()s get put in the combined loop().
You have to be aware that any loop() from the separate programs that include a delay() will likely have to be refactored to use the same kind of scheduled execution method as the Blink Without Delay example from Arduino. delay() stops the whole program while it twiddles thumbs, which means your other sensors aren't being read or managed during that time.

Thank you so much for your precious help. Because of all help by all you guys, I completed my code.(i'm sorry for replying too late from the day of completion of code)


text:
Adafruit Feather M0 Basic update bootloader
I bought a Feather M0 Basic from a reseller Lawicel however I'm missing the
UF2 boot feature. When I press the reset button two times I just
get a serial and have to program circuitpython using Bossa. The UF2
FEATHERBOOT usb storage drive as described  here doesnt show up.
I have a ARM-ICE and wired up the Feather board via SWD. I
can re-program the bootloader (first setting fuse to NVMCTRL_BOOTPROT 0x7
as described here ) via ARM-ICE.
However it seems that the Arduino bootloader featherm0bootloader_160305.zip is an old one that doesnt support the UF2 usb storage device programming protocol.
Where can I download a more recent bootloader that supports UF2 ?

this? https://learn.adafruit.com/installing-circuitpython-on-samd21-boards/installing-the-uf2-bootloader

post a link of the actual product, not the homepage of the retailer

@Juraj : Thanks, that was the one I was looking for. Programmed it and now FEATHERBOOT is appearing.


text:
MPU6050 Calibration
Why does the MPU6050 IMU sensor not require calibration? I've used other gyro sensors on RC helicopters that required calibration at boot. Also, how does it know what its neutral position is considering that I don't need to calibrate it?

it calibrates itself and as the datasheet says "Enhanced bias and sensitivity temperature stability reduces the need for user calibration".

It's not entirely true that it does not require any calibration at all.
The MPU60X0 family's triple-axis MEMS gyroscope has certain features that reduce the need for calibration. These features are, as mentioned by Juraj, and on the datasheet:

Enhanced bias
Sensitivity temperature stability

This does not mean the sensor is 100% properly calibrated right out of the box, which means if you need it to be extremely accurate, you'd probably have to do some manual calibration on top of the built-in calibration features.
There is a discussion about this on this Github issue. I suggest reading up on that and you might be able to answer your own questions. They are also referring to this datasheet (Direct Download).


text:
Replace 6 pin on/off switch on Power Bank with 3pin or 2pin?
I'm looking to finish up my project in a box and i'm using a battery bank to power the Leonardo micro pro and other components. The bank has a little on/off which on it which has 6 pins underneath.
To make the project neater I wanted to fit an on/off rocker switch to the project box making it look better and providing a more substantial switch. Mostly the on/off rocker switches come in 3 pin or 2 pin connections though. Is it possible for me to join it the 6 pin combining some of the pins in some way or not? I can also pick up another battery shield which has a 3 pin switch, again could I combine that with a 2pin if required or do I need to use a 3 pin rocker with it?
Some pictures of what i'm (or could be) using

(Current power bank, on/off switch on the right side in the middle, 6 pins)

Possible smaller power bank for my project with 3 pins on the on/off switch (bottom left side)

Two pin rocker switch

Three pin, two way rocker switch

Looks like only 2 of the 6 pins are used. It's a simple on-off. The switch itself is a "Double Pole Double Throw", but the two poles are tied together to make it single pole (like a 3 pin switch), and one throw is ignored, making it 2-pin.
You can see on the underside of your board which pins are tied together with traces. Bridge those pin pairs to turn the board on.

Thanks Majenko, so basically the two pin rocker switch will work fine, just connect the middle pin to the two pins in the middle and the other pin to the two pins on the "on" side?

That is correct.

using a double pole switch creates built-in redundancy .... if one contact fails, then the switch will still operate normally

@jsotola The redundancy is generally an added bonus. Most people use a double pole switch when it's in that style because they are far more common, and hence cheaper.