text:
Deep Sleep Reset with Shock Sensor
I am trying to design a circuit that wakes my ESP8266 (Wemos D1 Mini) from deep sleep using a shock sensor. I can achieve this using the reset pin but I need
it to ignore further requests to reset to give it time to run the code in my sketch. Provided there is still motion it will just continue to reset meaning the code only gets run after the 'shock' stops. I have tried all kinds of things with capacitors and transistors to delay subsequent resets but with very limited success. Can someone please point me in the right direction or suggest an easier way to do this? Many thanks in advance.

What kind of "shock" sensor, and what kind of "shocks" are you subjecting it to?

I'm using a ky-002 sensor. Shocks will be from slight movement.

Use the fact that GPIO16 is LOW in deepsleep and high otherwise - i.e. if GPIO16 is high, you want to prevent your shocks from effecting the reset pin - a simple OR gate may be all you need

@Tinted, why do you commet for JamesB?

This is actually somewhat more tricky than you would at first thing.
First off, the "shock sensor" is merely a spring inside a tube.  This will create lots of triggers while it's being "shocked", which really is messy.
Secondly, you only want those shocks to make it through to the ESP when you are in deep sleep.
Thirdly, you don't want whatever you connect to adversely affect, or be affected by, other circuitry that is connected to the reset pin.
So you first really need to "condition" the output of your sensor so that it gives a clean pulse that can reset the ESP8266. Then you need to "gate" that signal so it can only get through while the board is asleep.
For conditioning the shock sensor signal I would be inclined to use a 55 timer in monostable mode.  You can find a good circuit and description here which looks like this:

Now to gate that signal (which is active high) you need a signal to gate it with.  Since all the GPIOs of the ESP8266 are "dead" while it's asleep you need it to be in a "default on" state and have the ESP8266 drive an "I am awake" signal to disable the output.  So you'd have a pullup resistor on a GPIO to make it default HIGH (to match the trigger pulse for simplicity) and then use pinMode() and digitalWrite() as the first things after waking up (and at the start of setup()) to indicate it's awake by driving it LOW.  Then you combine those two signals:

If the trigger is HIGH and
If the gate signal is HIGH
Then pull reset LOW
Otherwise don't affect reset

So you make a truth table:
Trig | Gate | Res
-----------------
  L  |  L   |  HiZ
  L  |  H   |  HiZ
  H  |  L   |  HiZ
  H  |  H   |  L

The tricky one here is the "HiZ" - This means "High Impedance" - or in effect "Don't affect the reset pin at all".
Apart from that the truth table is that for a NAND gate - if both inputs are HIGH then the output is LOW - otherwise the output is HIGH.  Except we want HiZ not HIGH.
To make that HiZ there's two things you can do:

Use a NAND gate that has an "Open Collector" (or "Open Drain") output, or
Use an AND gate and create your own "Open Collector" that inverts the output by adding a transistor.

For option 1 you can use the 74AC01 which is a "Quad 2 input NAND gate Open Collector".  For option 2 you can use the 74AC08 and any NPN transistor (or N-channel MOSFET with a suitable threshold).

simulate this circuit – Schematic created using CircuitLab


text:
Ethernet.h Ethernet.Begin(mac) only connects if i have a LiquidCrystal object from LiquidCrystal.H
I have the following code;
#include <Ethernet.h>
#include <SPI.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(31, 30, 29, 28, 27, 26, 25, 24, 23, 22);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
EthernetClient client;

void setup()
{
  Serial.begin(9600);
  //client.begin(mac);
  //Init Ethernet Comms
  Serial.println(F("Start."));
  while (!Ethernet.begin(mac) == 0) {
    Serial.println(F("Network Error"));
    delay(200);
  };
  Serial.println(F("Connected"));

}

void loop() {}

As it is above it gets out of the while loop. However, if i remove the line LiquidCrystal lcd(31, 30, 29, 28, 27, 26, 25, 24, 23, 22);It will then fail to connect, and stay in the loop. Im at a complete loss here as the Ethernet shield and 2x16 LCD are unrelated devices, and if anything id expect the addition of used pins to cause issue, not the removal.
Edit: I should note this is occurring on two devices, one Mega one Uno.
2nd Edit: As pointed out by Juraj in the comments, this can be resolved using Ethernet.Init(CS_Pin) where CS_Pin is an unused pin, in my case D9.

do you have SD card inserted? if yes remove it or set the SD CS pin 4 HIGH. And I would add Ethernet.init(10);. What happens if you disconnect the LCD?

You beauty, that was exactly the issue. Oddly i have been using both the SD card and Ethernet port without issue for a while now, but only recently ran into this issue.

source: Stack Exchange

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

sort: votes


text:
How could i synchronize 2 signals
unsigned long Htime;
unsigned long Ltime;
unsigned long Ttime;
unsigned long f;
int N;

void setup() {
  // put your setup code here, to run once:
cli();
  TCNT2 = 0;
  TCCR2A = 0;
  TCCR2B = 0;
  Serial.begin(9600);
  pinMode(5,INPUT);
  pinMode(3,OUTPUT);
  pinMode(11,OUTPUT);
  TCCR2A = (1 << COM0A1) | (1 << COM0B1) | (1 << WGM21) | (1 << WGM20);
  TCCR2B = (1 << WGM22) | (1 << CS22) | (1 << CS21) | (1 << CS20);
  TIMSK2 = (1 << OCIE2A);
}

void loop() {
  // put your main code here, to run repeatedly:
  Htime = pulseIn(5, HIGH);
  Ltime = pulseIn(5, LOW);
  Ttime = Htime + Ltime;
  f = 1000000 / Ttime;
  Serial.println(f);
  N = (16000000 / 1024 / f ) - 1;
  OCR2A = N;
  OCR2B = N/2;

}

Hi this is what i have written. and i need output a square wave with timer, its frequency is measured from input signal in pin 5. After connecting the oscilloscope, i see the problem, there is phase shift between 2 signals. How could i synchronize this 2 signals?(rising edge to rising edge, falling edge to falling edge) Thank u so much for your help!

You assume a 1:1 HIGH-LOW ratio for your square output, correct? With that assumption you can get rid of the unsure location of the rising edge.

move the println after the OCR settings

The signal at CH1 is an external signal, right?

the top signal has a rising edge of almost 5 ms .... how do you expect to synchronize that?

I haven't fully understood what you want to achieve, but you can clear TCNT2 on a falling edge of the CH1 to synchronize them

Given that only the falling edge of your input is sharp and well
defined, I suggest the following approach:

Use the input-capture feature of Timer 1 to get a timestamp on the
falling edge and trigger an interrupt.
In the ISR, start by toggling the output in order to set it low. Then
compute the period of the signal (timestamp of this falling edge minus
timestamp of the previous one) and program a compare register to
trigger a compare match event after half a period.
The compare match would automatically toggle the output pin again, by
using the “toggle on compare match” timer output mode.

The following program attempts to implement this approach. Note that it
is completely untested. Input is on pin 8 (i.e. PB0 and ICP1). Output is
on pin 9 (i.e. PB1 and OC1A). The timer is set to run at F_CPU/8 in
order to accommodate frequencies as low as about 30.1 Hz. A
different prescaler should be used if lower frequencies are needed. The
program does not rely on the Arduino core, and thus defines its own
main() instead of setup() and loop().
ISR(TIMER1_CAPT_vect)
{
    TCCR1C = _BV(FOC1A);  // force output compare -> toggle output
    static uint16_t last_capture;
    uint16_t capture = ICR1;
    uint16_t period = capture - last_capture;
    last_capture = capture;
    OCR1A = capture + period/2;  // compare match after 1/2 period

    // If output is high, toggle again.
    if (bit_is_set(PINB, PB0))
        TCCR1C = _BV(FOC1A);
}

int main()
{
    // Set OC1A = PB1 = digital 9 as output.
    DDRB = _BV(PB1);

    // Configure Timer 1.
    TCCR1A = _BV(COM1A0);  // toggle OC1A on compare match
    TCCR1B = _BV(CS11);    // clock at F_CPU/8
    TCCR1C = _BV(FOC1A);   // force output compare -> toggle output
    TIFR1  = _BV(ICF1);    // clear capture flag
    TIMSK1 = _BV(ICIE1);   // enable capture interrupt
    sei();

    for (;;) {}
}

thank u so much, this code works perfect. And now i need to transform this square wave to sine wave. I tried set PB2 to change duty cycle and use RC-filter, but when i writte DDRB = _BV(PB2) and OCR1B = ... in programme then can't even get the square wave.why happens that?

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


text:
Error reading file
What should be done to solve it?
I have edited the board.txt file and none of my codes are getting verified
it shows this error:

"Error reading file (C:\Program Files
  (x86)\Arduino\hardware\arduino\avr\boards.txt:0): Invalid line format,
  should be 'key=value' "

it is obvious that you made a mistake editing the file .... revert the file to its original content

You can either reinstall the Arduino IDE (it will replace the file), or copy the original code back in the file (if you have a copy somewhere).
See the link: https://code.google.com/archive/p/arduino/wikis/Platforms.wiki for more background in case you are interested.
(note: I cannot copy the content of the file in the answer since it is more than 30000 characters.)


text:
Spikes in CO2 and TVOC measurements with CJMCU-811 sensor
Firstly, I'm not sure if this is the right SE to ask this question. Please feel free to direct me somewhere else if needed.
I am observing large spikes in CO2 and TVOC measurements using the CJMCU-811 sensor. When plotted it looks like this:

Nothing particular is happening around the sensor at those moments of spikes, I'm not breathing on the sensor etc.
I use Arduino Uno with the following code:
/******************************************************************************
  Read CO2 and TVOCs from CJMCU-811 sensor

  Arduino connection:
  3.3V to 3.3V
  ACC to 3.3V
  GND to GND
  WAK to GND
  SDA to A4
  SCL to A5

******************************************************************************/
#include <Wire.h>

#include "SparkFunCCS811.h"
#define CCS811_ADDR 0x5B

CCS811 mySensor(CCS811_ADDR);

void setup()
{
  Serial.begin(9600);
  Serial.println("CCS811 Basic Example");

  Wire.begin();

  CCS811Core::status returnCode = mySensor.begin();
  if (returnCode != CCS811Core::SENSOR_SUCCESS)
  {
    Serial.println(".begin() returned with an error.");
    while (1);
  }
}

void loop()
{

  if (mySensor.dataAvailable())
  {

    mySensor.readAlgorithmResults();

    delay(1);

    Serial.print("CO2 ");
    Serial.print(mySensor.getCO2());

    Serial.print(", tVOC ");
    Serial.print(mySensor.getTVOC());

    Serial.println();
  }

  delay(2000);
}

Of course I can filter and not worry about them, but I'm nevertheless curious what is causing it. Any suggestions what could be the reason for that?

