text:
Connecting wires and coding in GPS Module GY-NEO6MV2 with ESP8266-01

Here is the link : https://www.circuito.io/app?components=10167,11021,12083,13678,13959,975601
I'm just a beginner I don't have the idea on how GPS module wires should be connected
#include "DHT.h"
#include "NewPing.h"
#include <SoftwareSerial.h>
#define DEBUG true
 SoftwareSerial esp8266(11,10);
  //SoftwareSerial gps(8,9);
 #define DHTPIN 2       // DHT-11 Output Pin connection
 #define DHTTYPE DHT11   // DHT Type is DHT 11 (AM2302)
 #define TRIGGER_PIN 4
 #define ECHO_PIN 3
 #define MAX_DISTANCE 400

 NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

 float hum;
 float temp;

 DHT dht(DHTPIN, DHTTYPE);

 void setup() {
 Serial.begin (9600);
 Serial.println("START");
 esp8266.listen();
 esp8266.begin(9600);
 gps.begin(9600);
 dht.begin();

  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  sendData("AT+RST\r\n",2000,DEBUG);            // command to reset the
  module
     sendData("AT+CWMODE=2\r\n",1000,DEBUG);       // This will configure
     the mode
     as access point
   sendData("AT+CIFSR\r\n",1000,DEBUG);          // This command will get
   the ip
   address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG);       // This will configure the
  esp
for multiple connections
sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // This command will turn on
the
server on port 80
}

void loop()
{

 delay(2000);  // Delay so DHT-11 sensor can stabalize

 hum = dht.readHumidity();  // Get Humidity value
 temp= dht.readTemperature();  // Get Temperature value

  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);

long duration,distance;
duration= pulseIn(ECHO_PIN,HIGH);

distance = duration/58.2;

Serial.print("Humid: ");
Serial.print(hum);
Serial.print(" %, Temp: ");
Serial.print(temp);
Serial.print(" C, ");
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(50);

gps.listen();
while (gps.available())
Serial.write(gps.read());

esp8266.listen();
if(esp8266.available())         // This command will that check if the esp
    is sending a message
    {
    if(esp8266.find("+IPD,"))
    {
    delay(1000);

    int connectionId = esp8266.read()-48; /* We are subtracting 48 from the
    output because the read() function returns
                                        the ASCII decimal value and the
    first decimal number which is 0 starts at 48*/
     String webpage = "<meta http-equiv=\"refresh\" content=\"5;
     url=192.168.4.1/\">";
     webpage += "
Mabalacat City College Garbage Monitoring System
";
    webpage += "

";
    if (distance<=5)
    {
    webpage+= " Trash can is Red";
    }
    if (distance == 20)
    {
      webpage+= " Trash can is Orange";
      }
      if (distance == 35)
    {
      webpage+= " Trash can is Light Orange";
      }
      if (distance == 50)
    {
      webpage+= " Trash can is Yellow";
      }
      if (distance == 70)
    {
      webpage+= " Trash can is 2st Light Yellow";
      }
      if (distance == 85)
    {
      webpage+= " Trash can is 1st Light Yellow";
      }
      if (distance == 95)
    {
      webpage+= " Trash can is Green";
      }
      if (distance >= 100)
    {
      webpage+= " Trash can is Empty";
      }
      webpage+= "
";
      webpage+="Distance: ";
      webpage+=distance;
      webpage+=" cm";
      webpage+= "
";
      webpage+="Temperature: ";
      webpage+= temp;
      webpage+=" celsius";
      webpage+= "
";
      webpage+= "Humidity: ";
      webpage+= hum;
      webpage+= " %";

 webpage += "

";
 String cipSend = "AT+CIPSEND=";
 cipSend += connectionId;
 cipSend += ",";
 cipSend +=webpage.length();
 cipSend +="\r\n";
 sendData(cipSend,1000,DEBUG);
 sendData(webpage,1000,DEBUG);
 String closeCommand = "AT+CIPCLOSE=";
 closeCommand+=connectionId;
 closeCommand+="\r\n";
 sendData(closeCommand,3000,DEBUG);
}
   }
  }

  String sendData(String command, const int timeout, boolean debug)
{
esp8266.listen();
String response = "";
esp8266.print(command);
long int time = millis();
while( (time+timeout) > millis())
{
  while(esp8266.available())
  {
    char c = esp8266.read();
    response+=c;
  }
}
if(debug)
{
  Serial.print(command);
  Serial.print("> ");
  Serial.print(response);
}
gps.listen();
return response;
}

Comments are not for extended discussion; this conversation has been moved to chat.

GPS - Arduino
---------------
GND -  GND
TX  -  pin of SoftwareSerial RX
RX  -  pin of SoftwareSerial TX
Vcc -  3.3 V

Only one instance of SoftwareSerial can listen. Method listen() determines which one. So you must add esp8266.listen(); before talking to esp8266 and gps.listen(); before talking to GPS module.

in setup() add esp8266.listen() before first sendData call
in loop() add gps.listen() before while (gps.available())
in loop() add esp8266.listen() before if (esp8266.available())

Comments are not for extended discussion; this conversation has been moved to chat.

@Majenko, the system didn't offer move to chat and I could not create a chat with OP, because OP doesn't have reputation points to use the chat

The message is an automated moderator thing. I'm just cleaning up.


text:
Custom Classes - Redefinition of void error
I'm getting a redefinition error from my classes, but can't see what I did wrong.
Error: Icon.cpp:3:6: error: redefinition of 'void Icon::setIcon(byte (*)[8])'
Can any help me out on this? Thanks!
MyFile.ino
#include "MyIcon.h"

MyIcon myIcon;

MyIcon.h
#ifndef MyIcon_h
#define MyIcon_h

#include "Arduino.h"
#include "Icon.h"

class MyIcon : public Icon {
  public:
    MyIcon();
};

#endif

MyIcon.cpp
#include "MyIcon.h"