Two suggestions ... do you have a second sensor? If you run two sensors close to each other and the spikes coincide, then something IS happening around the sensor. Or ...  seal the sensor inside a container ... do the spikes still happen?

@Jaromanda X, good point, I have two of them so that will be easy to see.

If the "spikes" are due to some "internal" error, as per the answer, you could always take 5 or so readings in as short a time as the sensor will allow, remove any outliers then average the rest - the code for doing that isn't too difficult

I have two of those sensors in a long term setup and I know those spikes very well. I once put lots of effort in debugging and I personally gave up on the ccs811 and use a different sensor now.
Back then I have already tried what Jaromanda suggests in his comment.
Both of my sensos showed the same behaviour while the spikes on both sensors did not correlate in any form.
Also, if I remember it right, those erronous readings appeared to be at dedicated values.
I tried several pullups, which also didn't make any difference and on the oscilloscope everything looked fine.
Printing the output of the I2C related functions revealed that communication was always stable. If it was I2C related I would expect those erronous readings to be completely random anyway (which they aren't from my experience).
My final (vague) theory was that maybe there exist race conditions between the computation and the I2C interface or maybe the adc and the approximation algorithm (that's all "inside" of the sensor). I once produced such a bug myself which resulted in a similar behaviour.
At least I'm pretty sure that there is nothing you can do in your sketch to fix this problem, because for the mentioned reasons it is very unlikely related to communication problems. You might want to work-around it or look for an updated firmware.
Or (my prefered solution) choose a sensor which does a true CO2 measurement (the ccs811 only returns a pseudo, calculated CO2-equivalent approximation).
Those higher-class sensors use NDIR technique and are only a bit more expensive (still under 50$) but you'll probably have much more reliable readings, less problems and a wider measurement range (up to 0-40000ppm vs 400-8192ppm).
Ps: did you follow the guidelines concerning the "burn-in time"? Because honestly, that was a mistake I did: I simply plugged it in of curiosity to test communication and read about this step afterwards. But I don't believe it has something to do with this problem, because there are physical reasons why one should do so, but those artifacts seem to be of digital nature.

Which CO2 sensor did you end up going with?

@DaveW.Smith I personally like the SCD30 by sensirion, but there are other NDIR-CO2 sensors (this is not meant to be a product recommendstion).

There is a CCS811 library which supports querying the internal firmware version of the sensor, and flashing a new firmware (latest is 2.0.1). Older firmware versions used to have burn-in compensation which apparently caused more harm than good (instead, new firmware requires sensors to be burned-in during 48 hours), and also relied on an external sensor for temperature compensation, which is simply missing on most cheap breakout boards. Ironically many cheap boards come with CCS811 flashed with an older firmware, which periodically samples the voltage on a floating pin and uses that value to correct CO2/TVOC calculations.
Unless your board features a thermistor, consider upgrading the sensor firmware to 2.0.1. Even or boards with a thermistor (e.g. original Adafruit), new firmware might give better results.

I saw similar behavior from 3 CJMCU-811 sensors that I bought (in one order, so probably the same manufacturing lot) in mid 2019. Two gave readings with steady, spikey, but uncorrelated upward growth. The third periodically spiked into the 2000-3000 ppm zone and then popped back to ~450 ppm (in an empty room with decent airflow). A logic analyzer on the I2C lines didn't show issues (or I missed them).
I went as far as adding a line to reset the sensors every few minutes. Replacing the sensors with what I assume was a different manufacturing lot resolved the issue.
I'm using the AdaFruit ccs811 library on ESP8266s (Wemos D1 minis).
Months later: The replacements have gone haywire, occasionally giving readings in the 3000ppm range until reset, at which point they're back to the 400-600ppm range for a while until drifting higher. I recommend avoiding the ccs811.

Values dropping after a reset is something you should expect. The datasheet says "After writing to MEAS_MODE to configure the sensor in mode 1-4, run CCS811 for 20 minutes, before accurate readings are generated", so whatever you read right after a reset is garbage.

I expect the drop, but not from 3000 to 400, then drifting slowly to 800, then spiking back to 3000 and hanging out there until reset. This n a room with a window open, and the sensor placed so that it gets breeze.

Observed the same behavior on CJMCU-811, CO2 value drifting upwards until reset.


text:
ESP32: Share I2C bus among multiple freeRTOS tasks - do I have to expect synchronization issues?
I recently inherited some firmware with weird problems in regards to the duration of reading sensor values. The board is based on the ESP32 Wrover MCU and has multiple sensors connected via the I2C bus. The firmware makes use of the port of the FreeRTOS task library and uses the main loop to read two sensors as well as an extra task on the same core to read some more sensor via a DS2482 I2C to OneWire bridge. Usually I would expect the reading of the sensors to take at most one second (assuming the 'worst' case under normal conditions) via the bridge, but it takes a multitude of that, usually around 30 or more seconds for one sensor. Not only the reading but any communication over the bridge takes a very long time. One more detail: The sensors behind the bridge are connected one per channel of the bridge and the one wire channel is reset each time before a sensor is read.
My current suspicion is that using multiple tasks on the same I2C bus may screw up the timings of the communication and thus cause communication errors leading to the increased read times.
Does that suspicion sound reasonable at all or what would you suggest to investigate on the described system (knowing well, that I didn't provide too many details)?
Any ideas are welcome.
Thanks!

I've run into ports of FreeRTOS where using the I2C hardware is wrapped at quite a high level in an atomic block so it will block scheduling from occurring as you expect. That could be worth checking but it'd probably be a more widely reported issue if it was what's happening here.
I'd look at how long form reset to data being ready it is for the one-wire sensors and maybe even write a test program that doesn't use an RTOS to see how often you can get data from things beyond the bridge in the way you're doing it now. (i.e. reset the sensor and then get data)


text:
Communication between arduino nano and MCP3424 over I2c pt. 2
I'm am completing a project of mine that uses an MCP3424 i2c 18bit ADC and an arduino nano to measure temperature with an NTC thermistor but am having trouble with the arduino wire library. This is my first project using i2c so I'm not very knowledgeable about the subject but I have rigorously read the datasheet of the MCP3424 that can be found at (http://ww1.microchip.com/downloads/en/devicedoc/22088b.pdf) and tried many different ways to get it working. Also I'm new to posting on this stackexchange so pardon me if my syntax and what not is not right(I'm doing my best). Here is the code I have so far that is on my arduino.
#include<Wire.h>
//#include<LiquidCrystal.h>
//LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

#define MCP 0x6E //Device will output conversion data (7 bits, device address. 1 bit, Read/Write mode)
#define CH1 0x8c //PGA = 1, SPS = 3.75, One-Shot mode, channel 1, initiate new conversion.
#define CH2 0xac //channel 2
#define CH3 0xcc //channel 3
#define CH4 0xec //channel 4

void setup() {
  Serial.begin(9600);//Initiate Connection to computer
  //lcd.begin(16, 2); not used yet
  Wire.begin();//Initiate Wire library
}

void loop() {
  // Read data from
  int pins[] = {CH1, CH2, CH3, CH4};
  long results[] = {0, 0, 0, 0};
  for (int i = 0; i < 4 ; i++) {
    results[i] = ReadMCP(pins[i]);
    Serial.print(i+1);
    Serial.print(": ");
    Serial.print(ReadMCP(pins[i]));
    Serial.print(" ");
    delay(500);
  }
  Serial.print("\n");

}
long ReadMCP(int channel){
  //conversion takes the three bytes and converts to number between 0 and 131071
  int x, y, z;
  long result = 0;

  Wire.beginTransmission(MCP);//begin transmission with ADC in Write mode
  Wire.write(channel);//configure the ADC with settings found in either CH1, 2, 3 or 4
  Wire.endTransmission();
  //delay(500);
  Wire.requestFrom(MCP, 3);//request 6 Bytes of information from MCP3424
  x = Wire.read();//read bytes
  y = Wire.read();
  z = Wire.read();

  if (x>1) {
    if (x%2){
      result += (1 * 65536L);//x * 65536 = x * 2^16
      result += (y * 256L);//y * 256 = y * 2^8
      result += z;
      result = -131072 + result;
    }else{
      result += (y * 256L);//y * 256 = y * 2^8
      result += z;
      result = -131072 + result;
    }

  } else {
    result += (x * 65536L);//x * 65536 = x * 2^16
    result += (y * 256L);//y * 256 = y * 2^8
    result += z;
  }
  return result;
}

My program reads the measurements from each of the 4 channels of the ADC and prints them in the serial monitor.
The issue I am having is that when this code is run without the "delay(500);" function in the ReadMCP() function my measurements from each channel of the MCP3424 are in the wrong place. It prints the measurement from channel 1 as channel 2, the measurement from channel 4 as channel 1 and etc. However, with the delay between endTransmission() and requestFrom() the values are in the correct place. I have looked all over the datasheet and experimented a lot with the issue but cannot see what is causing it. Does anyone know why?
For reference when I have something to measure attached to channel 2 the output without the delay is
1: 131071 2: 131071 3: 66891 4: 131071
and with the delay is
1: 131071 2: 66843 3: 131071 4: 131071

You have to wait for the conversion to be complete. Check the RDY bit as detailed in the datasheet.

Don't leave the unused channels floating...you may read random values caused by noise or, worse, get crosstalk from adjacent channels. Tie unused channels to ground or some known reference voltage.

Why do you read MCP a second time Serial.print(ReadMCP(pins[i])); instead of using the the result you received 3 lines above (results[i] = ReadMCP(pins[i]);)?


text:
RS232 to ttl communication of arduino
I have an rs232 to TTL converter and I want to read something in the Arduino serial monitor by using the converter instead of using Arduino serial cable. I have connected the correct wiring in my opinion such as tx, Rx, Vcc and GND of the converter to Arduino pin 0 (Rx), pin 1 (Tx), 3.3 V and GND. But when I write something in the serial monitor of Arduino, I am getting nothing. But when I use only the arduino serial cable then I receive what I am writing in the serial monitor. Kindly can anyone tell me what am i doing wrong?

did you wire RX to TX?

The Uno works on 5V. Is your TTL converter 5V tolerant? Or why did you wire 3.3V?

Have you disconnected the Arduino's built-in serial connection to the USB interface?


text:
Program for counting days
I need a program to count days, from day 1 to day 21 for my project.
I'm making an artificial incubator and I need to show the days on an LCD.

Don't shout, use punctuation to start with. What part you need help with? Counting days in what sense? (with a for loop, or using a real time clock?) Be more precise in your requirements. What do you mean with 'like so' ?

google: "DS3231 Arduino". DS3231 is an Real Time Clock module which allows you to keep track of time and date.

If it doesn't need to be very accurate, you can use millis()

For what it's worth, one day is just 86400000 milliseconds.

You can do that easily using Real Time Clock IC. ds1307/ds3231 ic will do the job. Adafruit has Arduino library for that. easy to interface.
I don't supprt using millis() function. you will lose your time if the system power downs or mcu resets. Using RTC chip is safe option as it has backup battery for time keeping.


text:
double to char* conversion. Weird results from dtostrf
Here’s the code:
void setup()
{
    Serial.begin(9600);
    delay(300);

    double lat = 1111.11;
    double lon = 4444.44;

    const byte len{10};

    char sLat[len];
    char sLon[len];

    dtostrf(lat, len, 2, sLat);
    Serial.println(sLat);

    Serial.println("---");

    dtostrf(lon, len, 2, sLon);
    Serial.println(sLon);
    Serial.println(sLat); // <-- prints nothing!

    Serial.println("---");

    dtostrf(lat, len, 2, sLat);
    Serial.println(sLat);
    Serial.println(sLon); // <-- prints nothing!
}

void loop()
{
}

Here’s the output:
   1111.11
---
   4444.44

---
   1111.11
   4444.44   1111.11

As you see. Every next call for dtostrf ruins the previous results, in a weird way.
What’s the problem?

If len is the text array size, you need space there for the terminating '\0'.
So the second paramater to dtostrf has to be smaller than len.

Yeah, of course, your're right! Thanks a lot! I fixed declaration: char sLat[len+1]


text:
Floating power supply for Arduino - Is it still connected to the USB ground?
I am trying to power my Arduino Mega 2560 from a benchtop power supply. I plan to essentially feed in a 9V supply directly on the Vin pin and connect the GND pin to the floating ground pin on the power supply. I noticed on the schematic that the UGND is connected to GND through this jumper. On the Arduino that I have these two pins are tied together. Does this mean that even with the external power supply the Arduino will be connected to the UGND, and in effect the protective earth?
What is the best way to float the Arduino? Would it be ok to remove the jumper connection between UGND and GND? Or should I try something like a linear USB isolator like this?

Does this mean that even with the external power supply the Arduino will be connected to the UGND, and in effect the protective earth?

Yes.

Would it be ok to remove the jumper connection between UGND and GND?

No. I don't know quite why they provided that jumper. I can see no scenario in the datasheet where it suggests the two can be separate.

Or should I try something like a linear USB isolator like this?

If you want it to float then you need galvanic isolation on all USB pins. The device you link to will do that for you. There are others as well.
Personally in these situations I prefer to use a wireless communication system so there is no worry about grounds and isolation - it's naturally isolated.

What do you mean all USB pins? The data pins are differential with respect to the UGND right? Unfortunately I need the data to be transmitted through a wired link :|

By all pins I mean all pins. With galvanic isolation the ground is isolated. What is ground at one end is not ground at the other. Separating the grounds but not separating the rest of the signals means that only at the computer's end do the signals make any sense.


text:
real-time reading of a quadrature encoder at full resolution with only one interrupt on ATmega328
I want to read a quadrature rotary encoders at full resolution with only one interrupt on Arduino Nano (ATmega328). So I found out that we can use XOR to reach a full resolution:

Where pin 3 is interruptable but 4 and 5 are not.
Our requirements are:

Full resolution: for example, the solution offered in this answer works at a half-resolution only, not detecting all the edges.
Real-time: being as fast as possible up to the level that this hardware allows and safe in terms of not missing any of the signal edges.
using only one interrupt. We need the other one for other purposes.

So far, I have developed two different codes, one aiming for safety and the other for performance:
Preamble:
#include "digitalWriteFast.h"

#define pinT 3 // trigger pin comming from XOR

#define pinA 4 // channel A
#define pinB 5 // channel B

volatile long counter = 0;
long counter_ = counter;

where the digitalWriteFast library can be downloaded from here.
Performant:
volatile short int increment = 0;
volatile bool tmpA;
volatile bool tmpB;
volatile bool lastA;

ISR(trigger) {
  tmpA = digitalReadFast(pinA);
  tmpB = digitalReadFast(pinB);
  counter += (1 - 2 * tmpA) * (1 - 2 * tmpB) * (1 - 2 * (lastA != tmpA));
  lastA = tmpA;
}

void setup() {
  pinMode(pinA, INPUT_PULLUP);
  pinMode(pinB, INPUT_PULLUP);
  pinMode(pinT, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(pinT), trigger, CHANGE);
  lastA = digitalReadFast(pinA);
  Serial.begin(9600);
}

void loop() {
  if (counter != counter_) {
    Serial.println(counter);
    counter_ = counter;
  }
}

Safe:
volatile unsigned long error = 0;
unsigned long error_ = 0;

volatile bool inputA;
volatile bool inputB;

volatile short state; // 100 110 101 111
volatile short state_;

void detectState() {
  inputA = digitalReadFast(pinA);
  inputB = digitalReadFast(pinB);

  if (inputA) {
    if (inputB) {
      state = 111;
    } else {
      state = 110;
    }
  } else {
    if (inputB) {
      state = 101;
    } else {
      state = 100;
    }
  }
}

ISR(trigger) {

  detectState();

  if (state_ != state) {
    switch (state_) {
      case 100:
        if (state == 110) {
          counter++;
        } else if (state == 101) {
          counter--;
        } else {
          error++;
        }
        break;
      case 110:
        if (state == 100) {
          counter--;
        } else if (state == 111) {
          counter++;
        } else {
          error++;
        }
        break;
      case 101:
        if (state == 100) {
          counter++;
        } else if (state == 111) {
          counter--;
        } else {
          error++;
        }
        break;
      case 111:
        if (state == 110) {
          counter--;
        } else if (state == 101) {
          counter++;
        } else {
          error++;
        }
        break;
      default:
        error++;
        break;
    }

    state_ = state;
  } else {
    error++;
  }
}

void setup() {
  pinMode(pinT, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(pinT), trigger, CHANGE);

  pinMode(pinA, INPUT_PULLUP);
  pinMode(pinB, INPUT_PULLUP);

  detectState();
  state_ = state;

  Serial.begin(9600);
}

void loop() {
  if (counter != counter_) {
    Serial.print("counter: ");
    Serial.println(counter);
    counter_ = counter;
  }

  if (error != error_) {
    Serial.print(error);
    Serial.println(" errors");
    error_ = error;
  }
}

Now my questions are:

Is there any way to improve the speed/safety of the performant/safe code? Any way to improve this code is appreciated.
Is it possible to have maximum speed and safety together or some trade-off in between?
What is the maximum frequency we can get out of this configuration?

Thanks for your help in advance.

Note that, instead of a XOR gate, you could use a single pin change interrupt on both channels.

@EdgarBonet Do you mean connecting two channels to two interrupts? that we can't do. The Arduino Uno/Nano has only two interrupts and we need one for other things. Is that what you meant?

No, I mean connecting the two channels to a single pin change interrupt. The Arduino has three pin change interrupts in addition to the two external interrupts.

I'm not sure what "pin change interrupts" is, but if you connect two channels to a single interruptable pin (i.e, 3 or 4)  then it works like an AND.

No, it doesn't. Do a web search for “Arduino pin change interrupt”, or “AVR pin change interrupt”.

@EdgarBonet OK. Reading this page, I don't think using pin/port change interrupts are a better solution. Unless I haven't understood your point and you may be kind to elaborate.

The MCU has pin change interrupts so that you don't need to add a XOR gate and use one of the external interrupt pins. You don't need a library for using them, and you probably don't want the overhead of a library anyway. Read Arduino Pin Change Interrupts.

@EdgarBonet please consider that the rest of the pins are not free. there are reading and writing other stuff. So if I use on the 3 available blocks of PinChangeInterrupts  (0-7, 8-13, A0-A5). I receive lots of unnecessary interrupts. The XOR helps to read both channels in "real-time" with just one interrupt pin and one normal one. See this image.

No, you don't receive unnecessary interrupts if you don't activate PCINT on the other pins.

@EdgarBonet what is the correct syntax for reading pins 4 and 5 (which are not interruptable) using the pin/port change interrupt? what binary/hexadecimal values should be assigned to the PCICR and PCMSK0/PCMSK1/PCMSK2?

This is just a partial, rushed answer.
You should be able to get a significant speed-up if you define your own
ISR for handling the interrupt, as in:
ISR(INT1_vect) { ... }

The Arduino way of using interrupts is instead
void trigger() { ...}

void setup() {
    attachInterrupt(int_number, trigger, CHANGE);
    ...
}

but this is slow, as it involves the ISR provided by the Arduino core,
which has to locate and call your interrupt handler. The way you wrote
the handler is wrong: either you define a regular function, without the
ISR macro, and go the Arduino way, or you go the plain AVR path and
define the ISR yourself, which should be named INTERRUPT_NAME_vect, in
which case you don't use attachInterrupt(). The way you did it is
probably the slowest you can get, as the compiler will needlessly add an
ISR-type prologue and epilogue to your handler.
As for the maximum frequency, that's hard to assess without testing, but
you may get some idea by reading this answer on interrupt
latency.

Edit: As I stated in my first comment to the question, a pin change
interrupt can be used instead of an external logic gate. Here is how to
do it.
First, one should look at the Arduino Uno pinout and see that:

digital 4 = PD4 = PCINT20
digital 5 = PD5 = PCINT21

Both pins are tied to the pin change interrupt request 2 (PCINT2_vect).
This interrupt can be configured in setup() as follows:
PCMSK2 = _BV(PCINT20)   // enable interrupt on pin PCINT20 = PD4
       | _BV(PCINT21);  // enable interrupt on pin PCINT21 = PD5
PCIFR  = _BV(PCIF2);    // clear interrupt flag
PCICR  = _BV(PCIE2);    // enable pin change interrupt request 2

Now, the interrupt will fire on every change of the logic levels of
inputs 4 and 5.
Then, in the ISR, the whole port D can be read in a single cycle by
just evaluating the corresponding pin input register, i.e. PIND. With
some shifting and masking, one can get a phase between 0 and 3
(the count is in Gray code: 0, 1, 3, 2, 0...). From the previous and the
current phase, one can compute the change that needs to be applied to
the counter:
// Handle pin change interrupt request 2.
ISR(PCINT2_vect) {
    static uint8_t previous_phase;
    uint8_t phase = (PIND >> 4) & 0x03;  // read input pins
    counter += encoder_delta(previous_phase, phase);
    previous_phase = phase;
}

The implementation of encoder_delta() is left as an exercise to the
reader. ;-)

Thanks. I will go through the new edits and will bother you if I had further questions.


text:
Specific ports on Teensy 3.6 not reading correct bit resolution using ADC library?
I have a basic circuit, where I'm reading analog values from 14 infrared receivers.
I set the bit resolution to 16 but specific ports are returning 10 bit values (from 0 - 1024) instead of 16 bit values (from 0 - 65536).
I can confirm this is not a problem with my circuitry because when I've tested reading each individual sensor with a port that "works" and the correct range is returned every time.

Here is my code:
#include <ADC.h>

ADC *adc = new ADC();
const int* RECIEVERS = (int[14])
{
    A15, A16, A17, A19, A20, A21, A22, A1, A2, A3, A6, A7, A8, A9
};

void setup() {
    Serial.begin(4608000);
    adc->setAveraging(16); // set number of averages
    adc->setResolution(16); // set bits of resolution
    adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS);
    adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED);
    for (int i = 0; i < 14; i++) pinMode(RECIEVERS[i], INPUT);
}

void loop() {
    for (int i = 0; i < 14; i++) {
        Serial.print(adc->analogRead(RECIEVERS[i]));
        Serial.print(" | ");
        delay(1);
    }
    Serial.println("");
}

Is there a problem with my code or is my Teensy damaged?

The Kinesis 66 (the chip on the Teensy 3.6) has two ADC modules. Each one talks to different pins.
By default the configuration functions in that library configure ADC0, so unless you tell it otherwise, you will only be configuring half the ADC pins.
You should call each of the configuration functions twice, once for ADC0 and once for ADC1:
adc->setAveraging(16, 0); // set number of averages
adc->setResolution(16, 0); // set bits of resolution
adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS, 0);
adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED, 0);

adc->setAveraging(16, 1); // set number of averages
adc->setResolution(16, 1); // set bits of resolution
adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS, 1);
adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED, 1);

Exactly it. Thanks so much.

In the new version of the Library that must be adc->adc0->xy and adc->adc1->xy


text:
Program Arduino then Remove Atmega?
Can I program an Arduino and then remove the micro-controller from it and use it on a breadboard without reprogramming the micro-controller again?
My steps would be:

create my Arduino code.
I upload the compiled code to the board.
I remove the Ic and use it alone without the whole board.

Will the code be preserved on the microcontroller?

Yes. The programming of the arduino microcontroller sets the values inside the FLASH. This is non volatile memory and as such won't be erased by taking out the IC.
Please note that this is assuming a DIP package IC as these can be removed without force, heat and stress. A TQFP, and SMT packages like that, IC might get damaged by moving them in such a way. This doesn't mean it has to be erased, it is still non volatile storage, but the moving process is much more dangerous for the chip.
I would recommend connecting the whole arduino or if you really need the whole chip: designing your own board/circuit which allows you to program the chip without moving it around as this is really tedious and not worth the effort. Also moving the chip around is a ESD hazard.
Also please note that you'll need to add a clock source for the chip to work (most of the time). Or you'll need to enable an internal PLL. It will in any case require more effort on your part to make sure that the MCU can work. Therefore using the whole arduino board is preferable.