MyIcon::MyIcon() {

  byte _icon[8][8] = {
    {1, 1, 1, 1, 1, 1, 1, 1},
    {1, 1, 2, 2, 2, 2, 1, 1},
    {1, 2, 1, 1, 1, 1, 2, 1},
    {2, 1, 2, 2, 2, 2, 1, 2},
    {1, 2, 1, 1, 1, 1, 2, 1},
    {1, 1, 1, 2, 2, 1, 1, 1},
    {1, 1, 2, 1, 1, 2, 1, 1},
    {0, 0, 0, 1, 1, 0, 0, 0},
  };
  MyIcon::setIcon(_icon);

Icon.h
#ifndef Icon_h
#define Icon_h

#include "Arduino.h"

typedef struct{
  byte r;
  byte g;
  byte b;
} RGB;

class Icon {
  public:
    Icon();
    inline virtual void setIcon(byte icon[8][8]){};
    inline virtual void setIconColors(RGB colors[3]){};
};

#endif

Icon.cpp
#include "Icon.h"

void Icon::setIcon(byte icon[8][8]) {
  __icon = icon;
}

void Icon::setIconColors(RGB colors[3]) {
  __colors = colors;
}

Edited on 09/11/18
I attempted the following changes, before I realised thanks to KIIV, that I couldn't use array like that.
My idea was to be able to getIcon() and get back the byte array, which is later used to light up specific leds on a NeoMatrix panel.
I thought I would be able to build an icon "library" by extending a base class, setting the correct byte array in the class, and using it as needed (MyIcon, MyOtherIcon, etc...)
Have I completely missed the point?
Icon.h
void setIcon(byte icon[8][8]);
void setIconColors(RGB colors[3]);

Icon.cpp
#include "Icon.h"

Icon::Icon(){ }

void Icon::setIcon(byte icon[8][8]){
  memcpy(__icon, icon, sizeof(icon));
}

void Icon::setIconColors(RGB colors[3]){
  memcpy(__colors, colors, sizeof(colors));
}

Hidden error: You might also what to check the MyIcon constructor. What type of variable (_icon) are you passing to "Icon::setIcon()"?

this is an example of a question for Stack Overflow, not for Arduino SE. https://arduino.stackexchange.com/tour

You should make the Icon pure virtual by virtual void setIcon(byte icon[8][8]) = 0; and same for setIconColors. In Icon.cpp is total nonsense. Even if you define __icon and _colors in MyIcon as members, Icon don't know anything about it. And arrays cannot be assigned like this.

I think I got way lost in my attempts at achieving what I wanted to do. I wanted to be able to extend a base class (Icon) in order to be able to build an icon "library" of sorts.The icons are built from an 8x8 byte array, so I wanted to be able to request getIcon() from a child class like MyIcon in order to retrieve the icon (which is then use to light up a NeoMatrix panel. I didn't realize you couldn't return (or set) a byte array from a function.

I would suggest you don't want to use classes at all for this. You can have an icon as a single array of data in PROGMEM and write a little function to parse it. I'd have something like one byte for the number of colours (N), two bytes for the icon dimensions (W,H) (if needed), N*3 bytes for the colour information, then WxH bytes for the icon image. If the number of colours is always the same, or the dimensions of the icon is always the same then you could omit N and/or W,H values.

Hi Majenko, I am trying to follow your suggestions, and have tried the following gist. It seems to work for the icon byte array, but I'm having an issue in assigning fetching my struct once I place it in PROGMEM, hence why I removed the keyword. This is a very new approach to me, so I'd appreciate any feedback!
https://gist.github.com/Nate1661/0eea9200e9d1c86187c2acf205ba3602

You have bodies for setIcon and setIconColors in both the header file and the cpp file.  You can only have them in one or the other - choose.
Also, as an aside, the way that you are assigning icon data will go out of scope before you use it.  You create a local array variable which you then pass a pointer to to your constructor. That pointer is then saved. But then you go out of scope and the pointer is discarded, and the data will be overwritten.

As Majenko writes, you are having two bodies.
The bodies in the header file are empty and probably you do not want this. It is normal to implement the functions in the cpp file (which you do), so in the header file remove the {} in
inline virtual void setIcon(byte icon[8][8]){};
inline virtual void setIconColors(RGB colors[3]){};

so it becomes
inline virtual void setIcon(byte icon[8][8]);
inline virtual void setIconColors(RGB colors[3]);

source: Stack Exchange

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

sort: votes


text:
Trouble configuring Arduino Due SPI to ADC
I am having trouble configuring Arduino Due SPI to an AD7490 ADC.
Here is how I have the pins connected:

+3.3V > 7490 pin 22 Vin
+3.3V > 7490 Vref
DUE CS (8) > 7490 pin 20 SS - slave select)
DUE SCK > 7490 pin 16 (SCK - clock)
DUE MOSI > 7490 pin 19 (MOSI - data out)
Ground > 7490 pin 24 (all ground lines are tied together)
DUE MISO > 7490 pin 15

Below is my code, I feel like I am writing the correct bits into the register. The problem I think I'm having is getting the timing write. The code is a simple attempt to read a single channel.
#include <SPI.h>

// Set Constants
const int adcChipSelectPin = 8;      // set pin 8 as the chip select for the
ADC:

// Start setup function:
void setup() {

pinMode (adcChipSelectPin, OUTPUT);
// set the ChipSelectPins high initially:
digitalWrite(adcChipSelectPin, HIGH);
// initialise SPI:
SPI.begin();
SPI.setBitOrder(MSBFIRST);         // Not strictly needed but just to be
sure.
SPI.setDataMode(SPI_MODE0);        // Not strictly needed but just to be
sure.
Serial.begin(9600);
//Clock Speed: Master clock/divider
//84Mhz/64 =  1.3 MHz
SPI.setClockDivider(SPI_CLOCK_DIV64);

} // End setup function.

// Start loop function:
void loop() {
float voltage[2];
for (int i = 0; i < 3; i++) {
voltage[i] = readAdc(0, 0);
}

}// End of loop function.

//Function to read the ADC, accepts the channel to be read.
float readAdc(int channel, int slave) {

float value;
if (slave == 0) {
noInterrupts(); // disable interupts to prepare to send address data to the
ADC.
digitalWrite(adcChipSelectPin, LOW); // take the Chip Select pin low to
select the ADC.

byte FirstByte = 0b10000011;
byte SecondByte = 0b00110000;

SPI.transfer(FirstByte);

byte response1 = SPI.transfer(SecondByte);
byte response2 = SPI.transfer(0x00);

digitalWrite(adcChipSelectPin, HIGH); // take the Chip Select pin high to
de-select the ADC.
interrupts(); // Enable interupts.
Serial.println(response1);
Serial.println(response2);

}

The serial.prints output 255 consistently. In my experience this means the SPI is configured incorrectly.
Any pointers are appreciated.

I don't think the communication is like what you wrote here. It looks like it is sending the data with the next byte. Try with SPI.transfer(FirstByte); SPI.transfer(SecondByte); digitalWrite(adcChipSelectPin, HIGH); asm volatile("nop"); asm volatile("nop"); asm volatile("nop"); asm volatile("nop"); asm volatile("nop"); digitalWrite(adcChipSelectPin, LOW); byte response1 = SPI.transfer(0x00); byte response2 = SPI.transfer(0x00);. The five nops are for respecting the 50nm "t_quiet" time requested in the datasheet

(of course if this work you can avoid using the 0x00 writings and concatenate successive requests; for instance something like (using only one SPI.transfer instead of two, and some pseudo-code) SPI.transfer(read channel 0); CS high, nops, CS low; byte result_ch0 = SPI.transfer(read channel 1); CS high, ..[repeat as many times you need].. , CS low; byte result_chN = SPI.transfer(0x00);

I tried your suggestion and am still getting the same response as before unfortunately.  I'm not sure what the issue could be at this point.

Did you try to measure the value of voltage on the MISO pin? is it 3.3V stable or it is lower? Can you try disconnecting it from the ADC and measure the voltage on the microcontroller MISO? Can you try to put a 10k resistor between MISO and GND?

The voltage on my MISO pin is only about .8V DC. When I disconnect from ADC I read a voltage of about .8V.

If you think the problem may be my board, I just hooked up another ADC through SPI and I am getting correct values.

can you try using weak pull-ups or pull-downs? I mean, try with a 10k resistor between MISO and +3.3V, then between MISO and GND. The 0.8V is really strange, it looks like a disconnected pin... double check the soldering of that wire to the ADC

From 3.3V to MISO I am getting nearly 3.3V and from MISO to gnd I am getting nearly 0V. I ran this ADC through a reflow oven so I may have made a mistake in overheating. I have another board coming in so I'll try and make sure I'm following the datasheet reflow specifications.
Besides that, does my code look alright? Thanks for the help by the way!

So where did the 0.8V come? if you mounted them on your own, then double check the soldering of the DOUT pin on the ADC; maybe it is not correctly soldered. Sometimes just heating it with a soldering iron (and/or adding some solder) fixes the soldering

I just put a new ADC on my PCB and am now getting 3.3 V, still not the write output though.

3.3V seems reasonable. Now what is your output? Can you attach an oscilloscope during transmission to see if it is actually transferring something?

Hey frarugi, I figured it out. Than you so much for the pointers!

For anyone else who comes across the same problem, this worked for me:
// include the library code:
#include <SPI.h>

// Set Constants
const int adcChipSelectPin = 8;      // set pin 8 as the chip select for the ADC:

// Start setup function:
void setup() {
    pinMode (adcChipSelectPin, OUTPUT);

    // set the ChipSelectPins high initially:
    digitalWrite(adcChipSelectPin, HIGH);

    // initialise SPI:
    SPI.begin();
    SPI.setBitOrder(MSBFIRST);         // Not strictly needed but just to be sure.
    SPI.setDataMode(SPI_MODE0);        // Not strictly needed but just to be sure.
    Serial.begin(9600);

    //Clock Speed: Master clock/divider
    //84Mhz/64 =  1.3 MHz
    SPI.setClockDivider(SPI_CLOCK_DIV64);

    //Send dummy values over when ADC is turned on
    //Hold Din High for 16 clock cycles twice
    digitalWrite(adcChipSelectPin, LOW);
    SPI.transfer(0xFF);
    SPI.transfer(0xFF);
    digitalWrite(adcChipSelectPin, HIGH);

    digitalWrite(adcChipSelectPin, LOW);
    SPI.transfer(0xFF);
    SPI.transfer(0xFF);
    digitalWrite(adcChipSelectPin, HIGH);
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    //Send dummy values, next read should have correct values

    digitalWrite(adcChipSelectPin, LOW);
    byte FirstByte = 0x83;
    byte SecondByte = 0x50;
    byte response1 = SPI.transfer(FirstByte);
    byte response2 = SPI.transfer(SecondByte);

    digitalWrite(adcChipSelectPin, HIGH);

    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    ///////////////////////////////////////////////////////////////////////////////////

    //50ns quiet time?
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
} // End setup function.

// Start loop function:
void loop() {
    float voltage[2];
    for (int i = 1; i < 17; i++) {
        voltage[i] = readAdc(0, 1);
        //50ns quiet time?
        asm volatile("nop");
        asm volatile("nop");
        asm volatile("nop");
        asm volatile("nop");
        asm volatile("nop");
    }
} // End of loop function.

//Function to read the ADC, accepts the channel to be read.
float readAdc(int channel, int slave) {
    float value;
    if (slave == 0) {
        byte FirstByte = 0x83;
        byte SecondByte = 0x50;
        FirstByte |= channel << 2;

        noInterrupts(); // disable interupts to prepare to send address data to the ADC.

        digitalWrite(adcChipSelectPin, LOW); // take the Chip Select pin low to select the ADC.
        //Write = 1
        //SEQ = 0
        // ADD3-ADD0 = 0000
        //PM1 = PM0 = 1
        //Shadow = 0
        //WEAK/Tri = 1
        //Range = 0
        //Coding = 1
        //0b10000010 1010 0000
        //extra 4 zeros to fill

        //May need to wait 16 * (1/freq)
        //16 * (1/1.3MHz)
        byte response1 = SPI.transfer(FirstByte);
        byte response2 = SPI.transfer(SecondByte);
        digitalWrite(adcChipSelectPin, HIGH);

        interrupts(); // Enable interupts.

        //Serial.println(response1);
        Serial.println(response2);
        byte channel = (response1 >> 4);
        //byte value = (response1 << 4);
        //byte digitalValue = (response1 << 4) | response2;
        //Serial.println(digitalValue);
        //Serial.println(channel);

        byte digitalValue = 0x00;
        float value = (float(digitalValue) * 3.3) / 4096.000; // The digital value is
        converted to an analogue voltage using a VREF of 2.048V.
        //Serial.print(channel);
        //Serial.print("\t");
        //Serial.println(value);
    }
}

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


text:
Button state changes despite not being connected?
I have written some code to test buttons that I want to use
const int buttonPin1 = 1;
const int buttonPin2 = 2;
const int buttonPin3 = 3;
const int buttonPin4 = 4;
const int buttonPin5 = 5;
const int buttonPin6 = 6;

int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;
int buttonState5 = 0;
int buttonState6 = 0;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  pinMode(buttonPin3, INPUT_PULLUP);
  pinMode(buttonPin4, INPUT_PULLUP);
  pinMode(buttonPin5, INPUT_PULLUP);
  pinMode(buttonPin6, INPUT_PULLUP);
}

void loop() {
  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);
  buttonState3 = digitalRead(buttonPin3);
  buttonState4 = digitalRead(buttonPin4);
  buttonState5 = digitalRead(buttonPin5);
  buttonState6 = digitalRead(buttonPin6);

  if (buttonState1 == HIGH) {
    Serial.println("button1 press");
  }
  if (buttonState2 == HIGH){
    Serial.println("button2 press");
  }
  else if (buttonState3 == HIGH){
    Serial.println("button3 press");
  }
  else if (buttonState4 == HIGH){
    Serial.println("button4 press");
  }
  else if (buttonState5 == HIGH){
    Serial.println("button5 press");
  }
  else if (buttonState6 == HIGH){
    Serial.println("button6 press");
  }
  else{

  }
}

I have tried with the buttonPins being A0-A5 as well, and whenever I try to run the code, it always spams out that button 5 and button 2 are being pressed, despite me not pressing them, as well as when I remove the buttons entirely, and pull out all the wires from it, it still prints it out. Even when I re-run the code. How can I fix this?

Yes? That's to be expected. The clue is in the pin mode.... INPUT_PULLUP - and you check to see if it's HIGH. See the correlation?

how did you wire the buttons?

@Majenko oh, I see, so it's when I release it? That explains it.

You are setting button pins with INPUT_PULLUP mode, which activates internal resistor connected to supply voltage. In this way, your input pins are in state HIGH if disconnected or if button is not pressed.
To fix this, you need to compare your button state with LOW. Also, make sure that one side of your buttons is connected to ground. Then, pressing the button will connect the button to ground and will bring your button pin to LOW.

The answer is in the way you configured the buttons. Because you used INPUT_PULLUP, the Arduino will read the pin as HIGH when it is connected to ground.
To utilize this in your setup, the buttons must be connected to ground, not 5V. This way, when the button is pressed, the input pin gets connected to ground, causing it to read HIGH.
Another way to fix the problem is to leave the buttons connected to 5V and just set the button pins to normal input: pinMode(buttonPin, INPUT);

In summary, there are two fixes: either connect your buttons between the input pins and ground, not 5V OR use pinMode(buttonPin, INPUT);.


text:
Arduino Pro Micro bricked?
I have a Pro Micro board at which tried to upload a sketch with sparkfun's Pro Micro 3.3v processor selected.
After the upload completed successfully the board did not run again and is not even detected from the arduino ide anymore.
When I uploaded sketches with the leonardo 5.5v board selected everything went well and I had no problem. Now I can not burn the bootloader because of the arduino ide not detecting the board.
What can i do?

Nothing special, it was the sd example for listing the micro sd files that the ide has

I think that the 3.3v selected version is what caused the problem but I do not know what to do

if the sketch fails, USB is not handled. so you must activate the bootloader by activating reset twice. led should blink fast until it is active

Problem solved! By taping twice the reset and holding it the second time I managed to program my board and now the arduino ide detectes it and it works as expected.
Taping and releasing the button twice did not work but holding it the second time worked for me. I am a almost complete noob in electronics for now so to me is black magic that not releasing the button did the job instead of what everyone else is suggesting.
I hope this helps a newbie sometime in the future that is frustrated with his/er bricked board

and you know that I copied the comment from our chat about the not soldered board where you could not reset the board https://chat.stackexchange.com/transcript/message/47422785#47422785

@Juraj damn you are everywhere :P Soldering the pins was my problem indeed, I bought a soldering iron and some alloy, and now everything works just fine!

score! THanks for this, probably in the manual I did not read.

After bricking a few units I finally sat down and read the manual for my SparkFun Qwiic Pro Micro - USB-C (ATmega32U4). I also figured out the cause.
The cause of my unit bricking was bad code. Compiled and profiled fine, but crashed the unit when uploaded.  As a result the port became unavailable and seemingly gone.  In my particular case one brick was via and unsupported command in my source. The second brick was abuse of memory. Sketches would upload, then the unit dies and the no connection message pops up.
The solution for this unit was use of the reset switch with some key timing, and a trusted script to recapture the device.  This page was all I needed to read, classif #RTFM syndrome.
The following is a layman version of events for those less fortunate having not endured decades of software brain melt.
Recovery in a Nutshell
The USB port/comm when working will/can flip between the "normal" mode and the bootloader mode.  Bootloader is a mode where the devices is exposed and can receive code and special commands.
If something, like the code, is causing the device to crash, such as I had, then the desired USB/serial port is not available.
The Reset Switch
The reset switch may also be some pins to be shorted.  The manual talks about high/low and resistance.  Generally I have found you just short the damn thing, milage may vary. I used the button.
Per the instructions you can double tab the button and then I seem to trail off and not really absorb the rest. Eventually I got the pattern.
The Pattern
If you double click the reset button the device goes into boot loader for 8 seconds.
Find a short "hello world" sketch and have it ready.
Double tap the reset button and immediately upload the sketch.

That may not work...

When uploading a sketch the beginning of the upload is the compile step.  This must complete before there is anything to ship to the device.
I had to click upload and then double tap and get the timing right.  Eventually I would use the shortcut (CMD/CRTL + U).  The sketch takes and the device is back to normal.
Hope this helps someone - I needed the dummy version.


text:
Can I have two separated serial monitor for the same arduino board connected to PC?
I'd like to split serial communication into the two channels: 1) debug info, 2) application data.
There's only one Serial object to use.
However, maybe, there is an alternative way to print data separately, is there?
P.S. I use Nano and UNO.

There is the SoftwareSerial Library: https://www.arduino.cc/en/Reference/SoftwareSerial, https://www.arduino.cc/en/Tutorial/TwoPortReceive.

can you give more info on what device you are using, and what you are actually trying to accomplish

I specified boards I use and the purpose I'm pursuing.

@VE7JRO, Thanks for the answer. But how to see the output from two serial ports of the the same arduino board on the same computer?

In windows you need to open one instance via "run as administrator" and the other one as the standard user. This way the two instances don't know of each other and you can adjust the com port separately. Cheers

@JochenReitzig, it can be started twice with double click on a desktop icon. no need for "as asdministrator"

As Majenko mentioned in his answer, you can connect a USB to UART adaptor such as a PL2303HX to your Uno (cost is $0.70 CDN). Just connect the RX, TX, GND pins to your Arduino correctly and include the SoftwareSerial Library in your sketch.
Here is a simple test sketch which is almost identical to the "SoftwareSerialExample" that comes with the SoftwareSerial Library.
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup(){
  Serial.begin(9600);
  Serial.println("Print to Serial Monitor");
  mySerial.begin(9600);
  mySerial.println("Print to SoftwareSerial");
}

void loop(){
  if(mySerial.available()){
    Serial.write(mySerial.read());
  }
  if(Serial.available()){
    mySerial.write(Serial.read());
  }
}

If you want to have two Serial Monitors, start the IDE twice. Use your desktop shortcut or start menu entry to start the second instance of the IDE. In the second instance you can select a different port. It will not work for Upload of course, but when you open the Serial Monitor, it will work at the selected port.
Other option is to use some terminal program to see the output of the com port.
The other answers cover the fact that you need an USB to TTL Serial adapter to connect to USB and in sketch SoftwareSerial as your second serial interface or use some board with two or more hardware serial ports like the Mega on the picture.

spot on.  I have a device which uses a nodemcu & an Arduino nano and i monitor each on a separate instance of Arduino IDE

Not without adding more hardware, no.
You could add a usb to UART adapter and use software serial. Better would be to switch to a board that has a proper usb connection and a usb stack that supports multiple CDC/ACM instances, like a chipKIT board (Lenny, for instance).

Disclaimer: I designed the Lenny (though I only profit from it if you buy it from me) and I designed the usb stack specifically so you can have multiple instances of the different drivers.

one can actually use 2 separate USB ports, one for each device and run the IDE twice, as Juraj pointed out

@tonygil You mean like where I say "You could add a usb to UART adapter and use software serial."...?

You can add another channel with the SoftwareSerial library and an FTDI cable. The cable costs about US$17 in the US and is available here from Amazon, Sparkfun, and probably others. Internationally, I don't know. The SoftwareSerial library does have some limitations, most notably that it has to interrupts off while it's actually operating to get its baud rate right. But it does work and may be the simplest solution for you.

Depending on your software environment, the simplest thing may be to
send all the data multiplexed through the single serial port, then split
it into two channels at the other end. For that, you will need some sort
of multiplexing protocol. If all your data is text and line oriented,
this may be as simple as prefixing each line with "1" or "2" to select
the appropriate channel:
Serial.println("1This app data goes to stdout.");
Serial.println("2This diagnostic message goes to sterr.");

If you want to send arbitrary byte streams, you would instead use two
control characters for selecting the channels and an "escape" character
for when you want the control characters to be transmitted literally.
For convenience, you could encapsulate this logic into two separate
objects and implement stdout.println() and stderr.println().
Then on the computer side, you will have to write a program that reads
the serial port and splits the received bytes into two separate streams.
How you implement those streams is OS-dependent. On an Unixish system I
would probably use pipes, or pseudo-terminals if I needed bidirectional
communication.


text:
Watchdog on Arduino Nano does not recover
I'm trying to add a watchdog on an Arduino Nano, for my code, and I'm following the code in this manual exactly, but after the amount of time for not resetting the watchdog, it resets but does not reboot.
In the last paragraph it says that:

However, I could not find something similar in Optiboot bootloader (If
I'm wrong, correct me please!), used by Arduino UNO and other new
boards. It seems that they sacrificed this check for size. So, it is
possible that watchdog timer will be enabled after reset, so -  if you
set it's value too low, your board may never come out of bootloader
stage. So, to be always on the safe side, set watchdog to longer
periods (2S and more).

So I've tried for 8 s, but still same result.
What is wrong?
#include <avr/wdt.h>
int k=1;

void setup() {
  Serial.begin(9600);
  wdt_enable(WDTO_8S);
}

void loop() {
  //do stuff here
  k++;
  wdt_reset();
  Serial.println(1000 * k);
  delay(1000 * k);
}

Please describe "resets but does not reboot". What happens? What does not? Try section 11.8 of the Atmega328p datasheet which describes the operation modes of the watchdog timer. You may need some additional setup to get the result you want.

Please post the actual test code you are using. The linked page only shows code which should not reset unless "do stuff here" takes too long. (Edit your question to do this).

@NickGammon added

As @JRobert said, what do you mean by "it resets but does not reboot"? Do you mean the watchdog timer resets, or the processor resets? If the processor resets then it would reboot.

the "old" Nano bootloader doesn't clear the Watchdog flag and while the bootloader waits for the upload, the board resets.
flash the "new" bootloader to Nano
In IDE 1.8.6 you can select version of Nano in Tools menu. It is the 'new' bootloader if you select "Atmega328p" and 'old' if you select "Atmega328p (Old bootloader)". If you invoke "Burn bootloader" it will use the bootloader for the selected option.

Can you please refer ?

how to burn bootloader? you need a programmer or other Arduino. https://www.arduino.cc/en/Tutorial/ArduinoISP

where to get this "NEW" bootloader ?

I enhanced the answer

The complete process of burning a bootloader is described here: https://docs.arduino.cc/built-in-examples/arduino-isp/ArduinoISP . The answer above is a summary and assumes that a programmer is a,ready connected to the target "Nano".

This works on an Uno R3.
The sketch restarts every 4 seconds when wdt_reset() is commented out.
Please copy the code and try it.
  #include <avr/wdt.h>

  void setup() {
    pinMode(13,OUTPUT);
    digitalWrite(13,LOW);

    delay(50);
    digitalWrite(13,HIGH);    // flicker the LED to identify when setup() is running
    delay(50);
    digitalWrite(13,LOW);
    delay(50);
    digitalWrite(13,HIGH);
    delay(50);
    digitalWrite(13,LOW);
    delay(50);
    digitalWrite(13,HIGH);
    delay(50);
    digitalWrite(13,LOW);
    delay(50);

    wdt_enable(WDTO_4S);

  }
  void loop() {
    digitalWrite(13,HIGH);
    delay(500);
    digitalWrite(13,LOW);
    delay(500);
    //wdt_reset();
   }

hi- same affect... perhaps Uno and Nano behave not the same ?

@Guy.D: We still need to know what you see happening and what you expected would happen instead.

@JRobert I’ll describe what I see: code run ok until time that wdt does not get its reset ( which I do on purpose). After that leds on board start to flicker non stop, and data stop posting on serial monitor ( this part I call- reset ). Only after a power off - board is booting back up. If I wouldn’t power off- that flickering state would keep forever.

this makes no sense .... the code that i posted flickers the LEDs during setup(), but there is no serial I/O code ..... it appears that you are not loading the new sketch into the Arduino, just rerunning the old sketch

I got the WDT working in my Nano with the old bootloader using this code from an old post on Arduino Forum.
The code is added after the wdt_reset();
  //reset watchdog
  wdt_reset();
  //set up WDT interrupt
  WDTCSR = (1 << WDCE) | (1 << WDE);
  //Start watchdog timer with 4s prescaller
  WDTCSR = (1 << WDIE) | (1 << WDE) | (1 << WDP3) | (1 << WDP0);

the true problem are wdt intervals shorter than the time bootloader waits for upload

After that leds on board start to flicker non stop, and data stop
  posting on serial monitor

Definitely have a read of the datasheet for the '328p, section 11.8. There are several modes of operation - it can interrupt; reset; or both. Even if it resets, it doesn't reload your initial RAM data, so, for instance, line 2 int k=1; looks like an executable statement but is an initializer and has no effect at reset, and k retains its current value. There are probably other, similar, anomalies that happen when the WDT fires.
You probably don't need to understand the WDT down to its last control-bit but definitely make sure you're using it in the mode you want to be in. It will probably be handy during your testing to have a tiny sketch that just disables the watchdog so you can quickly get your Arduino back for the next test.

The problem may be that the 328 defaults to a Watchdog time of 16mS after a reset-
WDP3 = 0, WDP2 = 0, WDP1 = 0, WDP0 = 0 so when it resets and starts your program from the beginning of your code, the program never gets very far.  I made a very short recovery program that just invokes noInterrupts(); and load it straight after a power off / on. Then you can load a new program that doesn't use the watchdog.


text:
Won't break out of for loop
I'm new to Arduino and I'm trying to use PWM to generate a tone through a buzzer. I've created a for loop, however, the for loop doesn't seem to break when the variable ms is < 1000000.
int second = 1000000; //1 second in microseconds

void setup() {
  pinMode(3, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  //Play middle C for 1 second
  for(int ms=0; ms <= second; ms+=3830)
  {
    digitalWrite(3, HIGH);
    delayMicroseconds(1915);
    digitalWrite(3, LOW);
    delayMicroseconds(1915);
    Serial.println(ms);
  }
  Serial.write("Finished C");
}

We can see on the serial output that the value of ms exceeds 1000000 but the for loop is still going. Can anyone see where I am going wrong?

An int can't hold 1000000.  It is a signed 16-bit variable, which means it can only hold between -32768 and +32767.
To store larger numbers you need to use long, or unsigned long which are signed and unsigned 32-bit variables.

Just one more question for my own understanding. Why on the serial output do values > 32767 display in the serial output?

ms may have been promoted to long since println expects long. However second will hold -31072. When you have the wrong variable type strange things can happen.

Ok thanks, at least I know now that it's important to think about what type a variable is.

In addition to Majenko's answer (an int on this platform can't hold a number greater than 32767) you have a second problem. You are evidently trying to make a middle C tone (261.6 Hz) by toggling a pin with a period of 1/261.6 seconds. However your Serial.println takes time. In particular at 9600 baud each byte you send will take 1/960 of a second (because there are 8 data bits, one start bit and one stop bit per byte), and assuming the number you are printing is roughly 4 digits, plus carriage return plus linefeed, you are sending 6 bytes for each time around the loop.
6 bytes of 1/960 (1042 µs) would be 6252 µs which completely dwarves your delays of 1915 µs.
Whenever you try to do things with timing loops you need to take account that everything in the loop takes time, not just your delayMicroseconds statements.


text:
Unstable analog sensor readout
I have the Arduino Uno (non-original replica) board, general SPI lcd, and GUVA-S12SD analog UV sensor module.
The board (powered via USB) reads the data from the analog pin 0, converts it to voltage (multiplying the readout by (5.0/1023.0) ) and prints out to the LCD.
Being illuminated with an UV-flashlight, the sensor gives unstable readouts varying for around 0.03-0.04 V each readout cycle. I am a complete noob in electronics, so I want to ask how can I check where the problem is? Is this my error in wiring, faulty module, just normal behaviour of an analog sensor or something else?
Mine sensor module isn't from Adafriut and looks a bit different, the one in the diagram is just to show the general wiring.
Thanks!
(Sensor module description: https://www.electroschematics.com/11509/guva-s12sd-uv-sensor-module-circuit/ )
The code of the sketch is:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
int sensorValue;
float sensorVoltage;
LiquidCrystal_I2C lcd(0x27,16,2);  // display setup
void setup() {
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("");
}

void loop() {
  sensorValue = analogRead(A0);
  sensorVoltage = sensorValue * (5.0 / 1023.0);
  lcd.setCursor(0, 0);
  lcd.print(sensorVoltage/0.1); // rather low voltage is expected
  delay(1000);
}

Update: I tried to measure the output with a multimeter (as Vasekdvor suggested in answers) and it showed very similar results: continuous 0.04-0.07 V oscillations. Their magnitude seems to grow along with the intensivity of the illumination.
With sensor being dark, multimeter shows 0.006 V (changing to 0.007 V occasionally) between A0 pin and the ground.

post your code in the question so we can check that too

The code is added to the question.

I know you said that your sensor looked different from the fritzing one in the diagram..... but are you sure it’s connected with the output to A5?    Most of these I see for sale have the output on the leftmost pin.

Try to measure an output of this sensor with an multimeter, not with an arduino. According to your posted link of description of this sensor, there should be something between 0V to 1V. That way we can find out, if there is an problem with an sensor or in code.

Yes, exactly, mine sensor has output on the outer pin instead of the middle one, and that pin is connected to Arduino's A0 analog in.

Thanks for the idea! I'll check the output as soon as I get a multimeter, tomorrow or a day later maybe.
I suppose the sensor can give a bit more than 1V under the strong UV light, but with the atmosphere-filtered Sun as the UV source it shouldn't go beyond that.

yes, you are right, it should give 1170 mV and more, if there is a really strong UV light.

Keep in mind that it is unlikely your flashlight puts out UV light.  If you can see with your eyes the light coming from your flashlight then it's not UV.  The purple flashlights that look similar to a black light are typically putting out near-UV and your sensor may not be very sensitive to this wavelength.  Test your sensor out in direct sunlight.

I tried to measure the output with a multimeter, and it showed very similar results: continuous 0.04-0.07 V oscillations. I've added a little update to my question post.

The sensor reads approximately 1.7 V with the flashlight being around 40cm away, so I assume it gives enough of the light within the sensitivity spectrum of the sensor. I'll try the direct sunlight of course, but there's rather cloudy and dark weather outside now.

@NickL so there is probably something wrong with your chip.

@Greenonline I know that, but due to restrictions on StackExchange (not enough rank), i didn't have a permision to write a comment below his post, now i have, so if you want to do that change your (StackExchange) policy.

the sensor gives unstable readouts varying for around 0.03-0.04 V each
  readout cycle

If your sensor outputs 0 to 5V and you're only getting 0.03 to 0.04 variance then I would say that it's working pretty well.  You can get a more stable output by averaging several readings before printing them.
Additionally, for even more stable readings consider powering your Audrino from a battery.  USB power can induce a considerable amount of noise if it's coming from a PC or Laptop USB port.  Also, there is a low noise mode where you can put the Arduino to sleep during your ADC reading (and it wakes up afterwards) which helps a lot with ADC noise reduction.

Thanks for the averaging idea!
Arduino was powered by usb phone charger (Samsung travel adapter, 5V 2A output) for one of the tests and by the laptop USB port for the rest of the attempts. Should I try powering it by a powerbank, or should I take ordinary batteries without any charge/discharge controllers?

Batteries will likely give you the quietest power source but if you have to go through a switching voltage regulator there will be some ripple on the 5V.  A travel adapter or PowerBank will likely be better than a PC's USB port.  The only way to tell for sure is to look at the 5V supply with an oscilloscope.  Linear voltage regulators have the lowest noise but at the cost of wasted power which can be concern for battery powered devices.

I've tried using powerbank to power the board, but nothing changed (at least visibly or measurable). Didn't find enough AA batteries to power arduino yet.
I think I'll just average the readings, the only concern is is the sensor itself ok and working more or less correctly.

After averaging 10 or 15 measurements the output looks pretty stable, so I think this is a nice solution, thanks!


text:
Broken Arduino Uno, works over USB but cannot take DC in
My Arduino Uno (r3) board seems to be broken. It can still be powered over USB, and can store/run code properly, but the DC power in system appears to be crippled. I'm not entirely sure what happened, but I was most likely being careless with the power in and the vin pin. I'm not sure what component(s) are broken, but when I plug in 12v into the barrel connector, the uno doesn't power on. I can read about 0.6 volts from the 5 volt pin, and at some other locations on the board. Besides the 0.6, the only other voltage I read is the 12 volt, although it is slightly lower than the power supply, which outputs about 12.2 volts. How can I go about fixing this? Or is it even worth it?

Most certainly the voltage regulator is broken. Maybe you shorted the 5V pin intermediately or you tried to draw too much current from it. Do you have a specific question?

What is the voltage of the vin pin? If it is near 0v, then the diode is blown, if it is near 12v then the voltage regulator is broken. A broken voltage regulator can leak current of have a shortcut, if you remove a broken voltage regulator then you can use the board with usb power.

As you have noticed, measuring voltages is the first step. Here's some voltages for you and what they mean if they aren't there. These are all assuming precisely 12V in through the barrel jack. They are in order of "priority" - start at the top and work down, the first one that fails is your culpret (i.e., the barrel jack feeds VIN through the diode, VIN feeds 5V through the 5V regulator, and 5V feeds 3.3V through the 3.3V regulator).

Roughly 11.4V on VIN - if it's not there the input protection diode has blown
5V on the 5V pin - if it's not there the 5V regulator has blown
3.3V on the 3.3V pin - if it's not there the 3.3V regulator has blown

Fixing it may be as simple as replacing the faulty component identified above - although they are all surface mount and some are more tricky to replace than others.  That said, if it is (as it sounds) the 5V regulator that has gone, that is one of the larger components (SOT-223) so should be eaiser to replace. Also it's dirt cheap - I get them for a few cents each in bulk.

It would appear to be the 5v regulator, thank you! This was super helpful


text:
Arduino Comms disrupted, prevents program loading (catch 22)
I have written some software which, when loaded onto an Arduino Micro, blocks communications for some reason. Lets stipulate that there is something wrong with it.
Using the Ardiono IDE on Windows 10, and (ex internet) pressing the board's reset button twice within 5 seconds of power-up, then (device manager) a comms port comes into existence for 2 seconds, presumably under control of the micro-controller's bootstrap program.
In the IDE, you can only select an existing comms port. As above, a comms port comes into existence for 2 seconds.
The download button causes compilation and downloading to the comms port - typically taking 8 seconds.
Thus, one can only replace the duff program by selecting the briefly available comms port, compiling and downloading to it, which takes longer that the port availability window.
And so replacing the duff code with anything is impossible. Have I missed something here? Does anyone have some "emergency" code that waits for a port to appear and immediately loads something innocuous?
BTW the Tags restriction is preventing me from using meaningful tags.

try this: In Preferences turn on verbose output for Upload. while the board tries to Upload and can't find the right port, reset the board. perhaps it changes the port back to the one set in Tools menu and upload starts

That was very interesting. I did as you said, it failed, but then a message with the Arduino infinity/dipole symbol turned up at the bottom of the screen, saying "download to use ...". I did so, let it run, and it then ran, finding the new  comms port

I would suggest:

Turn on verbose compilation in the IDE.
Set up as you have been with the right port selected and go to upload - it will fail as normal
Find the avrdude command in the verbose output and copy the full command and its parameters
Open a command prompt or terminal window and paste in the command you copied (but don't run it yet).
Press reset twice to trigger the serial port creation
Run the command you pasted. It should immediately start uploading and "fix" your problem.

Thanks for your response, as see my previous one. Running the new verbose download, everything worked immediately, and the operations looked very much as you described above. I think someone at Arduino sent me this code change, which was just the job. Thanks all!


text:
How to access a website running on my localhost(host/server) to Serial Monitor using ESP8266(Client)?
The following source code is from the official ESP8266 website(Explanation provided): https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/client-examples.html
This .ino code returns the html code of the server name mentioned in "const char* server" declaration, on to the Serial Monitor.
And Yes, this code perfectly returned the html codes of wwww.google.com, www.arduino.cc etc. But when I try it with my 'led blinking.html' I am unable to find any luck. I guess it is because the website should be hosted on a live server.
Other Details:
1. uC Board: Wemos D1 mini (An ESP8266 Variant)
2. I am using Xampp to run Apache server and MySQL
3. Wemos board is set up as a WiFiClient
#include <ESP8266WiFi.h>

const char* ssid = "xxxxx";
const char* password = "xxxxxxxx";

I have put the html,php code of the website in the directory : C:/xampp/htdocs/LED BLINKING/led blinking.html
IP Address of my Windows PC: 192.168.100.9
const char* server = "192.168.100.9/LED BLINKING/led blinking.html";

I tried with just "192.168.100.9"; too.
I also unblocked the windows firewall for my ApacheHTTP Server. Now I can view the webpage on my mobile with the URL: 192.168.100.9/LED BLINKING/led blinking.html.
void setup()
{
  Serial.begin(115200);
  Serial.println();

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
}

void loop()
{
  WiFiClient client;

  Serial.printf("\n[Connecting ...");
  if (client.connect(server, 80))
  {
    Serial.println("connected]");

    Serial.println("[Sending a request]");
    client.print(String("GET /") + " HTTP/1.1\r\n" +
                 "server: " + server + "\r\n" +
                 "Connection: close\r\n" +
                 "\r\n"
                );

   Serial.println("[Response:]");
    while (client.connected())
    {
      if (client.available())
      {
        String line = client.readStringUntil('\n');
        Serial.println(line);
      }
    }
    client.stop();
    Serial.println("\n[Disconnected]");
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  delay(5000);
}

The output on Serial Monitor is:
Connecting to ssid connected
[Connecting connection failed!]

Variable server is a hostname or IP address for TCP connection.
The /LED BLINKING/led blinking.html goes after HTTP GET. Now there is / and it worked for main page of servers.
You need
client.print(String("GET /LED%20BLINKING/led%20blinking.htm") + " HTTP/1.1\r\n" +
             "server: " + server + "\r\n" +
             "Connection: close\r\n" +
             "\r\n"
            );

and you must escape the space


text:
How can I connect multiple different sensors that uses the same pins?
I'm doing a project on Arduino Uno and it requires me to connect 3 different sensors together: Waveshare 2.9 E-paper, MFRC522 RFID Reader and a ESP8266 wifi module. problem is, The e-paper and RFID uses the same multiple digital pins. How can I connect all of them together in a beardboard?
Edit:
The E-Paper uses:
e-paper 3V3 -> Arduino 3V3
e-paper GND -> Arduino GND
e-paper DIN -> Arduino D11
e-paper CLK -> Arduino D13
e-paper CS -> Arduino D10
e-paper DC -> Arduino D9
e-paper RST -> Arduino D8
e-paper BUSY -> Arduino D7

The rfid uses:
SDA --> Digital 10
SCK --> Digital 13
MOSI --> Digital 11
MISO --> Digital 12
IRQ --> unconnected
GND --> GND
RST --> Digital 9
3.3V -->3.3V

The wifi uses:
GND --> GND
VIN --> 3.3v
Enable --> 3.3V
TX --> RX
RX --> TX

I'm very new to electronics so i'm sorry if something does not make sense
I'm using library, code and instructions from this 3 websites:
E-paper ( Waveshare 2.9 E-paper): https://www.instructables.com/id/Getting-Started-With-E-Paper-Display-Modules/
RFID (MFRC522 RFID Reader): https://randomnerdtutorials.com/security-access-using-mfrc522-rfid-reader-with-arduino/
Wi-Fi (ESP8266 wifi module): https://www.hackster.io/jeffpar0721/add-wifi-to-arduino-uno-663b9e
Thanks!

Such a question cannot be answered in general, but only with full specifics of how each pin is being used.  In many cases you will be able to relocate one function to a different pin, or the pins are being used in ways (such as SPI or I2C busses) which are already designed to be shared.  But without full details this is unanswerable and will have to be closed.

@Arthane, you can use the preview under your post to check formatting before submission. Use the {} code tags to format as in my tidy-up. I didn't fix your "beardboard" as it looks interesting.

The normal procedure is to first check which interfaces you need and then select a suitable CPU. Blindly grabbing an Arduino (that name itself is anathema on this site) is not the right way.

You'll need to modify the code, most likely.

You are lucky, the two devices creating the conflict both use the same pins because they both use the same interface, SPI to be precise, which allows to have multiple devices connected using different Chip Select pins, abbreviated as CS.
Of the two libraries, one allows to define the CS pin (RFID module), the other has it hardcoded (ePaper). So, when declaring your RFID library, you should use the constructor that allows to define the chip select pin:
void PCD_Init(byte chipSelectPin, byte resetPowerDownPin);

This means in your code you should use:
PCD_Init(6,8) rfid;

The above also implies one of your RFID connections must be changed: what was previously SDA --> Digital 10 is now going to be SDA --> Digital 6. Please note I picked pin 6 randomly among the pins that seem unused by your code, but any other unused pin will be a good choice, including analog pins.
BTW, the web page about the RFID module uses a pin naming which causes a lot of confusion because it mixes up SDA with MISO and MOSI: those names are used in two different types of interface, the former is called I2C or TWI, the latter SPI. On Arduino the two interfaces share a couple of pins, but they are very different in many different ways.
In your case both modules use SPI, which is good for you.


text:
ESP8266 WebServer not responding (connection time out)
My web server running on ESP8266, stop working after while.
I cannot connect to it - browser shows connection time out error.
No error, no crash... nothing.
Have you any idea how to fix it?
My code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ESP8266mDNS.h>
#include <FS.h>

#include "console.h"
#include "tictactoe.h"
#include "main.h"

#define L_GREEN 2
#define L_YELLOW 0
#define L_ORANGE 4
#define L_RED 5

const char* ssid = "***";
const char* password = "***";

int requests = 0;
String IPs = "[";

IPAddress staticIP86_10(192,168,0,115);
IPAddress gateway86_10(192,168,0,1);
IPAddress subnet86_10(255,255,255,0);

ESP8266WebServer server(80); //Server on port 80

String getContentType(String filename);
bool handleFileRead(String path);

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "1.sk.pool.ntp.org", 60*60, 60*1000);

//===============================================================
// Game Data
//===============================================================

/*String ticPlayer1 = "";
String ticPlayer2 = "";
String ticClick = "-1";
int ticReset = 0;*/

//===============================================================
// LEDs
//===============================================================
void LEDblink(int pin) {
  requests++;
  digitalWrite(pin, HIGH);
  delay(10);
  digitalWrite(pin, LOW);
}
//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleNotFound(){
  if(server.uri().indexOf(".php")>-1) {
    Serial.print("404 "+server.uri()+": "+server.client().remoteIP().toString()+" (Blocked)\n");
    return;
  }
  Serial.print("404 "+server.uri()+": "+server.client().remoteIP().toString()+"\n");
  String s = HTML_Pro_notFound;
  server.send(404, "text/html", s);

  LEDblink(L_YELLOW);
}
void sendFile(String path, String type) {
  Serial.print(server.client().remoteIP().toString()+": "+server.uri()+"\n");
  if (SPIFFS.exists(path)) {                            // If the file exists
    File file = SPIFFS.open(path, "r");                 // Open it
    size_t sent = server.streamFile(file, type);        // And send it to the client
    file.close();                                       // Then close the file again
  }
}
//===============================================================
void reboot() {
 server.send(200, "text/plain", "true");
 LEDblink(L_RED);
 digitalWrite(15, LOW);
 digitalWrite(0, HIGH);
 digitalWrite(2, HIGH);
 ESP.restart();
}
void admin() {
 if(!server.hasArg("user") || !server.hasArg("pass") || server.arg("user") == NULL || server.arg("pass") == NULL || server.arg("request")=="login") {
    String expire = "";
    if(server.arg("remember")=="on"){expire="30";}else{expire="0";}
    server.send(200, "text/html", "<!DOCTYPE html><meta charset='UTF-8'><title>ProTools.tk | Please Wait</title><link rel='stylesheet' type='text/css' href='/main.css'><form class='center' action='/admin' method='post' style='display:none;'><input class='a' type='text' name='user'><input class='a' type='password' name='pass'><input class='a' type='text' name='request' value='panel'><button class='a' type='submit'></button></form>

");
    //server.sendHeader("Location","/login");
    //server.send(303);
 }
 if((server.arg("user")=="***")&&(server.arg("pass")=="***")) {
   if(server.arg("request")=="data") {
     String c = "{\"uptime\":"+String(millis(),DEC)+",\"req\":"+String(requests)+",\"ips\":"+IPs+"]}";
     server.send(200, "text/json", c);
   }
   else if(server.arg("request")=="panel") {
     server.send(200, "text/plain", "Admin panel here");
   }
   else {
    server.send(400, "text/plain", "400 Bad Request");
   }
 }
 else{
   server.sendHeader("Location","/login");
   server.send(303);
 }
 LEDblink(L_RED);
}
void console() {
 Serial.print("Console :"+server.client().remoteIP().toString()+"\n");
 String s = HTML_console;
 server.send(200, "text/html", s);
 LEDblink(L_ORANGE);
}

//===============================================================
/*void minesPage() {
 String s = HTML_mines;
 server.send(200, "text/html", s);
 LEDblink(L_YELLOW);
}
void minesScript() {
 String s = JS_mines;
 server.send(200, "text/javascript", s);
 LEDblink(L_YELLOW);
}
void minesStyle() {
 String s = CSS_mines;
 server.send(200, "text/css", s);
 LEDblink(L_YELLOW);
}*/

//===============================================================

/*void ticPage() {
 String s = HTML_tictactoe;
 server.send(200, "text/html", s);
 LEDblink(L_YELLOW);
}
void ticScript() {
 String s = JS_tictactoe;
 server.send(200, "text/javascript", s);
 LEDblink(L_YELLOW);
}
void ticStyle() {
 String s = CSS_tictactoe;
 server.send(200, "text/css", s);
 LEDblink(L_YELLOW);
}

void ticData() {
 Serial.print("TicTacToe: "+server.client().remoteIP().toString()+"\n");
 String user = server.arg("user");
 String clicked = server.arg("click");
 String request = server.arg("request");
 String leave = server.arg("leave");
 if(user != "") {
  if(user == "get") {
   server.send(200, "text/plain", "{\"Player1\":\""+ticPlayer1+"\", \"Player2\":\""+ticPlayer2+"\"}");
  }
  else if(ticPlayer1 == "") {
   ticPlayer1 = user;
   server.send(200, "text/plain", "player1");
  }
  else if(ticPlayer2 == "") {
   ticPlayer2 = user;
   server.send(200, "text/plain", "player2");
  }
  else {
   server.send(200, "text/plain", "Full");
  }
  if(ticPlayer1 != "" && ticPlayer2 != "") {
   ticClick = "0";
  }
  digitalWrite(L_ORANGE,HIGH);
  delay(500);
  digitalWrite(L_ORANGE,LOW);
 }
 else if(leave != "") {
  if(leave == ticPlayer1) {
   ticPlayer1 = "";
  }
  else if(leave == ticPlayer2) {
   ticPlayer2 = "";
  }
  ticClick = "-1";
  server.send(200, "text/plain", leave+" left");
 }
 else if(clicked != "") {
  ticClick = clicked;
  server.send(200, "text/plain", "OK: "+ticClick);
 }
 else if(request != "") {
  if(request == "checkClicked") {
   server.send(200, "text/plain", ticClick);
  }
  if(request == "reset") {
   ticReset++;
   if(ticReset == 2) {
    ticPlayer1 = "";
    ticPlayer2 = "";
    ticClick = "-1";
    ticReset = 0;
    server.send(200, "text/plain", "Reseted");
   }
   else {
    server.send(200, "text/plain", "Verification required");
   }
  }
 }
 LEDblink(L_YELLOW);
}*/
//==============================================================
//                  SETUP
//==============================================================
void setup(void){
  Serial.begin(9600);

  //Onboard LED port Direction output
  pinMode(L_GREEN,OUTPUT);
  pinMode(L_YELLOW,OUTPUT);
  pinMode(L_ORANGE,OUTPUT);
  pinMode(L_RED,OUTPUT);

  digitalWrite(L_RED, HIGH);

  WiFi.hostname("ESP8266");

  WiFi.begin(ssid, password);     //Connect to your WiFi router

  MDNS.begin("ESP8266");
  MDNS.addService("http", "tcp", 80);

  digitalWrite(L_RED, LOW);
  // Wait for connection
  digitalWrite(L_ORANGE, HIGH);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  digitalWrite(L_ORANGE, LOW);
  digitalWrite(L_YELLOW, HIGH);

  WiFi.config(staticIP86_10, gateway86_10, subnet86_10);

  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP

  SPIFFS.begin();

  server.on("/", []() {                                          // root
    sendFile("/page.html", "text/html");
    LEDblink(L_YELLOW);
  });
  server.on("/main.css", []() {                                  // main.css
    sendFile("/main.css", "text/css");
    LEDblink(L_ORANGE);
  });
  server.on("/page.css", []() {                                  // page.css
    sendFile("/page.css", "text/css");
    LEDblink(L_ORANGE);
  });
  server.on("/page.js", []() {                                   // page.js
    sendFile("/page.js", "text/javascript");
    String ip = server.client().remoteIP().toString();
    if(IPs=="["){
      IPs+="{\"time\":"+String(timeClient.getEpochTime(),DEC)+",\"ip\":\""+ip+"\"}";
    }else{
      IPs+=",{\"time\":"+String(timeClient.getEpochTime(),DEC)+",\"ip\":\""+ip+"\"}";
    }
    LEDblink(L_YELLOW);
  });
  server.on("/login/style.css", []() {                           // login/style.css
    sendFile("/login/style.css", "text/css");
    LEDblink(L_ORANGE);
  });
  server.on("/cookies.js", []() {                                // cookies.js
    sendFile("/cookies.js", "text/javascript");
    LEDblink(L_ORANGE);
  });

  server.on("/translator", []() {                                // translator
    sendFile("/translator/page.html", "text/html");
    LEDblink(L_ORANGE);
  });
  server.on("/translator/style.css", []() {                      // translator/style.css
    sendFile("/translator/style.css", "text/css");
    LEDblink(L_ORANGE);
  });
  server.on("/translator/script.js", []() {                      // translator/script.js
    sendFile("/translator/script.js", "text/javascript");
    LEDblink(L_ORANGE);
  });

  server.on("/login", []() {                                     // login
    sendFile("/login/page.html", "text/html");
    LEDblink(L_ORANGE);
  });
  server.on("/admin", admin);
  server.on("/reboot", reboot);
  server.on("/console", console);

  /*server.on("/minesweeper", minesPage);
  server.on("/minesweeper/script.js", minesScript);
  server.on("/minesweeper/style.css", minesStyle);

  server.on("/tictactoe", ticPage);
  server.on("/tictactoe/script.js", ticScript);
  server.on("/tictactoe/style.css", ticStyle);
  server.on("/tictactoe/data", ticData);*/

  server.onNotFound(handleNotFound);

  server.begin();                  //Start server
  timeClient.begin();
  Serial.println("HTTP server started");
  digitalWrite(L_YELLOW, LOW);
  digitalWrite(L_GREEN, HIGH);
}
//==============================================================
//                     LOOP
//==============================================================
void loop(void){
  timeClient.update();
  server.handleClient();          //Handle client requests
}

what version of the esp8266 arduino package you use?

hmm... I am not sure what version do you mean but in Arduino Board Manager I have installed ESP8266 of version 2.0.0 Please specify more where I can find that version if this is not what are you want.

What mime type is text/plane? Are you trying to transfer an aircraft?

use the latest version 2.4.2

@Majenko oops :D thanks for warning! I wrote it wrong and copy it to whole code, but its works good xD

@Juraj Its looks like it working. Thanks!

have you tried resetting your esp8266 ?

Use the latest version of Arduino esp8266 core package (2.4.2 or higher).


text:
TinyGPS doesn't give longitude latitude and other data
I'm trying to get GPS coordinates using TinyGPS. But it keeps printing ********* for the data fields. Any idea on how to get this working?. Here is what the serial monitor looks like.
Here is my code
#include <SoftwareSerial.h>

#include <TinyGPS.h>

/* This sample code demonstrates the normal use of a TinyGPS object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/

TinyGPS gps;
SoftwareSerial ss(1, 0);

static void smartdelay(unsigned long ms);
static void print_float(float val, float invalid, int len, int prec);
static void print_int(unsigned long val, unsigned long invalid, int len);
static void print_date(TinyGPS &gps);
static void print_str(const char *str, int len);

void setup()
{
  Serial.begin(115200);

  Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
  Serial.println("by Mikal Hart");
  Serial.println();
  Serial.println("Sats HDOP Latitude  Longitude  Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
  Serial.println("          (deg)     (deg)      Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
  Serial.println("-------------------------------------------------------------------------------------------------------------------------------------");

  ss.begin(4800);
}

void loop()
{
  float flat, flon;
  unsigned long age, date, time, chars = 0;
  unsigned short sentences = 0, failed = 0;
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

  print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
  print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
  gps.f_get_position(&flat, &flon, &age);
  print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 10, 6);
  print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 11, 6);
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  print_date(gps);
  print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
  print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
  print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
  print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
  print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);

  gps.stats(&chars, &sentences, &failed);
  print_int(chars, 0xFFFFFFFF, 6);
  print_int(sentences, 0xFFFFFFFF, 10);
  print_int(failed, 0xFFFFFFFF, 9);
  Serial.println();

  smartdelay(1000);
}

static void smartdelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

static void print_float(float val, float invalid, int len, int prec)
{
  if (val == invalid)
  {
    while (len-- > 1)
      Serial.print('*');
    Serial.print(' ');
  }
  else
  {
    Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1); // . and -
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
      Serial.print(' ');
  }
  smartdelay(0);
}

static void print_int(unsigned long val, unsigned long invalid, int len)
{
  char sz[32];
  if (val == invalid)
    strcpy(sz, "*******");
  else
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  smartdelay(0);
}

static void print_date(TinyGPS &gps)
{
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned long age;
  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  if (age == TinyGPS::GPS_INVALID_AGE)
    Serial.print("********** ******** ");
  else
  {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ",
        month, day, year, hour, minute, second);
    Serial.print(sz);
  }
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  smartdelay(0);
}

static void print_str(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
  smartdelay(0);
}

Looks like you have no signal or it hasn't locked on to the satellites yet. It can take a long time. How long have you waited? Is your antenna indoors?

why don't you simply print the raw serial data that is coming from the GPS module ...... use the above sketch only after the GPS module starts to send valid data

#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <SPI.h>

float lattitude,longitude; // create variable for latitude and longitude object
SoftwareSerial gpsSerial(8,9);//rx,tx
TinyGPSPlus gps;// create gps object

void setup(){
    Serial.begin(9600); // connect serial
    gpsSerial.begin(9600); // connect gps sensor
    delay(1000);
}

void loop(){

  while(1)
  {
   while (gpsSerial.available() > 0)
   { gps.encode(gpsSerial.read()); }

      if (gps.location.isUpdated())
      {
       lattitude=gps.location.lat();
       longitude=gps.location.lng();
       break;
      }

 }
   Serial.print("LATTITUDE="); Serial.println(lattitude,6);
   Serial.print("LONGITUDE="); Serial.println(longitude,6);
   delay(1000);
}

I managed to get it working using the following library TinyGPS++.h

From the description:
It requires the use of SoftwareSerial, and assumes that you have a
4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
But you are using Pin0 and Pin 1, as shown in your code:
SoftwareSerial ss(1, 0);
given that pin0 and pin one are hard Tx and Rx may create problems.
to check if the GPS is receiving anything use the BareMinimum sketch:
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
//Remember that Tx connects to Tx and Rx to Rx
that will show the NMEA string in the serial monitor.
(you can see a video about it, search for:"GPS Module with Arduino- Ublox NEO-6M"
Note:
in TinyGPS the Rx connects to Tx and Tx connects to Rx...
In case you use Softwareserial.h with Arduino Mega  you may have issues as not all pins can Rx (receive)... please check:
https://www.arduino.cc/en/Reference/SoftwareSerial
for NEO-6M the seed should be 9600baud, not 4800 as shown in the sketch, please check page 11 on:
https://www.u-blox.com/sites/default/files/products/documents/NEO-6_DataSheet_%28GPS.G6-HW-09005%29.pdf
Also change Serial.begin(115200); to 9600  so they are in sync.


text:
Servo can be moved only in steps of couple degree
I have Feetech FS5323M servo, with Sweep example code from Arduino site, it works fine, it rotates from 0 to 180 degree and back as expected.
The problem comes when I try to set servo position. I've added a simple servo.write(90); in setup, to reset servo position, but it didn't work (writeMicroseconds(1500); also failed).
After digging a little bit, I've discovered that I can rotate the servo only by a couple of degrees from its current physical position.
If the servo is at 140 degrees, I can move it back and forth only up to 7 degrees, value bigger than this will result in servo staying at its current position. So if I want to move it to 180 degrees I have to make a loop and go to this position in steps of 1-7 degrees (with delay = 15 * degree).
I attached external 2A power to the circuit and connected the grounds. It didn't solve the problem. The circuit is very simple, just servo connected to pin 3, without anything else. I also tried to add a 300uF capacitor between power and ground.
Edit 1:
I've tested pin 9 and 10 and the same happens. Sadly I have no way to test it on any other board because I have only one, same goes for the servo. I uploaded sweep example with the step size of 10, the servo didn't move or even twitched. I tried it both with a delay of 15 as well as 150.
Edit 2:
I've tested the program with only one servo.write(90); statement, but the issue hasn't been resolved. I tried it in setup and later in loop, in both programs there was only one write statement.

Quite interesting, does it happen on multiple Arduino boards (or other pins?) and does it happen on other servo's (of same and different type) as well?

start with the sweep example ..... modify the step size to 10 and upload  the new code ..... does it still fail?

The problem comes when I try to set servo position. I've added a
  simple servo.write(90); in setup, to reset servo position, but it
  didn't work

Understand that the method "setup()" in the Arduino paradigm is only run once after power up or reset.  Any code in "setup()" which positions the servo will immediately get over written by the code that positions the servo in the "loop()" method.  Likely this happens so quickly that the servo will not even react to the line "servo.write(90);".

Your servo should be powered separately from the Arduino as it draws 150mA just running and its stall current is well over an amp, according to the specs on this page. If you're powering it from the Arduino, it is quite likely that it drags the Arduino's supply voltage down enough to shut down the processor, but you may be getting away with it for very short moves.


text:
How to burn bootloader into arduino uno without using another arduino
I need to bootload my Uno board but I do not have another Arduino at my disposal so how do I bootload without another Arduino board

with AVR programmer

Sorry, I am new to this will you mind explaining further or may provide a link to relevant video/document for the procedure @Juraj

perhaps you should explain why do you need to 'bootload'

There are 3 main options how to write bootloader or program to AVR over ISP.

dedicated AVR programmer or Arduino ISP programmer
other Arduino with Arduino as ISP sketch or similar
parallel port of a computer

The USBTinyISP programmer attaches to your computer's USB port and uses the 6-pin ICSP port on your Arduino to program it.  It can program both bootloaders and sketches.  It can be purchased for less than $10 from Amazon or Ebay.
USBTinyISP programmer


text:
Arduino write to memory and self shut down (over MOSFET) - An idea help
i would like to ask you for help with design of an circuit.
I have and atmega328p, with detection for voltage on its Vin (Vcc).
I have made and voltage divider and its output i connected to Analog Pin. And i would like to, if an voltage decrease under an certain level (4.5V), to shutdown itself (atmega328p).
As i said the voltage detection is no problem (there is an voltage divider), programing it is as well no problem, but i though that i program it like this:

Detect voltage on analog pin A0, if the voltage is less than certain
  level (4.5V), write to memory and send to digital pin 3 an "LOW" (0)
  logical state.

This will turn the mosfet off and the atmega will loose its ground (GND) and its shuts down, but i have there an pull-up resistor which when the atmega shutsdown takes its lead an set Gate at MOSFET to high (transistor will turn on) and atmega turns on, then it shuts down and this will do the infinite cycling until there's no power to turn on atmega.
I want to use an Supercapacitor (2.2F 5.5V) to power it when the main input is lost and to give an atmega a time to write to memory and steadily turns off.
I am adding an schematics to better look at the problem.

I know that there is no crystal and capacitors and the other things to make it reliable and fully functional, but this is not a subject of this question.Its an first sketch, which is not completed.
I know some ICs that can detect Voltage and turn its output to some logical state (1 or 0), like an MAX809 (803 or 810) and so on and of course this is my backup plan, but i want to ask you, if you have any great idea to make this without any special ICs and more easily? I also thought about some OPamp or thyristor maybe, i don't know......
Can you help me with an idea or better with an schematics how to do it ? Thanks.

You should be using a p channel MOSFET and switching the power not the ground. When I get home I'll draw you a schematic

@Majenko Thank you, i appreciate that, but i have already thought about that and i think it will be the same situation but with all logic states reversed. If i think right then at the p channel mosfet, when there is high state on base the fet is OFF and vice versa. So if i during the running of atmega send LOW to base, the transistor is ON a everything is good, but when i want to shutdown atmega, atmega will send HIGH to base, transistor is OFF and the pull up resistor will stick it HIGH (until cap will discharge), but when the power is recovered resistor keeps it HIGH and atmega wont start.

if i use the pull-down instead of pull up, then when there is a power transistor is pulled down by resistor and its ON (good). When i want to turn transistor OFF, atmega will send HIGH to base of transistor and transistor will turn OFF (good), but when atmega dies, there will be no more HIGH at transistor base and the pull down resistor will turn transistor ON, and we have the same cycle as with the current schematics.
Sorry i use BASE, i know that MOSFET has a GATE, not BASE....

The trick is to have the arduino keep the system on, not tell it to turn off.

Just a question: are you using the arduino with a stable voltage reference or with VCC? if you use VCC as reference, and use a voltage divider to detect VCC, you will never see any change...

@frarugi87 yeah i know that, i forgot to mention it. I will be using internal analog reference 1.1V.

You should be using a P-channel MOSFET (which is set to be normally OFF with a pull-up resistor) and the Arduino is responsible for keeping it on:

simulate this circuit – Schematic created using CircuitLab
In this schematic M1 is normally off.  You press and hold SW1 and the Arduino gets power. The first thing it then does is turn on the GPIO. That turns M2 on, which in turn pulls the gate of M1 LOW turning it on. You can now release M1 and the Arduino will stay on.  When you want to turn off, just switch off the GPIO, turning off M2, which then allows R1 to pull the gate of M1 up again turning off the power.
This arrangement means:

You can control an incoming voltage higher than 5V (thanks to M2 doing the actual switching of the power MOSFET)
You get a soft-power switch to turn the power on
Current draw of the control circuit is basically the incoming voltage divided by the resistance of R1 (you can safely increase this if you want to reduce current draw - 1MΩ is fine).
You can have all the rest of the circuitry on the Arduino side of M1 so it has power removed when switched off (to prevent over-discharge of your batteries)
You are switching VCC, not GND (switching GND can cause all sorts of problems).

thanks, i got it, this works fine but i want to turn on arduino automaticaly (without switch) when the power is recovered. If we use a power supply (instead of battery).
When there is a power cut to the power supply, its all meant to be automatically saved the data to memory (for powering atmega for this time, there is an supercapacitor), power down atmega and when the power is recovered, automatically power up atmega again and read the data and so on .......

Sounds like you want a proper PMIC (or create one with a small MCU).  Maybe thrown in a little 8 pin ATTiny to manage the power...

Personally I usually use a PIC10F200-I/OT in this situation. Really small, really low power, really cheap, really hard to program for with only 256 words of instructions and 16 bytes of RAM. Ideal for something like a simple PMIC though...

i think that i can't avoid it (using PMIC or any other special IC). I thought if it can be possible to create it with simple design, but i am worried that i really need to use special IC to do this thing.

It is perfectly possible to create a circuit to do it, but that circuit would be considerably more complex with the addition of auto power on - and likely cost more than a PMIC or small low-power MCU. That's why PMICs exist - because they're cheaper and more convenient than trying to roll your own circuit.

OK, so i will stay at my backup plan, i will use MAX809 to switch ON/OFF the transistor, but as i look into it, i can use your schematic, that i will connect output of MAX809 to Gate of M1 Transistor. Then i will have the advantages you wrote, but in this situation i have to use MAX810 (which has output inverted compare to 809)

It would be easier to simply to power down the CPU using software once you're ready to shut down:
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
cli();
sleep_enable();
sleep_bod_disable();
sei();
sleep_cpu();

Thank you, i know, but i don't want to sleep it, i want to completely turn off supply.
I know that, you may ask why, but please just accept, that it will have to be like that.


text:
How do I make a stepper motor compass cross 360° to 0°?
I am building a wet compass for a flight simulator. I currently have a stepper motor functioning well with the simulator but at the point of crossing 360° to 0° the stepper does a full reverse 360° to get into position.
My question... can anyone please assist me in creating code that makes the linear cross from 360° to 0° work in both directions?
The simulator feeds a float val that is a degree out of 360° e.g. 172.13. My stepper has 4076 steps per full revolution. You will see the math in the code below. I am using the AccelStepper library.

void ProgOut(byte id, float val) {
switch (1) {
case 1:

if (val)
        { stepper1.moveTo(val * 11.3222222);         }

        stepper1.run();

break; }}

I have tried something like this:
void ProgOut(byte id, float val) {
switch (1) {
case 1:
if ( stepper1.distanceToGo () >= 4064){
          stepper1.moveTo(4076);
          stepper1.setCurrentPosition(0);
}
    else if (val)
        {

                stepper1.moveTo(val * 11.3222222);
        }

        stepper1.run();

break; }}

Your library doesn't understand that your stepper goes in a full circle.  See if it has some more primitive moves, like "home" and "move by n steps".  If it does you're in business, but you'll have to write your own "go to" function.  Alternately, dig through the documentation and see if it can be TOLD that it's dealing with a stepper that goes in a circle.  Again, if it does, you're in business.

have you tried to go to 361?

@TimWescott thanks Tim for the suggestion. I’ll go through it again to see what I have available

@jsotola the Val is feeding from the simulator software. So the maximum is actually 359.99. The Val after that would be 0

why are you involving data from the simulator during debugging? .... figure out how to step from 359 to 0 without moving a full circle ..... once that works, then use the simulator data again

Two options (for starters):

Use the move() class rather than the moveTo() class. This will allow you to do relative moves rather than absolute.
Use setCurrentPosition() (which sets the current position to zero) followed by moveTo() with a destination which is newPos - prevPos.

For either to work you will need to keep track of the current position of the needle.
To work out the relative move you will need to do some kink of modulo arithmetic but this will require some trickery to generate negative values for anti-clockwise moves.
// delta is the angular adjustment required.
delta = (currHeading + 180 - prevHeading) % 360 - 180;
setCurrentPosition();        // Zero the motor.
moveTo(delta);               // Move absolute from the new zero.
prevHeading = currHeading;   // Keep track.

The code assumes that you will never have to make a heading adjustment of more that 180° in one step.
Adding in the 180° before the modulo calculation and subtracting it again afterwards is a trick to allow negative results from the modulo arithmetic.

Also working on making a compass for flight simulator.
Hopefully the following code will help answer the question.
This is a working code that I have tested using serial monitor...
Note: For Flight Sim use, I did find that to get enough speed and smooth movement for the X27-168 gauge motor you need to use a stepper driver with microstepping rather than driving the X27-168 directly from the Nano I/O pins. You will have to adjust Max speed & acceleration and also edit the firmware for micro-stepping with using a stepper driver. Note: When using a stepper driver chip, you need to use the correct type for 6 step coil energising that the X27-168 stepper uses eg. AX1201728SG. Polulu (A4988) type stepper drivers use 8 steps coil energisation which will not move the gauge motor correctly - while it will move the gauge motor it creates a lot of noise and is not ideal.
I did have to add the following to get both left and right movements through North.
I used Movement rather than delta -
        if(Movement( < -180){Movement = Movement + 360;}
A single movement of 180 degrees defaults to CCW direction. however with Flight simulator data extraction, you shouldn't get a single movement of that amount.

/*Analog Compass Gauge.**
This uses an Arduino Nano processor that has four of its I/O's directly connected to an X27-168 geared stepper motor(Gauge indicator motor).
While it works, there should really be four sets of protection diodes across each of the I/O pins - diode to +5V & diode to 0V to eliminate spikes over 5v and below 0v on each I/O pin.
The X27-168 geared stepper motor has had the internal stop cut off on the main output shaft gear to allow full 360 degree movement.
A 55mm dia plastic round plate has been fitted to the X27-168 geared stepper motor 1mm diameter drive shaft and a printed label attached to the plate to show compass direction.
The plastic plate has a small Neodymium magnet (1mm dia x 2mm long) which can pass near a Hall Effect sensor (A3144)to provide a homing reference signal.
+5v,0v and I/O signal pin is connected directly to the Hall Effect sensor. The Nano internal I/O resistor is used to provide a pullup voltage for the Hall effect sensor signal.  The firmware uses the AccelStepper library.
PC Serial Monitor is used to enter new compass headings.
The X27-168 geared stepper motor is referred to as "stepper1" in the firmware.
*/
    #include "AccelStepper.h"
        AccelStepper Stepper1(AccelStepper::FULL4WIRE, 3, 4, 5, 6);   // Define stepper I/O pins (Using I/O pins connected directly to X27-168 Geared Stepper Motor)
       //AccelStepper Stepper1(AccelStepper::DRIVER, 2, 5); // Defines I/O pins when using a stepper driver e.g. AX1201728SG Quad driver chip -  Dir pin - Stepper pin
       #define Home_Sensor      2   // Pin 2 - Connected to Home Sensor - Hall Effect A3144- (0v when sensed)
       int Offset = -67;   // ****** Adjust this setting to ensure North facing when at Home Position(0)  ******
       int MaxSpeed = 80;   // ****** Adjust this setting for Max Speed of Stepper as to not miss steps    ******
       int Acceleration = 25   // ****** Adjust this setting for Acceleration of Stepper as to not miss steps ******
       int    Move_finished =   1;   // Used to check if move is completed
       long   Initial_Homing = -1;   // Used to Home Stepper at startup
       String InputString =    "";   // String to hold incoming data from serial monitor
       bool   StringComplete = false;   // Whether the string is complete
       int    LastHeading = 0;   // Register for Last heading
       int    NewHeading  = 0;   // Register for New heading
       int    Movement;   // Register for difference between Last and New heading
       void setup() {
       Serial.begin(9600);   // Start the Serial monitor at 9600 Baud
       pinMode(Home_Sensor, INPUT_PULLUP);   // Using internal pullup for Hall Effect sensor
       delay(5);   // Wait for stepper Driver wake up (if used)
       Stepper1.setMaxSpeed(MaxSpeed);   // Intial Homing Max Speed of Stepper (Slower to get better accuracy)
       Stepper1.setAcceleration(Acceleration );   // Intial Homing Acceleration of Stepper
       Serial.println("........ Homing Stepper ........");

       while (digitalRead(Home_Sensor)) {   // Make the Stepper1 move CW until the sensor is activated
       Stepper1.moveTo(Initial_Homing);   // Set the position to move to
       Initial_Homing--;   // Decrease by 1 for next move if needed
       Stepper1.run();   // Start moving stepper1
       delay(5);
       }
       Stepper1.setCurrentPosition(0);   // Set the current position as zero for now
       Initial_Homing=1;
       while (!digitalRead(Home_Sensor)) {   // Make the Stepper1 move CCW until the sensor is deactivated
       Stepper1.moveTo(Initial_Homing);
       Stepper1.run();
       Initial_Homing++;
       }
       //**** Should now be Homed to Magnet position which may not be North as per label. Below allows tuning to correct position of label ****
       Stepper1.setCurrentPosition(0);
       Stepper1.setMaxSpeed(MaxSpeed);   // Intial Homing Correction Max Speed of Stepper1
       Stepper1.setAcceleration(Acceleration );   // Intial Homing Correction Acceleration of Stepper1

       Stepper1.moveTo(Offset);   // To correct to have North as Home position
       while(Stepper1.distanceToGo() != 0){Stepper1.run();}   // Step to adjusted home position
       Stepper1.setCurrentPosition(0);   // Set Home position that will be used for all further movements..
       Serial.println("........ Homing Completed ........");
       Serial.println(" *** Enter Compass Heading 0 - 259 Degrees ***");
       // ---------   End of intial Homing Setup  ------------
       }
       void loop() {
       while (Serial.available() > 0) {   // Read serial input:
       int InChar = Serial.read();
       if (isDigit(InChar)) {InputString += (char)InChar;}   // Convert the incoming byte to a char and add it to the string
       if (InChar == '\n') {   // If you get a newline,
       NewHeading = (InputString.toInt());   // Convert input heading string to int value heading
       NewHeading = (NewHeading/2)*2;   // Eliminates 1 degree movements. Reduces movement errors with small movements
       Serial.print(NewHeading);

       if(NewHeading > 359 ||NewHeading < 0) {   // Displays error message if input is out of range
       NewHeading = LastHeading;   // No change due to incorrect data entered
       Serial.println("Input Error. Enter value between 0 - 259 Degrees ");
       }
       else { Serial.print("Heading "); Serial.print(NewHeading); Serial.println("...  Enter New Heading");

       }
       InputString = "";   // Clear the string for new input:
       Movement = ((NewHeading + 180 - LastHeading) % 360) - 180;   // Allows movement from North East to North West
       if(Movement < -180){Movement = Movement + 360;}   // Allows movement from North West to North East
       Stepper1.setCurrentPosition(0);   // Zero the motor.
       Stepper1.setMaxSpeed(MaxSpeed);   // Set Max Speed of Stepper1
       Stepper1.setAcceleration(Acceleration );   // Set Acceleration of Stepper1

       Stepper1.move(Movement*2);   // Set new move to position of Stepper1
       LastHeading = NewHeading;   // New heading now becomes last heading
       }
       }
       while(Stepper1.distanceToGo() != 0){Stepper1.run();   // Keep updating AccelStepper for current movement
       int XInChar = Serial.read();XInChar = Serial.read();}   // Keep clearing serial buffer- Only allow new heading input once movement finished.
       }


text:
How long does it takes for arduino to reach main()?
I am trying to emulate the behavior of a circuit using an Attiny85
This is the result I got so far:

In the picture above, D2 is VCC, D4, D5 and D6 are outputs of the circuit I am trying to emulate. D7 is the output of Attiny85
The code I am using is:
#define F_CPU 8000000L
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

int main() {

  DDRB = 0b00001000;

  PORTB = 0b00001000;
  _delay_ms(5);

  PORTB = 0b00000000;
  _delay_ms(5);
  PORTB = 0b00001000;
  _delay_ms(5);

  PORTB = 0b00000000;
  _delay_ms(5);

  _delay_ms(5);

  while(1)
  {
     PORTB = 0b00001000;
    _delay_ms(1);
     PORTB = 0b00000000;
    _delay_ms(1);
  }
    return 0;
}

According to this, it takes roughly 64ms from powerup until it actually run the main program.
Is there any reason for such a delay? How can I reduce it somehow (ideally to 20ms or less)?

do you use a bootloader or you program it over ISP?

Sorry, forgot to mention - yes, I programmed over a ISP (usbtiny) to make sure the bootloader is not active

The ATtiny85 has a built-in delay counter that keeps the MCU in reset
mode for some time after the power is applied. This seems to be intended
as a wait for the clock and power to be stabilized. The length of this
delay depends on your selected clock source, and is somewhat
configurable with the fuses.
According to your code, your MCU is clocked at 8 MHz. I assume you
are then using the internal RC oscillator as a clock source. If this is
the case, you have three choices for the startup delay:

20 CPU cycles
20 CPU cycles + 4 ms
20 CPU cycles + 64 ms

The latter is recommended if your power rises slowly, and is the default
configuration in which these MCUs are shipped. If you power level rises
fast, you may want to select a shorter delay by programming the SUT
fuses. See the datasheet for details (section System Clock and Clock
Options → Clock Sources → Calibrated Internal Oscillator).

You are right - my L fuse was programmed as 0xE1 (PLL clock, 64ms delay). I changed it to 0xD2 (Internal clock, 8Mhz, 4ms delay) and it worked


text:
How to connect NodeMCU to NRF24L01
I need to connect NodeMCU and NRF24L01. where I'm receiving data from another NRF24L01 Transmission. I managed to connect to a WiFi network but the data receiving is not taking place as expected. Here is my code
#include <SPI.h>
#include "RF24.h"
#include <ESP8266WiFi.h>

RF24 myRadio(7, 8);
const char* ssid = "******";
const char* password = "********";
struct package
{
    int id = 0;
    float longitude = 0.0;
    float latitude = 0.0;
    char text[100] = "empty";
};

byte addresses[][6] = {"0"};

typedef struct package Package;
Package data;

void setup()
{
    Serial.begin(115200);
    delay(1000);
    WiFi.begin(ssid, password);

    Serial.println();
    Serial.print("Connecting");
    while (WiFi.status() != WL_CONNECTED)
    {
     delay(500);
     Serial.print(".");
    }
    Serial.println("success!");
    Serial.print("IP Address is: ");
    Serial.println(WiFi.localIP());
    myRadio.begin();
    myRadio.setChannel(115);
    myRadio.setPALevel(RF24_PA_MAX);
    myRadio.setDataRate(RF24_250KBPS);
    myRadio.openReadingPipe(1, addresses[0]);
    myRadio.startListening();
}

void loop()
{

    if (myRadio.available())
    {
        while (myRadio.available())
        {
            myRadio.read(&data, sizeof(data));
        }
        Serial.print("\nPackage:");
        Serial.print(data.id);
        Serial.print("\n");
        Serial.println(data.longitude);
        Serial.println(data.latitude);
        Serial.println(data.text);
    }
}

Any idea on why this is not receiving data as expected?. This somehow managed to connect to my WIFI successfully. Here are my pin connection

7, 8 should be pin numbers? io 5 to io 11 are internal flash memory QIO SPI pins. if you connected the module to D7, D8, use D7, D8 constants

Hi @Juraj I used D7 and D8. i have updated my question with an image of the pin connection

The Dx pin labels on NodeMcu and Wemos/Lolin boards do not correspond to esp8266 internal io pin numbers. The pins_arduino.h file in core defines Dx constants which map internal io numbers to Dx labels.
Use RF24 myRadio(D7, D8);