It's not a PLL, it's an RC oscillator.

Yes you can do it (as said by Tarick).
Note about clock:
Be sure to program it correctly:

Do not add a bootloader if you don't need one
Do not use an external oscillator if you don't have one on your new board! This is important, since if you remove it you will not be able to start or programming it again!

So, before you remove the IC, set this on your Arduino (I assume it is an ATMega328):

8MHz internal (leave external only if you have an oscillator in the new board!)
Bootloader: no

You will see that you do not have this options if you select a normal Arduino, since it already has an oscillator.
So you should use the board manager and add this:
https://github.com/MCUdude/MiniCore

As code is stored in the flash memory, your code won't erase until some unexpected happens. But the question might comes in whether your code will work properly or not when you remove microcontroller from arduino board and connect with breadboard.
As you are planning to remove the microcontroller, I am guessing you are using Arduino Uno atmega328 DIP package.
You need to do two things for the proper function of the microcontroller in the breadboard. There are other solutions exist. I always prefer this one as easy.

connect 16MHz crystal with 22p(two) capacitor with the corresponding crystal pin(pin 9 &10). The crystal circuit is straightforward. Searching google might help.
Pull the Reset Pin with VCC using a 10k resistor.

Don't forget 0.1uF caps on the VCC and AVCC pins to Gnd. AVCC must also have power on it, either direct to the VCC pin, or thru a filter (small inductor)


text:
Using a class inside of another class
I have a seemingly simple problem that seems to be popular, but after searching several forums I still have not found the answer: How do you use a class inside of another class?
I have simplified my problem:
class A {
  const int pin;
  public:
  A(int attachPin) : pin(attachPin) {
  }

  void setup() {
    pinMode(pin, INPUT_PULLUP);
  }
};

class B {
  A myA;
  public:
  B(int a_attach) : myA(a_attach) {
  }

  void setup() {
    myA.setup();
  }
};

B test;

void setup() {
   test.setup();
}

void loop() {
}

I think, the problem in that line B test. You are define a variable, but you forget to define default constructor ( B() ). You try to setup an A class with unknown pin! To avoid this you may define test variable in that way B test(2); or in that way const int test_pin = 2; B test(test_pin);. Also to avoid this problem you may to set default value to the constructor sucha as  B(int attach=2) : myA(attach) {} and define test variable, as you do in your code B test;.


text:
Reading data from the MCP3002
I am using a MCP3002 to convert an analog signal to digital data. It works fine actually, sends good data. However; After a while, when the power is turned off and on again a few times, it only returns zeros. If I Power it on the next day, it works for a while again.
I am just beginning with SPI, so I do not know 'all' the basics. Is there something I should reset when powering on or something? (Clock, Timing, etc.)
This is the code I am using (pretty straightforward):
#include <SPI.h>
SPISettings spiSettings(7280000, MSBFIRST, SPI_MODE0);
const int SPI_CS = 2;

void setup() {
    pinMode (SPI_CS, OUTPUT);
    SPI.begin();
    SPI.setBitOrder(MSBFIRST);
    SPI.setFrequency(7280000);
}

void loop() {
    SPI.beginTransaction(spiSettings);
    digitalWrite (SPI_CS, LOW);

    uint8_t cmd = 0b11000000;
    byte msb, lsb;
    word assembled;

    msb = SPI.transfer(cmd);
    lsb = SPI.transfer(0);

    assembled = word(msb, lsb);
    Serial.println(assembled);

    digitalWrite (SPI_CS, HIGH);
    SPI.endTransaction();
}

Is there something wrong, or should something be added to this?

Try using a small delay between the transactions. An ADC need a bit of time to convert another value. The datasheet states, that is will clock out zeros indefinitely, when you continue to read (read chapter 5.1 in the datasheet. Last sentence in the left column). So I guess the CS pin is not long enough inactive

Ah, I will try that and read the data sheets!
But how does that explain that it works initially?

Maybe some weird racing condition, maybe something regarding how the sensor senses the CS pin

Thank you, I will try it a.s.a.p and come back here to add the results. This way others could use this as well.

Are you using a properly manufactured breakout board or just the bare chip on a breadboard?

@Majenko Properly manufactured, why?

Just wondering if you'd missed off the decoupling capacitors, but probably not if it's a BoB.

@Majenko, ah well its properly manufactured. But I designed the boards myselve (With capacitators) but maybe I am missing one. I will test chrisl s solution first. :-)

It is a good practice to set to Arduinos own Slave Select Pin (for UNO it's PIN 10) as an output. Because a signal on that pin could switch the Arduino to SPI Slave Mode. I do not believe it can fix your setting - but perhaps ... And you asked whether you missed something: pinMode (10, OUTPUT);

@chrisl It worked like a charm, Thanx! Can you post it as an answer, so I can accept it and people do not have to read the comments only?
The datasheet says:
'After completing the data transfer, if further clocks are applied with CS low, the A/D Converter will output zeros indefinitely. See
Figure 5-2 for details on obtaining LSB first data.'

I thin the following is happening:
The MCP transmits 1 measurement per SPI transaction, which consists of activating chip select, reading data and deactivating chip select. To distinguish between different transactions, the time between deactivation and reactivation of chip select need to have a bit delay between them. Currently your code runs really fast, a few microseconds between the transactions at max.
This may also be connected to the MCP needing time to measure the analog signal.
I think there is some kind of race condition, so that the MCP does not have a new value to transmit, either because the MCP hasn't finished measurement yet, or because the delay between the transactions were just a bit too short, maybe a combination of both.
When the MCP is once in this situation, it will only send zeros at that point  (read chapter 5.1 in the datasheet. Last sentence in the left column).
You need to give the MCP more time between the transactions. I suggest using a small delay at the end of the loop() function. You can experiment with the actual value, I would guess, that you can go down to the microseconds range.


text:
RS485 communication problem
I'm trying to achieve RS485 communication between Arduino Mega and Arduino UNO as specified in following link:
https://www.engineersgarage.com/arduino/rs485-communication-between-arduino-mega-and-arduino-pro-mini
But now my problem is The master i.e. Arduino Mega doesn't print anything on Serial Monitor.
Please help me out to solve this issue, trying from week still no success.

Sir Peter Paul Kiefer,
Im attaching my circuit setup

Master Code/Mega code
void setup()
{
  //Using Serial1 Port
  Serial1.begin(9600);
  Serial.begin(9600);

  //DE/RE Controling pin of RS-485
  pinMode(8, OUTPUT);
}

void loop()
{
  char getdata='m';

  //DE/RE=HIGH Transmit Enabled M1
  digitalWrite(8,HIGH);

  //Write '9' and Fetch Data From Pro Mini
  Serial1.print('9');

  //DE/RE=LOW Receive Enabled M1
  digitalWrite(8,LOW);
  delay(1000);

  //If Serial Data is available
  if(Serial1.available())
  {
    while( Serial1.available() && getdata!='d' )
    {
      getdata=Serial1.read();
      Serial.print(getdata);
    }

    Serial.println("");
  }
}

Slave code
void setup()
{
  //Serial1.begin(9600);//Uncomment for Arduino Lenardo
  Serial.begin(9600);
  //while(!Serial1);//Uncomment for Arduino Lenardo

  //Led Connected
  pinMode(13, OUTPUT);

  //DE/RE Controling pin of RS-485
  pinMode(8, OUTPUT);
}

void loop()
{
  // put your main code here, to run repeatedly:
  char getdata='c';

  //Led OFF
  digitalWrite(13,LOW);
  //DE/RE=LOW Receive Enabled
  digitalWrite(8,LOW);

  if(Serial.available())
  {
    getdata=Serial.read();
  }

  if(getdata=='9')
  {
     //DE/RE=HIGH Transmit Enabled
     digitalWrite(8,HIGH);

     Serial.print("AcruxTek");
     Serial.print("Isld");
  }

  delay(2000);
  //Led ON
  digitalWrite(13,HIGH);
  delay(2000);
}

I connected gnd of RS485 converter to arduino gnd and also i did common gnd between circuits but still no output. I used same code nothing changed.. except one thing the example uses arduino pro mini but i used arduino uno as slave

Sorry. The link doesn't work. And you did not specify your problem in any way. We can not help you with knowing your setup. Just showing like others have done, gives us no hint of what you have done. So how can we help?   I downvoted you, because it seems as a commercial for an diy page and of cause, I may be wrong. Edit your question, give us information about your own setup, perhaps a schematic (even hand drawn) and your code you've written so far. Then I will remove my downvote and probably I can even help you.

Oh, I've seen you have included the closing braket in the url. If I remove it the link works. I'll  draw my down vote back. But you should give us an overview of your own project, we can not find out out what's your problem if we study a working project from someone other.

Im trying to read energy meter holding register data through RS485. As given in my previous link im using RS485 to TTL converter for that purpose. I'm not success in getting data from energy meter. so i thought of trying basic example of RS485 commuication between ARduino Mega and Arduino Uno using this converter. AS I said serial monitor doesn't print anything

Yes I understood that, you have problems with connecting two Arduinos over a RS485 link using the mentioned Interfaces/adapters. But how did you do that? Please give a description of what you did. The project from the link should work, so what did you different. What about your program code. Have you a typo in it. How did you connect the parts?  I do not know because I can not have a look into it. I would really like to help you, but I can't without information. HINT: It would be better to edit your question with the new information.

If you doubt that the linked code is correct. I've tried it last evening and it worked. But you might had interpreted the schematics wrong. These are not very clear and definitely not made for beginners. That's why I asked you to show me your setup. Perhaps you would better succeed with another project, that's clearly explained. https://www.instructables.com/id/RS485-Serial-Communication-Between-Arduino-Mega-an . But i have no experience with this Visuino program. I hope it will generate C/C++ Code so you can see it. Or don't you need the code?

Please put additional information in your question, you can [edit] it! Don't write an answer, I just found it by accident. And as PeterPaulKiefer said, we need to see your source code or a note that you use the linked code unchanged. Did you connect GND between the Arduinos and the RS485 modules?

I connected gnd of RS485 converter to arduino gnd and also i did common gnd between circuits but still no output. I used same code nothing changed.. except one thing the example uses arduino pro mini but i used arduino uno as slave

I think there might be two issues in the engineering garage code. delay() function parameter in both codes is not matched. And another thing might cause problem is"Arduino Serial monitor hardware serial is already connected with another usb-serial converter ic which you are using for code uploading, so you cannot use this serial port for rs-485. So using software serial of Arduino pro-mini is a safe option. Finally you have to connect the software Serial pins with rs-485 converter. I have modified the code a little bit and attached the code herewith.
Arduino Mega code
void setup()
{
  Serial1.begin(9600);//Using Serial1 Port
  Serial.begin(9600);
  pinMode(8, OUTPUT);//DE/RE Controling pin of RS-485
}

void loop()
{
  digitalWrite(8,HIGH);//DE/RE=HIGH Transmit Enabled M1
  Serial1.print('9');//Write '9' and Fetch Data From Pro Mini

  int timeOut = 0;
  digitalWrite(8,LOW);//DE/RE=LOW Receive Enable
  while(!Serial1.available() && timeOut < 5000)
  {
    delay(1);
    timeOut++; // wait 5s to get response from slave
  }
  String response = Serial1.readString();
  Serial.println(response);
}

Arduino Pro-Mini Code
#include <SoftwareSerial.h>
#define RS485_RX 2
#define RS485_TX 3
SoftwareSerial mySerial(RS485_RX,RS485_TX);//Creating object

void setup()
{
  //Serial1.begin(9600);//Uncomment for Arduino Lenardo
  Serial.begin(9600);
  mySerial.begin(9600);
  //while(!Serial1);//Uncomment for Arduino Lenardo

  pinMode(13, OUTPUT);//Led Connected
  pinMode(8, OUTPUT);//DE/RE Controling pin of RS-485
}

void loop()
{
  digitalWrite(13,LOW);//Led OFF
  digitalWrite(8,LOW);//DE/RE=LOW Receive Enable

  while(!mySerial.available())
  {
    delay(1);
  }

  String res = mySerial.readString();
  if (res == "9")
  {
     digitalWrite(8,HIGH);//DE/RE=HIGH Transmit Enabled
     mySerial.print("AcruxTek");
     mySerial.print("Isld");
  }
  digitalWrite(13,HIGH);//Led OFF
}

Thanks for your reply sir, Ill definitely try your suggestions and let you know the results

Sir, I tried your code still there is not output coming in master i.e. mega serial monitor

It's not really clear from the picture, but it seems that, the two adapter have no common ground. i.e you have to connect the ground (GND) pin of one the adapter to the GND pin of the other one. But do not remove the connection between the GND pins and the arduino GND pins.
I also assume that the mega-adapter is powered with 3.3 V and the UNO-adapter is powered with 5 V (or 3.3V I can not see). This might cause a problem, because the MAX485 chip needs a 5V power supply.
EDIT:
Sorry by a second view a saw, the mega delivers 5 V. So possibly you only have to connect the GNDs of the adapters to solve your problem.
EDIT 2:
I guess the little yellow wire in front of of both adapters connects the DE pins of them. The DE pin of each adapter is also connected to the respective Arduino PIN 8. So it doesn't matter which Arduino is requesting to switch the adapter into the send mode. Both adapters are sending. As far as I know, the adapter only work in Half Duplex you mus define the direction of the data flow. If one adapter is in send mode the other must be in receive mode.
It might also be possible that the DE and RE PIN of each adapter is connected.
But this seams strange to me also. With that I would say you setup up one adapter in both receive and send mode and the other in none of them.
EDIT 3:
By looking into the MAX485 Spec. I saw that RE is LOW active but labeled as RE (which I understood as HIGH active), so sorry the last paragraph of my EDIT 2 is nonsense. So, perhaps it's a matter of timing or (more likely) there is still something wrong with the wiring.
EDIT 4:
In the picture I see that you connect the hardware tx and rx pins to the adapter. But Software Serial needs its own pins. Pin0 and Pin1 are connected with the PC Serial Terminal over the built in USB to Serial adapter of the arduino UNO. That's the reason why you need the software serial solution on an arduino. You need a second serial interface and UNO has only one of them which is already used for the connection to the PC (Programming and serial monitor).
In the code I don't see the initialization of the software serial port.
This is also necessary:
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

// set up a new serial object
SoftwareSerial mySerial (rxPin, txPin);

@priya I rejected your edits of my Answer because I think, it might confuse the readers. I appended the text to this comment: "As per your suggestion I connected RE pin to pin 9 of Arduino for both MEGA and UNO boards and set the logic level. But still no output. Can you suggest any test that can be done to ensure that RS485 converters are in working condition or damaged?"

I formatted you code, so I can read it better. Parts of the Code are missing there should be a line SoftwareSerial Serial1( rxPin, txPin ); Oh wait... In the picture I see that you connect the hardware tx and rx pins to the adapter. But Software Serial needs its own pins. The other are connected with the PC Serial Terminal. I'll edit my answer.

Sir I tried the code provided by Shuvangkar Shuvo which uses software serial still no success

Did you reconnect the DI and RO pins of the adapter to Pin2 and Pin3 of the UNO? In the picture you used the wrong pins (pin0 and pin1) of the UNO.

Yes Sir, I connected DI pin to pin 3 and RO pin to pin 2 of arduino UNO

No, that should be DI(TX) <-> Pin2 and RO(RX) <-> Pin3 for the arduino UNO. And  DI(TX) <-> TX1 (Pin19?) and   RO(RX) <-> RX1 (Pin18?)  for the mega.

Then I have to swap the connections of TX and RX of Uno board. But for Mega board a little confusion in connection. I have mega board which is made in China.If we look at TX1 and RX1 pins there is a difference, which is correct??

Im attaching link of both the boards                                                                           Mega (Italy Board) - https://www.elexp.com/media/catalog/product/cache/75eed2686e01eb22cb4050b2f40ddf97/0/1/01ARD000067.jpg                                                                        Mega (China Board)- http://1.bp.blogspot.com/-VsoefcyjVzI/VW7oXCHCnaI/AAAAAAAAACM/R-0kdrViX_E/s1600/Clone%2BArduino%2BMega%2B2560.JPG. Please let me now whether my board is good.  Please see there is a difference in pin no for Serial1 port

That's funny. They flipped the Pins . But I hope they only labeled it false, I don't know. If the labels are correct then the program will have a problem. The predefined HardwareSerials e.g. Serial1 on the Mega are bound to pin 18 and 19 for TX and RX and not 19 and 18 for TX and RX.I have no chinese clone and zero exprerience with them. But if you want to be sure, you can use the second port and Serial2 in your program. The pins of port 2 seams to be the same.

I interchanged Arduino Uno RX and TX pins as per above suggestions and also Im using Serial2 in Arduino Mega.. The RX LED on MEGA blinks but Serial monitor doesn't print anything.

@priya Look how I edited my answer each time I had something new. Please, if you have changed something on your setup, append also a new paragraph to your question. Add the new code and a picture of your new setup. I can not say what's wrong if I can not see what you have done. And the picture should show the scene from above, so I can really see the wiring and  the labels of the pins.

Sir, still im not succeeded in my RS485 testing. Please help me out


text:
Nano 33 IoT rescue from the dead: No USB. No upload mode
First of all: my board used to work fine.
Now my Nano 33 IoT turns ON (green light) when connected to USB on Mac but:

doesn't enter in upload mode after pressing twice on board button.
doesn't shows up in any serial port: nor /dev/cu.usbmodem14*01, neither /dev/tty.usbmodem14*01

For reasons too long to explain, I want to connect via ANY pins to the SAMD21 and force the burning of a new bootloader.
Is that possible in any way? Any idea is welcome!
Tx

Use the SWD interface and a programmer to burn the bootloader to SAMD.

source of the picture https://medium.com/@manuel.bl/arduino-in-circuit-debugging-with-platformio-9f699da57ddc
I had luck with Adafruit DAP library using an Arduino M0 to burn a bootloader to MKR Zero.


text:
Connect arduino nano and ESP32 with I2C on the GPIO7 and GPIO8?
I made a mistake connecting SD0 (GPIO7) and SD1 (GPIO8) with the SDA and SCL on my arduino nano. I got confused with GPIO21 and pin21 and GPIO22 and pin 22!
Since I made a PCB prototype, I would avoid to add some wires and cut the traces, so I would ask if I could use these pins (GPIO7 and GPIO8) as SDA and SCL.
If the answer is affirmative, using Arduino library how could I assign them?
Wire.begin (7,8)?
Another question, I would use a dedicate 2x4.7K pull up resistors. On the arduino side I wrote:
digitalWrite(SDA, 0);
digitalWrite(SCL, 0);
It is correct to do the same thing on the ESP32 side?
Update November 01:
After the question from Majenco I think I need more help for the I2c setup.
I designed the PCB having in mind that the esp32 was 5V tolerant, so at the moment I pull-up the SDA, SCL from the 5V that I input in the esp power pin. Note that this 5V doesn't come from the Nano due to the high current required by the esp. I take my 12V power supply input and regulate it to 5V with a 7805, only dedicated to the esp (I know, a lot of dissipation! In the next PCB version I have to change the things, having in mind that I need both 12V and 5V in my circuit).
Now, I read that the esp32 is not 5V tolerant. In order to avoid level shifter can I pull up the SDA and SCL from the 3.3V line (the arduino 3.3V or esp32 one?)?
I would use the esp32 as master.
Thanks.

As I know, the Wire library is a hardware I2C library, not software. Hardware I2C is bound to special pins. And why would you try to pull both lines to low via digitalWrite?

I would pull low the two lines in order to eliminate the internal arduino pull up resistors from the circuit, using the esternal one. I don't know if I can do same  on the esp32 side.

If you are using hardware I2C on the Nano, the lines would do nothing, since the pins are controlled by the I2C hardware instead of the digital output hardware. If you are using software I2C, The pins will be controlled by the library. Doing the digitalWrite will disable the internal pullups for the moment, but as soon as the library takes action, the pins will be set to the libraries default state (most likely with enabled pullup, but not garanteed). So I think these lines do not serve a function on the Arduino.

Since I made a PCB prototype, I would avoid to add some wires and cut the traces, so I would ask if I could use these pins (GPIO7 and GPIO8) as SDA and SCL.

No, you can't. Those pins are used by the internal flash chip. If you connect things to them you will end up not being able to read the flash and thus won't be able to run any code.  In other words, the chip will not boot. So you will have to bite the bullet and cut traces and add bodge wires.

Wire.begin (7,8)?

Yes. That will control the bus matrix to route the I2C through different pins - but of course you can't use those pins, as noted above.

On the arduino side I wrote:
digitalWrite(SDA, 0); digitalWrite(SCL, 0);
It is correct to do the same thing on the ESP32 side?

No. That exploits a quirk in the AVR GPIO system that doesn't exist in the ESP32. In the ESP32 the pins are configured with:
pinMode(sda, OPEN_DRAIN | PULLUP | INPUT | OUTPUT );

and
pinMode(scl, INPUT | PULLUP);

so you could try replicating that in your code but without the PULLUP flag. However the effect of this is unknown, so YMMV.
However, if your external pullups are pulling up to 3.3V then you really don't need to do anything on the ESP32. All you end up with is a large resistance in parallel with your 4.7kΩ, which will just cause your resistance to drop slightly (and since 4.7kΩ is arguably too high any way that's a good thing).

it is 7 and 8 on Nano

@Juraj No, it's SD0 and SD1, which are GPIO7 and 8 on the esp32! Read the question. The nano is irrelevant.

yes, sorry, you are right.

@Majenco so how could I use the external 4.7K pull up without interfere with the esp32 internals?

@daigs What voltage are you pulling up to?

@Majenaco good question :-) I'm in trouble! I try to edit the first post to have a little more help from you over the question.


text:
When does interrupt get fired
When does the ISR mapped to SPI_STC_vect (SPI transmission complete) get fired? Does it fire after a byte has been received (eight clock cycles) of when the slave select changes back to high to deselect the slave?
Or: does "transmission" mean the transmission of a byte or the whole bunch of bytes that belong to the command sequence?

It fires after a single byte has been sent or received (the two are one and the same). This is because there is only room for one byte in the buffer, so you need to get it out of that buffer (or put a new one in) after each 8-bit transfer.


text:
Esp8266 + Atmega328p as flash
Being clear I'm not talking about How to flash ESP8266 using arduino.
I want to ask how can I use atmega328p as flash with esp8266 (instead of that 8 pin small chip on ESP-01) so that I can burn Webserver code on Atmega328p and it simply works with esp8266?
Thanks in advance.

No. No you cannot.

Can I ask why? And if I need a webserver should I upload a code to Esp8266 seperatly and make atmega328p and esp8266 communicate via TX RX?

To do it you would need 1) a high speed (40mhz or better) spi slave interface, 2) hundreds of kB or even multiple mb of flash, 3) firmware to emulate a flash chip. The Arduino doesn't have 1 or 2 and writing 3 would be a chore.

To make a web server either install the at firmware on the esp and follow the examples or program the esp directly and use whatever communication method you feel is appropriate to talk to an Arduino if you really feel you need to have an Arduino at all.

why emulate the flash if every esp8266 module has the flash to which you can upload over the esp8266?

It can't be done (also, why would you think that would ever be a good idea?!)
The 8 pin chip on the ESP-01 is a 512kB SPI flash that runs at (at least) 40MHz.  So to emulate that you would need:

More than 512kB of flash,
A slave SPI interface that can operate at a minimum of 40MHz, and
The knowledge, time and energy to write the firmware to emulate an SPI flash chip

The first two are certainly beyond an ATMega328P with 32kB flash and an 8MHz maximum speed SPI interface. The third is probably beyond you since you have to ask the question in the first place (which shows a certain lack of knowledge on what it is you are proposing).
There are plenty of examples for creating a web server using an ESP8266 using either the standard AT firmware or by directly programming the ESP8266's flash chip through the ESP8266's built-in UART bootloader.  Personally I find the use of AT firmware clumsy at best and prefer to always program my ESP8266's directly.  If you feel the need to also add an ATMega328P into the mix for some reason then the communication protocol that you use between them is entirely up to you.


text:
Measuring Battery level with ADC already in use
I have NodeMCU v3 with ESP8266 and I am running small project where I am measuring the input from IR phototransistor via ADC pin (A0) and everything is working flawlessly.
But now I want to transfer it to battery source (powerbank -> microUSB) and I want to be able to tell the remaining battery capacity, but all tutorials I found were going through switching ADC(A0) to internal, thus disabling it.
Is there any other way I can either measure the battery OR input from phototransistor?
Thanks!

you can just stop exploring now; the power bank will spit out 5.0v until it's dead.

As @dandavis rightly says in the comments, you can't measure the battery voltage from a power bank.  This is because the power bank typically includes a step-up converter to turn the batter voltage (3.2 to 4V) into a stable 5V.  That 5V will alwaye be 5V (or thereabouts) until the battery runs out and the power bank shuts itself off.
To measure the battery state you will have to directly interface with the batteries (disassemble the power bank) and tap into the battery terminals themselves.
Some power banks also have LEDs in them to display the power remaining. It could be possible to interface directly with these as well.
One thing to note, though, is that using a power bank for an ESP8266 board is pretty silly.  You are taking nominal 3.6V, stepping it up to 5V, then linearly dropping it back down to 3.3V again.  Both stages involve power wastage - the 5V to 3.3V most of all (a linear regulator turns the waste voltage into heat).
You would be better removing the batteries from the power bank and wiring them directly to the power input - or better still, feed them through a high efficiency switching regulator to get a stable 3.3V and feed that directly into the 3.3V pin.  be sure to include some way of monitoring the battery voltage and shutting off the power when it gets too low. Since your ADC input is already in use the simplest way is to add an external ADC chip to your design.


text:
Audio stops playing after rtc is connected
I am trying to play a song using arduino while at the same time display time using a rtc board using the tmrpcm library. However, if the rtc board is connected no sound is played.
I do understand that the tmrpcm may be interfering with the wire.h library but even commenting the same doesn't resolve the problem.
I am using the following code:
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <RTClib.h>
#include<Wire.h>
#include <Arduino.h>
#include "SevenSegmentTM1637.h"
#include "SevenSegmentExtended.h"
#include "SevenSegmentFun.h"
#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"

TMRpcm tmrpcm;

const int ProxSensor=3;
int inputVal = 0;
#define CLK 8
#define DIO 7

// The amount of time (in milliseconds) between tests
#define TEST_DELAY   2000

SevenSegmentFun    display(CLK, DIO);

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {
  Serial.begin(9600);
  if(!SD.begin(SD_ChipSelectPin))
  {
    Serial.println("SD fail");
    return;
  }
  while (!Serial); // for Leonardo/Micro/Zero
  tmrpcm.speakerPin=9;
  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(2019, 10, 19, 01,41,00));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
  pinMode(ProxSensor,INPUT);    //Pin 2 is connected to the output of proximity sensor
  display.begin();
}

void loop(){
  DateTime now = rtc.now();
  display.print((now.unixtime() / 86400L )-17963);
  Serial.print((now.unixtime() / 86400L )-17963);
  while(digitalRead(ProxSensor)==LOW)      //Check the sensor output
  {
    tmrpcm.setVolume(5);
    tmrpcm.play("test.wav");
      repeat:
    if(digitalRead(ProxSensor==LOW))
      goto repeat;
  }
}

Can anyone please help me?

The TMRpcm and one of your other libraries might use the same timer on Uno which causes one of them to break. Either get a Arduino Mega which can run TMRpcm on TIMER3,4 or 5 or use libraries that don't require a timer.

In what way does the Wire library use a timer?

@Majenko probably for timing the SCK pulses.

I can't find any reference of what it is used for and if used at all but it seems that the usage of the TWBR breaks many things related to timer one.

Can you cite some evidence for this? This is new to me - and the TWI peripheral has nothing to do with any timer peripherals - the baud rate generator is internal to TWI and uses the system clock as its source.

@SoumendraDey, explain please how did this answer help, because it should not

The problem is
repeat:
if(digitalRead(ProxSensor==LOW))
  goto repeat;

ProxSensor==LOW is false so 0. you read the pin 0 and the outcome is random. The surrounding wiring can affect that. If digitalRead(0) is zero the wav starts playing immediately again. At least use
while (digitalRead(ProxSensor) == LOW);

I am already using while (digitalRead(ProxSensor) == LOW) in my code

@SoumendraDey,  read the answer again and slow


text:
Laser Controller using Arduino Uno
---> I am trying to create a controller using Arduino Uno that simply detects pulses from a waveform generator mimicking a Laser Machine and then switches between 4 state machines states at the output of a Pre-amp, it is a built on of this previous post so the connections are the same except for the waveform generator settings. The new waveform generator settings are :
Type: Pulse, Freq:20Hz (50ms), Amp:5.0 Vpp, Offset:0V, Width = 100ns
---> I am trying to add 5 things in the project so any input is greatly appreciated:
1) Initialize all the 4 state machine states into an Array so user can define as many states as they want from the declarations.
2) ADD a digital de-bounce to the input pin, LASER_PIN.
3)(requires item #5 to be done first)  ADD a reset to the system which moves the program back to STATE_00  from whatever it is doing.
4) Better code to wait until a pulse from Laser arrives before going to the state machine in void loop().
5) (item #2 depends on this) Completely Remove delay from the CountPulses() function and replace with millis() function to allow the use of reset button
---> Here is what i have so far, i started off by adding 4 state machine states and using the delay() function in the CountPulses() function just like in the previous post and it works fine and i am able to switch states while counting pulses, however, when i added the millis() to replace delay() function as shown below in the code, i only get 0s in pulse count and the state machine is stuck in STATE_00 so i used a couple of print statements to debug  and it turns out currentmillis() - startmillis() is actually less than period = 1000ms so i am stuck on how to set this up and without this i cannot move forward, any help would be appreciated. My code and serial monitor results are shown below:
--> UPDATE: items #3 and #5 work perfectly fine , please see updated code. for item #4 i have not figured this one out yet. for item #2 ,there are a lot of libraries for debounce but not sure which libraries (Button, Bounce and etc) are most trusted by arduino community, any suggestions would help.
-->UPDATE 2: The code has been update with the following changes, external interrupts are used to reset the system if switch is LOW, Polling with interrupts is used to wait for pulses.
THE UPDATE TO QUESTION: items#3, 4 and 5 were solved and now only 2 items remain to be added to the project with modifications to item #1 and item #2 based on comments:
1) I require the state machine to do the following:
a) Declared in an array where user can easily change the order of execution of states. (eg: state_2--> state_1 -->state_3--> state_0).
b) User can easily decrease the number of states from MAX_VALUE = 4 to only 1 state. (eg with MAX_VALUE = 3: state_0--> state_1--> state_2)  .
2) ADD a digital de-bounce to the input pin, RESET_PIN.
Note: The debounce to LASER_PIN was a mistake in understanding based on the comments, so i have updated this.
Updated code with current serial monitor results is shown below:
       //Objectives: Use input from laser to control pre-amp on adc. Multiplex the inputs on Pre-Amp
//Date:10/21/2019
//Type: Pulse, Freq:20Hz (50ms), Amp:5.0 Vpp, Offset:500mV, Width = 100ns

//-----------------------PROJECT LIBRARIES----------------------------------
#include <Bounce2.h>
#include <Arduino.h>
#include <avr/io.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>
//-----------------------DEFINES------------------------------------------
//Declare Laser Input Pin
#define LASER_PIN 2

//Declare Reset Pin
#define RESET_PIN 3

//Define the states of the machine
typedef enum {STATE_00, STATE_01, STATE_10, STATE_11} fsm_state_type;
fsm_state_type fsm_state = STATE_00;

// -------------------------CONSTANTS (won't change)-------------------------------------
const unsigned long period = 1000;  //the value is a number of milliseconds

//-------------------------VARIABLES (will change)-------------------------------------
bool only_for_print = false;//used only for print state ments

int reset_switch = 1;//Start HIGH to avoid reset
int PulseCount = 0; //Pulse count from X-RAY
int Output = 0;//Switch state on the Pre-Amp
int wait = 0;//wait for pulses count
int N = 20;//no. of pulses to count before switching states
volatile int IRQcount = 0;
volatile boolean reset_flag = false;

unsigned long start_time = 0;
unsigned long current_time = 0;

//----------------------------USER DEFINED FUNCTIONS---------------------------------
void fsm();
void loop();
void setup();
void WDT_RESET();
void IRQcounter();
void CountPulses();
//-----------------------------DEBOUNCE FUNCTIONS---------------------------------------

//--------------------------------MAIN SETUP--------------------------------------

void setup()
{

  Serial.begin(115200);

  //Pin Setup
  pinMode(LASER_PIN, INPUT_PULLUP);
  pinMode(RESET_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(LASER_PIN), IRQcounter, RISING);//attach interrupt handler to laser input
  attachInterrupt (digitalPinToInterrupt (RESET_PIN), RESET_ISR, FALLING);  // attach interrupt handler to reset, wait for user press button or switch
  start_time = millis();   //initial start time
  sei();//Turn on Interrupts

    WaitForPulses();//Waits to detect 20 pulses
}

//--------------------------------MAIN LOOP----------------------------------
void loop()
{

 current_time = millis();
 fsm();//State machine
}

//--------------------------------PULSE COUNT FUNCTION--------------------------------------------

void CountPulses()
{
  //  current_time = millis();
  if ((current_time - start_time) >= period)
  {
    start_time = current_time;
    cli();//disable interrupts
    PulseCount = IRQcount;
    IRQcount = 0;
    Serial.print(F("Pulse Count is = "));
    Serial.println(PulseCount);
    sei();//enable interrupts
  }
}

//--------------------------------STATE MACHINE FUNCTION--------------------------------------------
void fsm()
{
  switch (fsm_state)
  {

    case STATE_00:

/////////Print Statement only for debugging//////////
        while (only_for_print == false)
        {
            Serial.println("The state is 00");
            only_for_print = true;
        }

///////// Count Pulses Setup /////////////////
            current_time = millis();
            CountPulses();
            Output = 0;
            if (PulseCount == N)
            {
              PulseCount = 0;//Reset Pulse Count
              only_for_print = false; //used only for print statments
              fsm_state = STATE_01;//switch to next state
            }
      break;

    case STATE_01:
/////////Print Statement only for debugging//////////
      while (only_for_print == false)
      {
          Serial.println("The state is 01");
          only_for_print = true;
      }

///////// Count Pulses Setup /////////////////
          current_time = millis();
          CountPulses();
          Output = 2;
          if (PulseCount == N)
          {
            PulseCount = 0;//Reset Pulse Count
            only_for_print = false; //used only for print statments
            fsm_state = STATE_10;//switch to next state
          }
      break;

    case STATE_10:
/////////Print Statement only for debugging//////////
      while (only_for_print == false)
      {
          Serial.println("The state is 10");
          only_for_print = true;
      }

///////// Count Pulses Setup /////////////////
          current_time = millis();
          CountPulses();
          Output = 3;
          if (PulseCount == N)
          {
            PulseCount = 0;//Reset Pulse Count
            only_for_print = false; //used only for print statments
            fsm_state = STATE_11;//switch to next state
          }

      break;

    case STATE_11:
/////////Print Statement only for debugging//////////
      while (only_for_print == false)
      {
          Serial.println("The state is 11");
          only_for_print = true;
      }
///////// Count Pulses Setup /////////////////
          current_time = millis();
          CountPulses();
          Output = 4;
          if (PulseCount == N)
          {
            PulseCount = 0;//Reset Pulse Count
            only_for_print = false; //used only for print statments
            fsm_state = STATE_00;//switch to next state
          }

      break;

    default:
      fsm_state = STATE_00;
      break;
  }

}

//----------------------------------RESET SWITCH ISR-------------------------------------

void RESET_ISR()
{
  reset_flag = true;
  if(reset_flag == true)
    {
     // Serial.println("System will now Reset");// Only for debugging
      reset_flag = false;//Reset reset switch flag
      wdt_enable(WDTO_500MS);//Reset after 0.5 seconds
      while (1)
       {
         // wdt_reset();          // uncomment to avoid reboot
       }
    }
}

//-----------------------PULSE COUNT ISR---------------------------------------

void IRQcounter()
{
  IRQcount++;
}
//-----------------------WAIT FOR PULSES---------------------------------------
void WaitForPulses()
{
  while(wait<20)
 {
    if (bit_is_set(EIFR, INTF0))
    {
      Serial.println("Pulse is detected ");
      wait++;
    }
 }
 wait = 0;//reset
}
*/

[![edited image][3]][3]
The serial monitor is shown below with added reset switch on pin 3 using watch dog timer library .
 Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
Pulse is detected
The state is 00
Pulse Count is = 112
Pulse Count is = 20
The state is 01
Pulse Count is = 20
The state is 10
Pulse Count is = 20
The state is 11
Pulse Count is = 20
The state is 00
Pulse Count is = 20
The state is 01
Pulse Count is = 20
The state is 10
Pulse Count is = 20
The state is 11
Pulse Count is = 20
The state is 00
Pulse Count is = 20
The state is 01
Pulse Count is = 20
The state is 10
Pulse Count is = 20
The state is 11
Pulse Count is = 20
The state is 00
Pulse Count is = 20
The state is 01
Pulse Count is = 20
The state is 10
Pulse Count is = 20
The state is 11
Pulse Count is = 20

Important note:
After reading (again) your other question and its answers: You are stressing the input of your Arduino with negative voltages! Please set the offset of the signal to 2.5V (the middle between GND and VCC) and the amplitude to 5Vpp. The signal must neither be lower than GND nor higher than VCC! The input might withstand this for a while but given enough time and power it will get damaged.
Analysis of your problem:
1. The measurement of the period
Let's take a look at a "condensed" version of your time code:
void setup()
{
  startMillis = millis();
}

void loop()
{
  currentMillis = millis();
  if (currentMillis - startMillis <= period)
  {
    startMillis = currentMillis;
  }
}

I'm sure you see it now, too! Because right at the first call of loop() the time passed since setup() is short, the condition is true and startMillis is updated to the current time. This is repeated ever and ever again. The condition will always evaluate as true.
2. The number of pulses
In the function CountPulses() the counter is reset at the beginning. Then after some undefined very short duration (because your if-condition is always true) it is read. Chances are low for a pulse to be counted in that time span.
Additional note:
Just one more tip. You can define and use your own data types to show your intentions. For example the states look so much better like shown below, and you'll get free error messages from code analyzers.
typedef enum {
    STATE_00, STATE_01, STATE_10, STATE_11,
} fsm_state_type;
fsm_state_type fsm_state = STATE_00;

EDIT after you added new informations:
Item #2
Why do you think you need to debounce the laser pulse? Is it generated by a mechanical switch? Only those need debouncing. If the pulses are generated from some electronic circuit they should be clean.
Item #4
You can reset the IRQcount and then wait for it to count up.
But as this involves disabling and enabling the interrupt and reading an int just for 1 event, I'd rather set a flag if the interrupt occurs. Then the FSM could wait for the flag to be set.
Another alternative is to poll the input pin directly and to wait for the leading edge. But for this the pulse has to be wide enough.
As @EdgarBonet pointed out it will be even simpler to poll the interrupt flag. But IIRC the interrupt has to be disabled for this, else the call of the interrupt service routine will clear the flag with no chance for the main program to see it.

A better alternative is to poll the interrupt flag (i.e. if (bit_is_set(EIFR, INTF0)) { ... }). Then you don't need a wide pulse: once the hardware detects the rising edge, the flag is set and remains set until you explicitly clear it (EIFR = _BV(INTF0);).

here is where i am having the difficulty from transition from delay() to millis() :  when adding the delay() function, the program is able to count the number of pulses, now removing it and replacing with millis() function, the program is too fast to count the pulses (always shows 0 pules) . I have tried lowering the baud rate but and changing the settings for millis() function with different periods, but it doesnt help.

Well, step away from the source code and make a design. Don't program by accident, think and plan. You know that you need some certain period as the source shows. Now use it. What would you do as a human to tackle the task? millis() can be compared to a look at the wall clock.

Re “Another alternative is to poll the input pin [...]. But for this the pulse has to be wide enough.”: A better alternative is to poll the interrupt flag (i.e. if (bit_is_set(EIFR, INTF0)) { ... }). Then you don't need a wide pulse: once the hardware detects the rising edge, the flag is set and remains set until you explicitly clear it (EIFR = _BV(INTF0);).

@EdgarBonet Thanks for reminding me to this. I took the liberty to quote you.

Re “IIRC the interrupt has to be disabled for this [...]”: You do recall correctly. ;-)

I am little confused, when i use if (bit_is_set(EIFR, INTF0)) { ... } , it returns a 0 which tells me that the interrupt flag ITF0 is not set in EIFR register. In order to test it out i put a print statement in the if statement which always executes when i turn on the waveform generator and stops executing when i turn it off which tells me that ITF0 is set and cleared, so i am not sure what is going on , any clarifications ?

Would you mind to post the code for this?

Oh, and please do this by editing your question, and putting some informational words around it so that others don't have to dig deep in the comments.


text:
WifiManager and WiFi functionally
I’m considering using wifiManager mostly to have the ability not to hard code WiFi creditntials.
But In my current code I use WiFi’s functions as WiFi.setAutoReconnect(true) and WiFi.status() != WL_CONNECTED
How can it be done using WifiManager?

You don't. WifiManager does all that for you. You don't need anything like that in your code. Just follow the examples and read the documentation.
But if you do want to then you just need to remember that WifiManager is merely a library that configures the WiFi for you. If you want to query or alter the WiFi settings you can - exactly as you are right now. The two aren't mutually exclusive.

I didn’t find any example to check if connected

You don't "check if connected". It connects, or it gives you an AP with a portal. In the latter case it blocks waiting for you to configure it. There is no "check". If your code runs then it's connected. All the examples show that.

I understand what you say, but from time to time there are disconnections, and I do not want that it will automatically go to AP mode. how many retires before entering AP mode/ time to try to reconnect ?

WifiManager is just a library that use the WiFi object. It's not a replacement. If you want to also interact with WiFi there's nothing to stop you. You can set auto reconnect. You can query the status. Just as you are.

OK. Should I define an instance of Wifi as well ?

No, there already is one.

Here's a working example that's on my Wemos D1 Mini. It stands up an AP until you provide credentials for your local LAN, then displays it's DHCP IP address on a 16x2 LCD and stands up a webserver. Once the credentials are stored it won't stand up the AP, it will just reconnect and do the main loop() of the sketch. To force the AP to restart you need to call the ESP.reset(); method to flush the stored credentials and reboot the Wemos.
#include <LiquidCrystal_PCF8574.h>
#include <ESP8266WiFi.h>

#include <WiFiManager.h>
#include <ESP8266WebServer.h>
#include <Wire.h>

WiFiClient wemosCL;

ESP8266WebServer server(80);

const int led = LED_BUILTIN;

LiquidCrystal_PCF8574 lcd(0x38);

void handleRoot() {
  digitalWrite(led, 1);
  server.send(200, "text/html", "<title>ESP8266 Demo</title>
Hello from ESP8266!

IP Addr: " +
          WiFi.localIP().toString() + "
");

  digitalWrite(led, 0);
}

void handleNotFound() {
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}

void setup(void) {
  Serial.begin(115200);
  WiFiManager wifiManager;
  wifiManager.autoConnect("Wemos", "configuration");
  pinMode(led, OUTPUT);
  digitalWrite(led, 0);

  lcd.begin(16, 2);
  lcd.setBacklight(255);
  lcd.print("I'm alive");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    lcd.setCursor(0, 0);
    lcd.print(".");
  }

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Status:Connected");
  lcd.setCursor(0, 1);
  lcd.print("IP:");
  lcd.print(WiFi.localIP());

  server.on("/", handleRoot);

  server.onNotFound(handleNotFound);

  server.begin();
}

void loop(void) {
  server.handleClient();
}

Hi Dougi, something I miss is, when line of code reaches wifimanager in setup it only look for stored crediatials ? from what I understood in Mejenko's asnwer, once it passed that line, wifi is connected, so I don't understand why the section called \\wait for connection is relevant. I'm guessing that something I don't understand here :)

The wait for connection is after the credentials for my home WiFi are entered as it switches from AP to STA mode then my router does the DHCP handshake. That takes some time to run.

OK. and at next boot... when credentials were entered boot before, and just being used at current boot ... still when reaching \\ wait for connection- in that excat moment, is Wifi connected ?


text:
5v relay module and bulb holder

Hello sir , so can i cut the switch from the picture and connect the wires to my relay module ? Im sorry because im still learning . Thank you !

If you are still learning I would recommend you start with something more basic like LEDs instead. And learning the basic concepts of electricity from there. Not mains power that can kill you in case of mishandling.

Thank you sir @Coder_fox i will be carefully handling this project :)

A relay is nothing more than a switch - but instead of your finger controlling it, it's controlled by an electromagnet.
The relay can perform the exact same function as the switch on that cable.  In the image you have posted you would use the right-hand two screw terminals (middle is "common", right is "normally open") to replace the switch.

So that means , it works right if i do like that sir @Majenko ? Thank you sir for the help ! :) Your are kind !

You can refer to this to cut the switch
If you are a beginner, you can get started with Relay here
NOTE: It's dangerous and can cost your life. Please be careful when using Relay with 220 VAC

Thank you sir . You r kind ! Will do , thanks again I relay appreciated it !


text:
Creating and Arduino synthesizer without the tone library
I am thinking about trying to make an Arduino synthesizer using the true analog output on the Due. However I would like to be able to play multiple notes at the same time on a single buzzer. Is this possible and how would I do it?

what is buzzer? .... is it able to produce different tones?

You just have to add the waveforms. For example, if you want to play
pure tones (the simplest and most boring timbre), you generate a sine
wave for each of them and add them together:
struct Note {
    float frequency;
    float phase;
    bool is_active;
} notes[MAX_NOTES];

void output_sample()
{
    static uint32_t previous_time;
    uint32_t now = micros();
    uint32_t elapsed_time = now - previous_time;
    previous_time = now;
    float output = 0;
    for (int i = 0; i < MAX_NOTES; i++) {
        Note *note = &notes[i];
        if (note->is_active) {
            output += cos(note->phase);
            note->phase += 2*M_PI*note->frequency*1e-6*elapsed_time;
            if (note->phase >= 2*M_PI) {
                note->phase -= 2*M_PI;
            }
        }
    }
    analogWrite(DAC_PIN, 2048 + round(output * (2047.0 / MAX_NOTES)));
}

The function output_sample() should be called as frequently as
possible. You can change the notes array any time to add, remove or
change notes.
There is some room for optimization here, like:

storing 2*M_PI*note->frequency*1e-6 as the “frequency” in order to
save some calculations
using a wave table instead of the cos() function (I don't know how
good is the Due at transcendental math)
replacing elapsed_time by a constant if you can manage to output the
samples at a fixed rate.

Edit: I wrote “You can change the notes array any time to add,
remove or change notes.” Here is how to start or stop a note, i.e. to
add or remove it from the list of active notes:
// Start a note. Returns an index to be used with stop_note(), or -1 if
// we couldn't start the note because we are already outputting the
// maximum number of simultaneous notes.
int start_note(float frequency)
{
    int i;  // index of the note in the notes[] array

    // Find a free slot in the array.
    for (i = 0; i < MAX_NOTES; i++)
        if (!notes[i].is_active) break;  // found

    // Couldn't find a free slot?
    if (i == MAX_NOTES) return -1;

    // Setup the note parameters.
    notes[i].frequency = frequency;
    notes[i].phase = 0;
    notes[i].is_active = true;
    return i;
}

// Stop the note with the given index.
void stop_note(int index)
{
    if (index >=0 && index < MAX_NOTES)
        notes[index].is_active = false;
}

How would I add notes here? I am not extremely familiar with structs.

@Someone: You find a cell in the array where is_active is false, and you set the desired frequency, and set is_active to true.

how would I add an item to the note array?

Sound is nothing else than a multiple simple waves combined in to one. So, theoretically you can play as many sounds (tones) as you like on a single pin. If you want to go true analog than you probably want to use a sin wave to generate sound. However, in that case you can do the following:
Either make a function that would be capable of generating a sin wave of your desired frequency. In case of true analog this would probably be done by calculating actual sin values and using the map() function mapping 0 - 1 to 0 - 1024 and writing to the pin. The frequency can be adjusted by changing the delay between each step of changing the voltage or DAC value. However, this will not allow for multiple frequencies.
Alternatively for multiple frequencies to be played at the same time you would need to calculate the Fourier inversion of all the waves you want to play and send the results of that to the DAC.

And you would need to use a speaker instead of a buzzer, since they can produce a single tone at a time.

“Fourier inversion” is needless math jargon for what is simply the sum of the tones.

@EdgarBonet yes, it's basically a sum.

How would I go about doing this?

@Someone Writing code that would preform the above described. I've included hyperlinks to help understanding what is meant and how to use it. Also, visit the https://www.arduino.cc/reference/en/ page that includes much information on how to perform mathematical and logical operations in the Arduino language as well as how to control the hardware of the Arduino.

Mixing sounds is not as simple as summing them mathematically (nor summing and averaging to bring the level back down). I made that mistake once years ago, and the results were crap. Once I found a proper sound mixing function I never looked back...


text:
How to merge two GPS coordinates without losing decimals
I want to take the GPS coordinates like 42.1234 per 22.1234 and merge them as a string, with a separator character:
42.1234 x 22.1234
But using this code:
gps_string = (String)gps.location.lat()+' x '+(String)gps.location.lng();
I lose the last decimals and I get:
42.12 x 22.12
The only way I could see full coordinates is by specifying an extra parameter to println, like this:
Serial.println(gps.location.lat(), 6);
How can I create a string containing both two coordinates without losing decimals ? e.g 42.1234 x 22.1234

your question has nothing to do with GPS ... it is a question about converting a floating point number to string without losing precision

one thing to note, the GPS module probably outputs text, not floating point numbers

What GPS module have you got? What GPS library are you using?

@Dougie I can check when I get back on computer but like jsotola said, it is a float number conversion issue, not really speciffic to this GPS, but to Arduino.

Try using dtostrf(val, 4, 6, buff); rather than casting the value to a String.

the CStringBuilder from my StreamLib allows to build a C string (char array terminated by 0) with the same functions you use on Serial

@jsotola: The GPS module probably outputs text in the NMEA format, with degrees, minutes, and minute decimals. So you'll need to convert that anyway.

If you want 4 decimal places, you may try something like this:
gps_string = String(gps.location.lat(), 4)
           + " x "
           + String(gps.location.lng(), 4);

https://forum.arduino.cc/index.php?topic=243660.0 suggests avoiding Strings and String() functions. Use dtostrf(val, 4, 6, buff);

This one works very nice (simple). If I can simplify the code a bit, I will post an answer using the dtostrf. I understand the dtostrf method is for memory/performance considerations.